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.
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
**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
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.
## 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
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
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 |
|---|---|
| **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 |
| **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 |
| **Result** | selects batch output messages |
| **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.
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)
if (!answer?.ok) return null
const body = await answer.json()
return (body.data || [])
.map((one) => one.name)
.find((n) => n.endsWith("_results"))
const board = (body.data || []).find((one) => one.name.endsWith("_results"))
if (!board) return null
// 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
@@ -144,8 +154,7 @@ async function captureRuns(page, dir) {
// 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.
if (results) {
const flow = results.replace(/_results$/, "")
await page.goto(`${APP_URL}/runs?flow=${flow}`, {
await page.goto(`${APP_URL}/runs?flow=${results.flow}`, {
waitUntil: "networkidle",
})
const ids = await page.getByTestId("run-link").evaluateAll((links) =>
@@ -155,7 +164,7 @@ async function captureRuns(page, dir) {
.filter(Boolean),
)
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",
})
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 { 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 { Button } from "@/components/ui/button"
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 control = useControl(node)
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 [loaded, setLoaded] = useState(false)
@@ -156,8 +156,8 @@ function Tile({
}) {
return (
<Link
to="/dashboards/$name"
params={{ name: dashboard.name }}
to="/dashboards/$id"
params={{ id: dashboard.id! }}
data-testid="home-dashboard-tile"
className={cn(
"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 (
<div className={container}>
{dashboards.map((dashboard) => (
<Tile key={dashboard.name} dashboard={dashboard} className={tile} />
<Tile key={dashboard.id} dashboard={dashboard} className={tile} />
))}
</div>
)
+11 -18
View File
@@ -159,46 +159,39 @@ export function GlobalSearch({
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) => {
onOpenChange(false)
setQuery("")
const id = entry.id ?? ""
switch (entry.category) {
case "flow":
return navigate({
to: "/flows/$flowName",
params: { flowName: entry.name },
})
return navigate({ to: "/flows/$flowId", params: { flowId: id } })
case "node":
return navigate({
to: "/flows/$flowName",
params: { flowName: entry.parent ?? "" },
to: "/flows/$flowId",
params: { flowId: id },
search: { node: entry.name },
})
// A setting is `<node>.<setting>`, and a node id has no dot.
case "setting":
return navigate({
to: "/flows/$flowName",
params: { flowName: entry.parent ?? "" },
to: "/flows/$flowId",
params: { flowId: id },
search: { node: entry.name.split(".")[0] },
})
// Arriving on the label's id does what clicking the label does.
case "input":
case "output":
return navigate({
to: "/flows/$flowName",
params: { flowName: entry.parent ?? "" },
to: "/flows/$flowId",
params: { flowId: id },
search: { node: `${entry.category}:${entry.name}` },
})
case "dashboard":
return navigate({
to: "/dashboards/$name",
params: { name: entry.name },
})
case "widget":
return navigate({
to: "/dashboards/$name",
params: { name: entry.parent ?? "" },
})
return navigate({ to: "/dashboards/$id", params: { id } })
case "device":
return navigate({ to: "/devices/$id", params: { id: entry.name } })
case "secret":
@@ -220,6 +220,8 @@ export function OverviewToolbar({
*
* @param done what the toast says happened to them, "Published"
* @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(
act: (name: string) => Promise<unknown>,
@@ -227,6 +229,7 @@ function useBatch(
done: string,
missed: string,
onDone: () => void,
labelOf: (name: string) => string = (name) => name,
) {
const { showSuccessToast, showErrorToast } = useCustomToast()
return useMutation({
@@ -236,7 +239,9 @@ function useBatch(
try {
await act(name)
} catch (err) {
failed.push(`${name} (${extractErrorMessage(err as ApiError)})`)
failed.push(
`${labelOf(name)} (${extractErrorMessage(err as ApiError)})`,
)
}
}
return failed
@@ -261,8 +266,16 @@ export function usePublishAll(
publish: (name: string) => Promise<unknown>,
noun: string,
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>,
noun: string,
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>,
noun: string,
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
}) {
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)
// The face a round dashboard shows: the widget picked, or the one last
// picked or paged to once its settings are put away.
@@ -403,9 +405,9 @@ export function DashboardEditor({
const root = useCanvasRoot(draft)
const navigate = useNavigate()
const queryClient = useQueryClient()
const save = useSaveDashboard(dashboard.name)
const publish = usePublishDashboard(dashboard.name)
const discard = useDiscardDashboardDraft(dashboard.name)
const save = useSaveDashboard(id)
const publish = usePublishDashboard(id)
const discard = useDiscardDashboardDraft(id)
const [discardOpen, setDiscardOpen] = useState(false)
const { showSuccessToast, showErrorToast } = useCustomToast()
const copied = useCopiedWidget()
@@ -484,8 +486,7 @@ export function DashboardEditor({
}
const remove = useMutation({
mutationFn: () =>
DashboardsService.deleteDashboard({ dashboardId: draft.name }),
mutationFn: () => DashboardsService.deleteDashboard({ dashboardId: id }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: dashboardKeys.all })
navigate({ to: "/dashboards" })
@@ -590,7 +591,7 @@ export function DashboardEditor({
(devices?.data ?? []).find(
(device) =>
(device.dashboards ?? []).length > 1 &&
(device.dashboards ?? []).includes(draft.name),
(device.dashboards ?? []).includes(id),
)?.dashboards ?? null
// A round face has no room for one: a panel swipes between those instead.
const hasRail = Boolean(railDashboards) && !stacked && !round
@@ -598,13 +599,13 @@ export function DashboardEditor({
railDashboards && !round ? (
<PanelRail
dashboards={railDashboards}
current={draft.name}
current={id}
horizontal={stacked}
// Editing one dashboard of a panel and editing its neighbour are the
// same job, so the rail keeps whichever mode this one is in.
linkFor={(name) => ({
to: "/dashboards/$name",
params: { name },
linkFor={(other) => ({
to: "/dashboards/$id",
params: { id: other },
search: edit ? { edit: true } : {},
})}
/>
@@ -675,8 +676,8 @@ export function DashboardEditor({
setSelected(null)
setSettingsOpen(false)
navigate({
to: "/dashboards/$name",
params: { name: draft.name },
to: "/dashboards/$id",
params: { id },
search: next ? { edit: true } : {},
})
}
@@ -685,7 +686,7 @@ export function DashboardEditor({
const pickable = (widget: WidgetDef, grip = false) => (
<Pickable
widget={widget}
dashboard={draft.name}
dashboard={id}
grip={grip}
selected={widget.id === selected}
onPick={() => {
@@ -985,7 +986,7 @@ export function DashboardEditor({
asChild
>
<a
href={appPath(`/view/${draft.name}`)}
href={appPath(`/view/${id}`)}
target="_blank"
rel="noreferrer"
>
@@ -97,14 +97,14 @@ export function DashboardPalette({
<CommandGroup heading="Dashboards">
{dashboards.map((dashboard) => (
<CommandItem
key={dashboard.name}
key={dashboard.id}
value={`dashboard ${dashboard.name} ${dashboard.title}`}
onSelect={() =>
close(() =>
// Editing a neighbour is the same job, as on the rail.
navigate({
to: "/dashboards/$name",
params: { name: dashboard.name },
to: "/dashboards/$id",
params: { id: dashboard.id! },
search: { edit: true },
}),
)
@@ -536,7 +536,7 @@ function WidgetGrid({
issue={widgetIssue(widget)}
scroll={scrolls(widget)}
>
<WidgetBody widget={widget} dashboard={dashboard.name} />
<WidgetBody widget={widget} dashboard={dashboard.id!} />
</Frame>
)}
</motion.div>
@@ -28,20 +28,21 @@ export function PanelRail({
linkFor,
horizontal,
}: {
/** Dashboard ids, in the order the device carries them. */
dashboards: string[]
current: string
linkFor: (name: string) => LinkProps
linkFor: (id: string) => LinkProps
horizontal?: boolean
}) {
const { Rail } = useUi()
const box = useRef<HTMLDivElement>(null)
const still = useReducedMotion()
const entries = useQueries({
queries: dashboards.map((name) => dashboardQueryOptions(name)),
queries: dashboards.map((id) => dashboardQueryOptions(id)),
combine: (results) =>
results.map((result, index) => ({
name: dashboards[index],
label: result.data?.title || dashboards[index],
label: result.data?.title || result.data?.name || dashboards[index],
icon: result.data?.icon ?? "",
active: dashboards[index] === current,
link: linkFor(dashboards[index]),
@@ -16,7 +16,7 @@ import { cn } from "@/lib/utils"
* One dashboard filling whatever screen it landed on.
*
* 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 dashboard's theme is stated by the route rather than here: on these two
@@ -601,7 +601,7 @@ export function RoundView({
>
<Face
widget={one}
dashboard={dashboard.name}
dashboard={dashboard.id!}
size={size}
editing={editing}
onPick={onPick && (() => onPick(one.id))}
@@ -80,8 +80,10 @@ export function RunsContextProvider({
const finals = new Map<string, LiveValue>()
if (primary) {
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 ?? {})) {
finals.set(key.includes(".") ? key : `${primary.flow}.${key}`, {
finals.set(key.includes(".") ? key : `${namespace}.${key}`, {
value,
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 = {
kind: "runs",
label:
+11 -2
View File
@@ -8,6 +8,7 @@ import { screensOf } from "@/components/Devices/ports"
import { devicesQueryOptions } from "@/components/Devices/queries"
import {
FieldLabel,
IdentitySection,
InfoTip,
PANEL_SECTION,
PanelSection,
@@ -241,6 +242,8 @@ function RunsSourceFields({
}) {
const { data: flows } = useQuery(runOverviewQueryOptions())
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 (
<div className="grid gap-2">
@@ -256,7 +259,7 @@ function RunsSourceFields({
<SelectContent>
{(flows ?? []).map((row) => (
<SelectItem key={row.flow} value={row.flow}>
{row.flow}
{row.flow_name || row.flow}
</SelectItem>
))}
</SelectContent>
@@ -271,7 +274,7 @@ function RunsSourceFields({
placeholder="Pick a metric"
filter={(message) =>
(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 })}
/>
@@ -1980,6 +1983,12 @@ export function DashboardPanel({
}
>
<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
title="Rail icon"
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 = {
all: ["dashboards"] as const,
/** The working copy and the published document are two different reads. */
detail: (name: string, draft = false) =>
["dashboards", name, draft ? "draft" : "published"] as const,
/** By id. The working copy and the published document are two reads. */
detail: (id: string, draft = false) =>
["dashboards", id, draft ? "draft" : "published"] as const,
messages: ["messages"] 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
* split: nothing half-arranged reaches the wall until someone publishes.
*/
export const dashboardQueryOptions = (name: string, draft = false) => ({
queryKey: dashboardKeys.detail(name, draft),
queryFn: () => DashboardsService.readDashboard({ dashboardId: name, draft }),
export const dashboardQueryOptions = (id: string, draft = false) => ({
queryKey: dashboardKeys.detail(id, draft),
queryFn: () => DashboardsService.readDashboard({ dashboardId: id, draft }),
})
/** 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.
*/
export function useSaveDashboard(name: string) {
export function useSaveDashboard(id: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (body: DashboardDef_Input) =>
DashboardsService.saveDashboard({ dashboardId: name, requestBody: body }),
DashboardsService.saveDashboard({ dashboardId: id, requestBody: body }),
onSuccess: (saved) => {
queryClient.setQueryData(dashboardKeys.detail(name, true), saved)
queryClient.setQueryData(dashboardKeys.detail(id, true), saved)
queryClient.invalidateQueries({ queryKey: dashboardKeys.all })
},
})
}
/** 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()
return useMutation({
mutationFn: (version: number) =>
DashboardsService.publishDashboard({
dashboardId: name,
dashboardId: id,
requestBody: { version },
}),
onSuccess: (published) => {
queryClient.setQueryData(dashboardKeys.detail(name, true), published)
queryClient.setQueryData(dashboardKeys.detail(name), published)
queryClient.setQueryData(dashboardKeys.detail(id, true), published)
queryClient.setQueryData(dashboardKeys.detail(id), published)
queryClient.invalidateQueries({ queryKey: dashboardKeys.all })
},
})
}
/** 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()
return useMutation({
mutationFn: () =>
DashboardsService.discardDashboardDraft({ dashboardId: name }),
DashboardsService.discardDashboardDraft({ dashboardId: id }),
onSuccess: (published) => {
queryClient.setQueryData(dashboardKeys.detail(name, true), published)
queryClient.setQueryData(dashboardKeys.detail(name), published)
queryClient.setQueryData(dashboardKeys.detail(id, true), published)
queryClient.setQueryData(dashboardKeys.detail(id), published)
queryClient.invalidateQueries({ queryKey: dashboardKeys.all })
},
})
@@ -116,7 +116,8 @@ export function usePublishMessage() {
requestBody: {
value,
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:
dashboard && widget ? `dashboard:${dashboard}:${widget}` : "",
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 }
const RENDERERS: Partial<
@@ -312,14 +312,15 @@ function Dashboards({
}) {
const { data } = useQuery(dashboardsQueryOptions())
const known = data?.data ?? []
// Dashboard ids: a device keeps showing a dashboard whatever it is called.
const assigned = device.dashboards ?? []
const byName = new Map(known.map((dashboard) => [dashboard.name, dashboard]))
const free = known.filter((dashboard) => !assigned.includes(dashboard.name))
const byId = new Map(known.map((dashboard) => [dashboard.id, dashboard]))
const free = known.filter((dashboard) => !assigned.includes(dashboard.id!))
const set = (dashboards: string[]) => onChange({ dashboards })
const move = (from: number, by: number) => {
const next = [...assigned]
const [name] = next.splice(from, 1)
next.splice(from + by, 0, name)
const [id] = next.splice(from, 1)
next.splice(from + by, 0, id)
set(next)
}
@@ -334,13 +335,13 @@ function Dashboards({
</p>
) : (
<ol className="grid gap-1" data-testid="device-dashboards">
{assigned.map((name, index) => {
const dashboard = byName.get(name)
const title = dashboard?.title || name
{assigned.map((id, index) => {
const dashboard = byId.get(id)
const title = dashboard?.title || dashboard?.name || id
// What this dashboard draws on the rail.
const Glyph = resolveIcon(dashboard?.icon ?? "")
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">
{index + 1}
</span>
@@ -352,8 +353,8 @@ function Dashboards({
</span>
{dashboard ? (
<Link
to="/dashboards/$name"
params={{ name }}
to="/dashboards/$id"
params={{ id }}
className="min-w-0 flex-1 truncate hover:underline"
>
{title}
@@ -361,7 +362,7 @@ function Dashboards({
) : (
// Deleted since: the device skips it.
<span className="min-w-0 flex-1 truncate text-muted-foreground line-through">
{name}
{id}
</span>
)}
{canEdit ? (
@@ -391,7 +392,7 @@ function Dashboards({
size="icon-touch"
className="text-muted-foreground"
aria-label={`Remove ${title}`}
onClick={() => set(assigned.filter((n) => n !== name))}
onClick={() => set(assigned.filter((n) => n !== id))}
>
<X />
</Button>
@@ -403,7 +404,7 @@ function Dashboards({
</ol>
)}
{canEdit && free.length > 0 ? (
<Select value="" onValueChange={(name) => set([...assigned, name])}>
<Select value="" onValueChange={(id) => set([...assigned, id])}>
<SelectTrigger
className="justify-self-start"
aria-label="Add a dashboard"
@@ -413,7 +414,7 @@ function Dashboards({
</SelectTrigger>
<SelectContent>
{free.map((dashboard) => (
<SelectItem key={dashboard.name} value={dashboard.name}>
<SelectItem key={dashboard.id} value={dashboard.id!}>
{dashboard.title || dashboard.name}
</SelectItem>
))}
@@ -778,8 +779,8 @@ function Capabilities({
{wired.map((binding) => (
<Link
key={`${binding.flow}.${binding.node}.${binding.message}`}
to="/flows/$flowName"
params={{ flowName: binding.flow }}
to="/flows/$flowId"
params={{ flowId: binding.flow_id! }}
search={{ node: binding.node }}
className="min-w-0 truncate font-mono hover:underline"
>
@@ -839,8 +840,8 @@ export function UseInFlow({
const { data } = useQuery(flowsQueryOptions())
const flows = data?.data ?? []
const place = useMutation({
mutationFn: async (flowName: string) => {
const { definition } = await FlowsService.readFlow({ flowId: flowName })
mutationFn: async (flowId: string) => {
const { definition } = await FlowsService.readFlow({ flowId })
const nodes = definition.nodes ?? []
const existing = deviceNodeOf(nodes, device.id)
const node = existing ?? {
@@ -854,7 +855,7 @@ export function UseInFlow({
const placed = port ? withPort(node, port) : node
if (placed !== existing) {
await FlowsService.saveFlow({
flowId: flowName,
flowId,
requestBody: {
...definition,
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({
to: "/flows/$flowName",
params: { flowName },
to: "/flows/$flowId",
params: { flowId },
search: { node },
}),
onError: (error) => handleError.call(showErrorToast, error as ApiError),
@@ -876,7 +877,7 @@ export function UseInFlow({
if (flows.length === 0) return null
return (
<Select value="" onValueChange={(flowName) => place.mutate(flowName)}>
<Select value="" onValueChange={(flowId) => place.mutate(flowId)}>
<SelectTrigger
size={size}
className="shrink-0 justify-self-start"
@@ -892,7 +893,7 @@ export function UseInFlow({
</SelectTrigger>
<SelectContent>
{flows.map((flow) => (
<SelectItem key={flow.name} value={flow.name}>
<SelectItem key={flow.id} value={flow.id!}>
{flow.title || flow.name}
</SelectItem>
))}
@@ -10,7 +10,9 @@ export type BrainNodeData = {
kind: string
/** The `flow.node_id` names behind this neuron; live events key by these. */
members: string[]
/** The keys of the flows it sits in, and their ids in the same order. */
flows: string[]
flowIds: string[]
/** Circle diameter in pixels, from how many neurons this one is wired to. */
size: number
/** 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,
members: source.members ?? [],
flows: source.flows ?? [],
flowIds: source.flow_ids ?? [],
size: node.size,
issue: source.issue,
} satisfies BrainNodeData,
@@ -233,18 +234,22 @@ function BrainCanvas() {
// flows are in the order they contributed one — which is rarely the
// 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.
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(
(member) =>
liveStore.getFailure(member) ||
liveStore.getStatus(member)?.status === "error",
)
const [memberFlow, nodeId] = (failing ?? "").split(".")
const flowName = memberFlow || flows[0]
if (flowName)
const flowId = memberFlow
? flowIds[flows.indexOf(memberFlow)]
: flowIds[0]
if (flowId)
navigate({
to: "/flows/$flowName",
params: { flowName },
to: "/flows/$flowId",
params: { flowId },
search: nodeId ? { node: nodeId } : {},
})
}}
@@ -149,13 +149,13 @@ export function CommandPalette({
<CommandGroup heading="Flows">
{flows.map((flow) => (
<CommandItem
key={flow.name}
key={flow.id}
value={`flow ${flow.name} ${flow.title}`}
onSelect={() =>
close(() =>
navigate({
to: "/flows/$flowName",
params: { flowName: flow.name },
to: "/flows/$flowId",
params: { flowId: flow.id! },
}),
)
}
@@ -49,11 +49,14 @@ export type InspectedEdge = {
export function EdgeInspector({
edge,
flow,
flowId,
onClose,
onUnbind,
}: {
edge: InspectedEdge | null
/** The flow's key, which its messages are named under. */
flow: string
flowId: string
onClose: () => void
onUnbind: (message: string) => void
}) {
@@ -64,7 +67,7 @@ export function EdgeInspector({
const replay = useMutation({
mutationFn: (value: unknown) =>
FlowsService.triggerNode({
flowId: flow,
flowId,
nodeId: edge?.sourceId ?? "",
requestBody: { values: { [edge?.message ?? ""]: value } },
}),
@@ -145,6 +148,7 @@ export function EdgeInspector({
<div className="mt-2">
<MessageSparkline
flow={flow}
flowId={flowId}
name={displayName(flow, edge.message)}
/>
</div>
+51 -36
View File
@@ -258,11 +258,12 @@ function uniqueNodeId(existing: NodeDef_Input[], type: string): string {
}
function FlowEditorInner({
flowName,
flowId,
focus,
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. */
focus?: string
onReload: () => void
@@ -275,8 +276,11 @@ function FlowEditorInner({
const { resolvedTheme } = useTheme()
const { data: flows } = useSuspenseQuery(flowsQueryOptions())
const { data: detail } = useSuspenseQuery(flowQueryOptions(flowName))
const { data: detail } = useSuspenseQuery(flowQueryOptions(flowId))
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 {
save,
@@ -285,9 +289,9 @@ function FlowEditorInner({
resolveConflict,
adopt,
mutation: saving,
} = useAutosave(flowName)
const publish = usePublish(flowName)
const discard = useDiscardDraft(flowName)
} = useAutosave(flowId)
const publish = usePublish(flowId)
const discard = useDiscardDraft(flowId)
// 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.
@@ -464,6 +468,7 @@ function FlowEditorInner({
data: {
definition: definition ?? { id: node.id },
flow: flowName,
flowId,
typeLabel:
typeLabels.get(definition?.type ?? "") ?? definition?.type ?? "",
isPlugin: pluginTypes.has(definition?.type ?? ""),
@@ -477,6 +482,7 @@ function FlowEditorInner({
canvasNodes,
definitions,
flowName,
flowId,
issuesByNode,
warningsByNode,
pluginTypes,
@@ -532,25 +538,28 @@ function FlowEditorInner({
*/
const openEndpoint = useCallback(
(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") {
// This flow's own boundary, declared in its settings.
setSelectedId(null)
setFlowPanelOpen(true)
} else if (kind === "dashboard") {
} else if (kind === "dashboard" && owner) {
navigate({ to: "/dashboards/$id", params: { id: owner } })
} else if (kind === "flow" && owner) {
navigate({
to: "/dashboards/$name",
params: { name: (rest ?? "").split(":")[0] },
})
} else if (kind === "flow") {
navigate({
to: "/flows/$flowName",
params: { flowName: (rest ?? "").split(".")[0] },
to: "/flows/$flowId",
params: { flowId: owner },
search: { node: `flow:${via ? `${flowName}.${via}` : flowName}` },
})
}
},
[navigate, flowName],
[navigate, flowName, flowId, queryClient],
)
/**
@@ -861,7 +870,7 @@ function FlowEditorInner({
const runMutation = useMutation({
mutationFn: (inputs: Record<string, unknown> = {}) =>
FlowsService.runFlow({ flowId: flowName, requestBody: { inputs } }),
FlowsService.runFlow({ flowId, requestBody: { inputs } }),
onSuccess: (state) => {
liveStore.setValues(
Object.fromEntries(
@@ -892,10 +901,10 @@ function FlowEditorInner({
const enableMutation = useMutation({
mutationFn: (next: boolean) =>
next
? FlowsService.startFlow({ flowId: flowName })
: FlowsService.stopFlow({ flowId: flowName }),
? FlowsService.startFlow({ flowId })
: FlowsService.stopFlow({ flowId }),
onSuccess: (detail) => {
queryClient.setQueryData(flowKeys.detail(flowName), detail)
queryClient.setQueryData(flowKeys.detail(flowId), detail)
queryClient.invalidateQueries({ queryKey: flowKeys.all, exact: true })
},
onError: () => showErrorToast("The flow could not be started or stopped."),
@@ -904,14 +913,14 @@ function FlowEditorInner({
const pauseMutation = useMutation({
mutationFn: (next: boolean) =>
next
? FlowsService.pauseFlow({ flowId: flowName })
: FlowsService.resumeFlow({ flowId: flowName }),
? FlowsService.pauseFlow({ flowId })
: FlowsService.resumeFlow({ flowId }),
// The engine answers with a flow_paused event, which is what the dock reads.
onError: () => showErrorToast("The flow could not be paused."),
})
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.
onSuccess: (result) => showSuccessToast(result.message),
onError: () => showErrorToast("The flow could not be stepped."),
@@ -919,11 +928,11 @@ function FlowEditorInner({
const deleteMutation = useMutation({
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
// leaves both standing.
if (withRuns)
await RunsService.deleteRuns({ flow: flowName, history: true })
await RunsService.deleteRuns({ flow: flowId, history: true })
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: flowKeys.all })
@@ -947,7 +956,7 @@ function FlowEditorInner({
// draft, so the ports on the canvas have to be there first.
await flush()
return FlowsService.saveNodeSource({
flowId: flowName,
flowId,
nodeId,
requestBody: { code },
drop,
@@ -955,7 +964,7 @@ function FlowEditorInner({
},
// One at a time: the save that drops a port must not land before the
// autosave that kept it.
scope: { id: `source:${flowName}` },
scope: { id: `source:${flowId}` },
onSuccess: (saved) => {
const followed = saved.node
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
// queued save has landed.
const current = queryClient.getQueryData<FlowDetail>(
flowKeys.detail(flowName),
flowKeys.detail(flowId),
)
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. */
const copyNodes = useCallback(async () => {
@@ -1227,7 +1236,7 @@ function FlowEditorInner({
.filter((node) => !node.source_ref && sourceTypes.has(node.type ?? ""))
.map(async (node) => {
const { code } = await FlowsService.readNodeSource({
flowId: flowName,
flowId,
nodeId: node.id,
})
sources[node.id] = code
@@ -1244,7 +1253,7 @@ function FlowEditorInner({
if (!stored) {
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
@@ -1341,6 +1350,8 @@ function FlowEditorInner({
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
* entrance the brain view uses. React Flow reads a node's handle bounds
@@ -1531,6 +1542,7 @@ function FlowEditorInner({
<FlowPanel
open={flowPanelOpen && !selected}
flowId={flowId}
definition={flowDoc}
nodeCount={definitions.length}
// Confirmed, so it is a finished edit rather than a run of keystrokes.
@@ -1546,6 +1558,7 @@ function FlowEditorInner({
<NodePanel
node={selected}
flow={flowName}
flowId={flowId}
nodeTypes={nodeTypeInfo ?? []}
origin={flowDoc.origin}
suggestions={suggestions}
@@ -1572,6 +1585,7 @@ function FlowEditorInner({
<EdgeInspector
edge={inspected}
flow={flowName}
flowId={flowId}
onClose={() => setInspected(null)}
onUnbind={unbind}
/>
@@ -1579,6 +1593,7 @@ function FlowEditorInner({
<InputInspector
input={inspectedInput}
flow={flowName}
flowId={flowId}
onClose={() => setInspectedInput(null)}
onEdit={() => {
setInspectedInput(null)
@@ -1753,10 +1768,10 @@ function useUnpositionedNodes(definitions: NodeDef_Input[]) {
}
export function FlowEditor({
flowName,
flowId,
focus,
}: {
flowName: string
flowId: string
/** A node or endpoint to arrive on — see `FlowEditorInner`. */
focus?: string
}) {
@@ -1782,8 +1797,8 @@ export function FlowEditor({
* would throw an unsaved edit away with it.
*/}
<FlowEditorInner
key={`${flowName}:${epoch}`}
flowName={flowName}
key={`${flowId}:${epoch}`}
flowId={flowId}
focus={focus}
onReload={reload}
/>
+6 -2
View File
@@ -92,7 +92,10 @@ const STATUS_STYLES = {
export type FlowNodeData = {
definition: NodeDef_Input
/** The flow's key, which its node ids and live values are named under. */
flow: string
/** The flow's id, which the API takes. */
flowId: string
typeLabel: string
isPlugin?: boolean
issueText: string
@@ -141,6 +144,7 @@ function FlowNodeComponent({ data, selected }: NodeProps) {
const {
definition,
flow,
flowId,
typeLabel,
isPlugin,
issueText,
@@ -278,7 +282,7 @@ function FlowNodeComponent({ data, selected }: NodeProps) {
// Best effort by nature: it may well have finished between
// the render and the click, which is the outcome asked for.
FlowsService.cancelNode({
flowId: flow,
flowId,
nodeId: definition.id,
}).catch(() => {})
}}
@@ -318,7 +322,7 @@ function FlowNodeComponent({ data, selected }: NodeProps) {
onShowLogs(definition.id)
// Reading it is what dismisses it: nothing else does, and a
// marker that never goes away stops meaning anything.
liveStore.acknowledgeFailure(nodeId)
liveStore.acknowledgeFailure(nodeId, flowId)
}}
>
<Bug />
+14 -1
View File
@@ -13,7 +13,12 @@ import {
} from "@/components/ui/dialog"
import { Switch } from "@/components/ui/switch"
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
@@ -21,6 +26,7 @@ import { PanelSection, PanelTitle, SidePanel } from "./SidePanel"
*/
export function FlowPanel({
open,
flowId,
definition,
nodeCount,
onChange,
@@ -32,6 +38,7 @@ export function FlowPanel({
onClose,
}: {
open: boolean
flowId: string
definition: FlowDef_Input
nodeCount: number
onChange: (next: FlowDef_Input) => void
@@ -77,6 +84,12 @@ export function FlowPanel({
}
>
<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
title="Running"
className="gap-3"
@@ -24,11 +24,14 @@ export type InspectedInput = {
export function InputInspector({
input,
flow,
flowId,
onClose,
onEdit,
}: {
input: InspectedInput | null
/** The flow's key, which its messages are named under. */
flow: string
flowId: string
onClose: () => void
onEdit: () => void
}) {
@@ -111,6 +114,7 @@ export function InputInspector({
<div className="mt-2">
<MessageSparkline
flow={flow}
flowId={flowId}
name={displayName(flow, qualify(flow, name))}
dtype={spec.dtype}
/>
@@ -59,17 +59,20 @@ function useSettled(value: string): string {
*/
export function MessageSparkline({
flow,
flowId,
name,
dtype,
}: {
/** The flow's key, which a bare `name` is read under. */
flow: string
flowId: string
name: string
/** What the port declares, so a value that never arrived still says what it would be. */
dtype?: DType
}) {
const message = useSettled(name)
const live = useLiveValue(qualify(flow, message))
const { data } = useQuery(messageHistoryQueryOptions(flow, message))
const { data } = useQuery(messageHistoryQueryOptions(flowId, message))
const [tail, setTail] = useState<HistoryPoint[]>([])
// Pointing the field at another message makes the collected tail meaningless.
+80 -14
View File
@@ -26,6 +26,7 @@ import {
type MessageSpec,
type NodeDef_Input,
type NodeTypeInfo,
OpenAPI,
} from "@/client"
import {
DEVICE_TYPE,
@@ -81,6 +82,7 @@ import {
useParamSuggestions,
} from "./queries"
import {
CopyValue,
FieldLabel,
InfoTip,
PANEL_SECTION,
@@ -307,6 +309,7 @@ function PortList({
side,
specs,
flow,
flowId,
emptyHint,
suggestions,
onChange,
@@ -318,7 +321,9 @@ function PortList({
/** An input reads a message into the code, an output writes one out of it. */
side: "requires" | "provides"
specs: MessageSpec[]
/** The flow's key, which a bare message name is read under. */
flow: string
flowId: string
emptyHint: string
suggestions: string[]
onChange: (next: MessageSpec[]) => void
@@ -579,6 +584,7 @@ function PortList({
{spec.name ? (
<MessageSparkline
flow={flow}
flowId={flowId}
name={spec.name}
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
* it. Each flow keeps its own ports and settings; only the code is common, so
* one fix reaches all of them.
*/
function SharingSection({
flow,
flowId,
node,
onShared,
}: {
flow: string
flowId: string
node: NodeDef_Input
onShared: () => void
}) {
@@ -1640,14 +1698,14 @@ function SharingSection({
const done = () => {
queryClient.invalidateQueries({ queryKey: flowKeys.library })
queryClient.invalidateQueries({ queryKey: flowKeys.detail(flow) })
queryClient.invalidateQueries({ queryKey: flowKeys.detail(flowId) })
onShared()
}
const share = useMutation({
mutationFn: (libName: string) =>
FlowsService.shareNode({
flowId: flow,
flowId,
nodeId: node.id,
requestBody: { lib_name: libName },
}),
@@ -1657,8 +1715,7 @@ function SharingSection({
})
const unshare = useMutation({
mutationFn: () =>
FlowsService.unshareNode({ flowId: flow, nodeId: node.id }),
mutationFn: () => FlowsService.unshareNode({ flowId, nodeId: node.id }),
onSuccess: done,
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.
*/
function TrainingSection({
flow,
flowId,
node,
onUse,
}: {
flow: string
flowId: string
node: NodeDef_Input
onUse: (model: string) => void
}) {
const queryClient = useQueryClient()
// Why it would not start, such as wren's training flow not being registered.
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({
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.
refetchInterval: (query) =>
query.state.data && isLive(query.state.data.status) ? 5_000 : false,
})
const train = useMutation({
mutationFn: () => FlowsService.trainNode({ flowId: flow, nodeId: node.id }),
mutationFn: () => FlowsService.trainNode({ flowId, nodeId: node.id }),
onMutate: () => setProblem(null),
onSuccess: () => queryClient.invalidateQueries({ queryKey }),
onError: handleError.bind(setProblem),
@@ -2030,6 +2087,7 @@ function scaffoldFor(node: NodeDef_Input): string {
function PanelBody({
node,
flow,
flowId,
nodeType,
origin,
suggestions,
@@ -2043,6 +2101,7 @@ function PanelBody({
}: {
node: NodeDef_Input
flow: string
flowId: string
nodeType: NodeTypeInfo | undefined
origin: FlowOrigin | null | undefined
suggestions: PortSuggestions
@@ -2057,7 +2116,7 @@ function PanelBody({
}) {
const hasSource = nodeType?.has_source ?? node.type === "python"
const { data: source } = useQuery({
...nodeSourceQueryOptions(flow, node.id),
...nodeSourceQueryOptions(flowId, node.id),
enabled: hasSource,
})
// Code the engine runs is a superuser's to change; the server refuses
@@ -2228,6 +2287,7 @@ function PanelBody({
side="requires"
specs={node.requires ?? []}
flow={flow}
flowId={flowId}
emptyHint="Nothing yet. Add a message this node reads."
suggestions={suggestions.consumes}
onChange={(requires) => editNode({ ...node, requires })}
@@ -2237,6 +2297,7 @@ function PanelBody({
side="provides"
specs={node.provides ?? []}
flow={flow}
flowId={flowId}
emptyHint="Nothing yet. Add a message this node publishes."
suggestions={suggestions.provides}
onChange={(provides) => {
@@ -2270,6 +2331,7 @@ function PanelBody({
) : (
paramsForm
)}
<HookSection flowId={flowId} node={node} />
{nodeType?.free_params ? (
<FreeParamsForm
params={node.params ?? {}}
@@ -2282,7 +2344,7 @@ function PanelBody({
) : null}
{node.type === "wren" ? (
<TrainingSection
flow={flow}
flowId={flowId}
node={node}
onUse={(model) =>
editNode({ ...node, params: { ...node.params, model } })
@@ -2325,7 +2387,7 @@ function PanelBody({
<ResourcesSection node={node} onChange={editNode} />
) : null}
{hasSource ? (
<SharingSection flow={flow} node={node} onShared={onShared} />
<SharingSection flowId={flowId} node={node} onShared={onShared} />
) : null}
</div>
@@ -2405,6 +2467,7 @@ export type PortSuggestions = { consumes: string[]; provides: string[] }
export function NodePanel({
node,
flow,
flowId,
nodeTypes,
origin,
suggestions,
@@ -2419,7 +2482,9 @@ export function NodePanel({
onDelete,
}: {
node: NodeDef_Input | null
/** The flow's key, the namespace its messages are named under. */
flow: string
flowId: string
nodeTypes: NodeTypeInfo[]
/** Set when the flow was declared in code elsewhere; its bodies are generated. */
origin: FlowOrigin | null | undefined
@@ -2476,6 +2541,7 @@ export function NodePanel({
<PanelBody
node={node}
flow={flow}
flowId={flowId}
nodeType={nodeType}
origin={origin}
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 type { ReactNode } from "react"
import { useEffect, useState } from "react"
@@ -12,6 +12,7 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip"
import { useCopyToClipboard } from "@/hooks/useCopyToClipboard"
import { useIsMobile } from "@/hooks/useMobile"
import { duration, easeEmphasized, easeStandard } from "@/lib/motion"
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.
*
+6 -5
View File
@@ -201,18 +201,19 @@ export const liveStore = {
* not, which is what makes a failure between two glances at the canvas
* findable at all.
*/
acknowledgeFailure(nodeId: string) {
acknowledgeFailure(nodeId: string, flowId: string) {
if (!failures.delete(nodeId)) return
notify(`failure:${nodeId}`)
const [flow, node] = nodeId.split(".")
if (!flow || !node) return
// `key.node`: the key names the node, the id addresses the flow.
const node = nodeId.split(".")[1]
if (!node) return
// 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
// reload — which is the safer way round for a failure.
request(OpenAPI, {
method: "POST",
url: "/api/v1/flows/{name}/nodes/{node_id}/acknowledge",
path: { name: flow, node_id: node },
url: "/api/v1/flows/{flow_id}/nodes/{node_id}/acknowledge",
path: { flow_id: flowId, node_id: node },
}).catch(() => {})
},
recordEngineEvent(event: EngineEvent) {
+28 -27
View File
@@ -15,13 +15,14 @@ import {
SecretsService,
} from "@/client"
/** Keyed by flow id, which every flow route takes. */
export const flowKeys = {
all: ["flows"] as const,
detail: (name: string) => ["flows", name] as const,
source: (name: string, nodeId: string) =>
["flows", name, "source", nodeId] as const,
history: (name: string, message: string) =>
["flows", name, "history", message] as const,
detail: (id: string) => ["flows", id] as const,
source: (id: string, nodeId: string) =>
["flows", id, "source", nodeId] as const,
history: (id: string, message: string) =>
["flows", id, "history", message] as const,
nodeTypes: ["flows", "node-types"] as const,
library: ["flows", "library"] as const,
// Under `all` on purpose: the socket invalidates that prefix on every
@@ -34,9 +35,9 @@ export const flowsQueryOptions = () => ({
queryFn: () => FlowsService.readFlows(),
})
export const flowQueryOptions = (name: string) => ({
queryKey: flowKeys.detail(name),
queryFn: () => FlowsService.readFlow({ flowId: name }),
export const flowQueryOptions = (id: string) => ({
queryKey: flowKeys.detail(id),
queryFn: () => FlowsService.readFlow({ flowId: id }),
})
/** Names of the stored secrets, for pointing a credential parameter at one. */
@@ -69,15 +70,15 @@ export const nodeTypesQueryOptions = () => ({
staleTime: Number.POSITIVE_INFINITY,
})
export const nodeSourceQueryOptions = (name: string, nodeId: string) => ({
queryKey: flowKeys.source(name, nodeId),
queryFn: () => FlowsService.readNodeSource({ flowId: name, nodeId }),
export const nodeSourceQueryOptions = (id: string, nodeId: string) => ({
queryKey: flowKeys.source(id, nodeId),
queryFn: () => FlowsService.readNodeSource({ flowId: id, nodeId }),
})
/** The recent values of one message, for the panel's sparkline. */
export const messageHistoryQueryOptions = (name: string, message: string) => ({
queryKey: flowKeys.history(name, message),
queryFn: () => FlowsService.readMessageHistory({ flowId: name, message }),
export const messageHistoryQueryOptions = (id: string, message: string) => ({
queryKey: flowKeys.history(id, message),
queryFn: () => FlowsService.readMessageHistory({ flowId: id, message }),
})
/** 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.
const details = useQueries({
queries: (type ? (flows?.data ?? []) : []).map((flow) => ({
...flowQueryOptions(flow.name),
...flowQueryOptions(flow.id!),
staleTime: SUGGEST_STALE,
})),
})
@@ -130,25 +131,25 @@ const AUTOSAVE_DELAY = 800
const RETRY_DELAY = 100
/** 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()
return useMutation({
mutationFn: (version: number) =>
FlowsService.publishFlow({ flowId: name, requestBody: { version } }),
FlowsService.publishFlow({ flowId: id, requestBody: { version } }),
onSuccess: (detail) => {
queryClient.setQueryData(flowKeys.detail(name), detail)
queryClient.setQueryData(flowKeys.detail(id), detail)
queryClient.invalidateQueries({ queryKey: flowKeys.all, exact: true })
},
})
}
/** 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()
return useMutation({
mutationFn: () => FlowsService.discardDraft({ flowId: name }),
mutationFn: () => FlowsService.discardDraft({ flowId: id }),
onSuccess: (detail) => {
queryClient.setQueryData(flowKeys.detail(name), detail)
queryClient.setQueryData(flowKeys.detail(id), detail)
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`
* 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
/** Send what is queued and resolve once the server has it. */
flush: () => Promise<void>
@@ -189,7 +190,7 @@ export function useAutosave(name: string): {
const mutation = useMutation({
mutationFn: (definition: FlowDef_Input) =>
FlowsService.saveFlow({
flowId: name,
flowId: id,
// The ref holds the freshest version this client has seen; before the
// first save that is the one the document was loaded with. Sending
// `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
// Write the server's answer straight into the cache: invalidating would
// 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 })
},
onError: (error) => {
@@ -250,17 +251,17 @@ export function useAutosave(name: string): {
sent.current = null
version.current = null
await queryClient.invalidateQueries({
queryKey: flowKeys.detail(name),
queryKey: flowKeys.detail(id),
})
return
}
const current = await FlowsService.readFlow({ flowId: name })
const current = await FlowsService.readFlow({ flowId: id })
version.current = current.definition.version ?? null
const definition = pending.current ?? sent.current
pending.current = null
if (definition) mutate(definition)
},
[mutate, name, queryClient],
[mutate, id, queryClient],
)
const save = useCallback(
+26 -6
View File
@@ -35,6 +35,11 @@ const AUTH_ATTEMPTS = 3
*/
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: "snapshot"
@@ -58,6 +63,7 @@ type FlowEvent =
| {
type: "node_queued"
flow?: string
flow_id?: string
node: string
run?: string
detail?: string
@@ -66,6 +72,7 @@ type FlowEvent =
| {
type: "node_executed"
flow?: string
flow_id?: string
node: string
outputs: number
duration_ms?: number
@@ -73,6 +80,7 @@ type FlowEvent =
| {
type: "node_error"
flow?: string
flow_id?: string
node: string
error: string
ts?: number
@@ -80,21 +88,29 @@ type FlowEvent =
| { type: "node_status"; node: string; status: string; error?: string | null }
| { type: "node_error_acknowledged"; node: string; ts?: number }
| ({ type: "node_log" } & LogLine)
| { type: "flow_paused"; flow: string; paused: boolean }
| { type: "flow_paused"; flow: string; flow_id?: string; paused: boolean }
| {
type: "node_health"
flow?: string
flow_id?: string
node: string
health: "ok" | "degraded" | "down" | "unknown"
detail?: string | null
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_fatal"; reason?: string; ts?: number }
| {
type: "cascade_dropped"
flow?: string
flow_id?: string
node?: string
deliveries?: number
ts?: number
@@ -102,6 +118,7 @@ type FlowEvent =
| {
type: "queue_unavailable"
flow?: string
flow_id?: string
node?: string
error?: string
ts?: number
@@ -111,6 +128,7 @@ type FlowEvent =
nodes: { id: string; status: string; error?: string | null }[]
paused?: string[]
}
/** `dashboard` is an id, or empty when only device assignments changed. */
| { type: "dashboard_changed"; dashboard?: string; ts?: number }
| {
type: "device_status"
@@ -122,6 +140,7 @@ type FlowEvent =
| {
type: "run_started" | "run_finished"
flow: string
flow_id?: string
run: string
status?: string
group?: string
@@ -130,6 +149,7 @@ type FlowEvent =
| {
type: "run_metric"
flow: string
flow_id?: string
run: string
names: string[]
ts?: number
@@ -231,11 +251,11 @@ function endLive() {
}
/** 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
// detail invalidation alone never reaches Home's fault rings.
for (const queryKey of [
flow ? flowKeys.detail(flow) : flowKeys.all,
flowId ? flowKeys.detail(flowId) : flowKeys.all,
flowKeys.graph,
]) {
client?.invalidateQueries({ queryKey })
@@ -387,7 +407,7 @@ function open(url: string) {
// the server derives — so the screen only moved on mount, navigation
// or a rebuild, never when health actually flipped. The store had a
// 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
// a fault.
if (message.health === "down" || message.health === "degraded") {
@@ -402,7 +422,7 @@ function open(url: string) {
message.node,
setTimeout(() => {
healthTimers.delete(message.node)
invalidateHealth(message.flow)
invalidateHealth(message.flow_id)
}, HEALTH_FLOOR),
)
}
+8 -7
View File
@@ -37,6 +37,7 @@ export function FlowTable({ range }: { range: Range }) {
const { data: rollups } = useQuery(flowRollupsQueryOptions(range))
const flows = [...(data?.data ?? [])].sort(byRecency)
// Rollups name the flow by id, as every list here is keyed.
const activity = new Map<string, FlowRollup>(
(rollups ?? []).map((row: FlowRollup) => [row.flow, row]),
)
@@ -104,9 +105,9 @@ export function FlowTable({ range }: { range: Range }) {
<tbody>
{flows.map((flow) => (
<Row
key={flow.name}
key={flow.id}
flow={flow}
activity={activity.get(flow.name)}
activity={activity.get(flow.id!)}
/>
))}
</tbody>
@@ -132,11 +133,11 @@ function Row({
const toggle = useMutation({
mutationFn: (next: boolean) =>
next
? FlowsService.startFlow({ flowId: flow.name })
: FlowsService.stopFlow({ flowId: flow.name }),
? FlowsService.startFlow({ flowId: flow.id! })
: FlowsService.stopFlow({ flowId: flow.id! }),
onSuccess: () => {
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."),
})
@@ -151,8 +152,8 @@ function Row({
sizes to the longest name and pushes the page sideways. */}
<td className="max-w-0 px-4 py-2 sm:min-w-40">
<Link
to="/flows/$flowName"
params={{ flowName: flow.name }}
to="/flows/$flowId"
params={{ flowId: flow.id! }}
className="block min-w-0"
>
<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. */}
<span className="min-w-0 flex-1 break-words">
<span className="font-mono text-sm">
{event.node || event.flow || "engine"}
{event.node || event.flow_name || event.flow || "engine"}
</span>
<span className="ml-2 text-sm text-muted-foreground">{first}</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"
>
<span className="min-w-0 flex-1 truncate font-mono">
{run.flow}
{run.flow_name || run.flow}
</span>
{/* Five fixed columns do not fit a phone. What caused a run
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.flow ? (
<span className="ml-1 font-mono text-muted-foreground">
{event.flow}
{event.flow_name || event.flow}
</span>
) : null}
</span>
+4 -3
View File
@@ -70,13 +70,14 @@ export function NewRun({
const counts = new Map((overview ?? []).map((row) => [row.flow, row]))
const rows = (flows?.data ?? []).map((one) => {
const seen = counts.get(one.name)
const seen = counts.get(one.id!)
const notes = [
one.mode === "batch" ? "batch" : "",
one.has_draft ? "draft" : "",
].filter(Boolean)
return {
flow: one.name,
flow: one.id!,
flow_name: one.name,
runs: seen?.runs ?? 0,
running: seen?.running ?? 0,
queued: seen?.queued ?? 0,
@@ -106,7 +107,7 @@ export function NewRun({
</div>
{flow && (
<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" />
Open in editor
</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
* declared ports, which is the shortest path from "I ran something" to "I can
* 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({
flow,
flowName,
ids,
}: {
flow?: string
flowName?: string
ids: string[]
}) {
const navigate = useNavigate()
@@ -48,32 +53,38 @@ export function OpenInDashboard({
const [open, setOpen] = useState(false)
const { data } = useQuery(dashboardsQueryOptions())
const show = (name: string) => {
const show = (id: string) => {
setOpen(false)
navigate({
to: "/view/$name",
params: { name },
to: "/view/$id",
params: { id },
search: { runs: ids.join(",") },
})
}
const dashboards = data?.data ?? []
const label = flowName || flow
const results = flowName ? resultsName(flowName) : ""
const generate = useMutation({
mutationFn: (name: string) =>
DashboardsService.generateResultsDashboard({ flowId: name }),
mutationFn: (flowId: string) =>
DashboardsService.generateResultsDashboard({ flowId }),
onSuccess: (made) => {
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
// that was wanted either way.
if (error.status === 409 && flow) return show(resultsName(flow))
// that was wanted either way. The refusal does not say its id.
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")
},
})
const dashboards = data?.data ?? []
const results = flow ? resultsName(flow) : ""
const hasResults = dashboards.some((one) => one.name === results)
if (ids.length === 0) return null
@@ -98,22 +109,22 @@ export function OpenInDashboard({
{flow && !hasResults ? (
<CommandGroup>
<CommandItem
value={`build results ${flow}`}
value={`build results ${label}`}
onSelect={() => generate.mutate(flow)}
disabled={generate.isPending}
>
{generate.isPending
? "Building…"
: `Build a results dashboard for ${flow}`}
: `Build a results dashboard for ${label}`}
</CommandItem>
</CommandGroup>
) : null}
<CommandGroup>
{dashboards.map((one) => (
<CommandItem
key={one.name}
key={one.id}
value={`${one.name} ${one.title}`}
onSelect={() => show(one.name)}
onSelect={() => show(one.id!)}
>
{one.title || one.name}
{one.name === results ? (
+6 -2
View File
@@ -87,7 +87,7 @@ export function RunDetail({ id }: { id: string }) {
search={{ flow: run.flow }}
className="text-muted-foreground text-sm hover:underline"
>
{run.flow}
{run.flow_name || run.flow}
</Link>
<h1 className="font-mono font-semibold text-xl">{shortId(run.id)}</h1>
<RunStatusBadge run={run} />
@@ -115,7 +115,11 @@ export function RunDetail({ id }: { id: string }) {
)}
<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) ? (
<Button
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">
<header className="flex flex-wrap items-center gap-3">
<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>
<Button variant="brand" size="sm" className="h-8" asChild>
@@ -301,7 +304,7 @@ export function RunsScreen({
ids={selected}
search={search}
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 = {
/** The flow's id; `flow_name`, its key, is what the rail shows. */
flow: string
flow_name?: string
runs: number
running: number
queued: number
@@ -387,7 +392,7 @@ export function FlowRail({
{rows.map((row) =>
entry(
row.flow,
row.flow,
row.flow_name || row.flow,
row.runs,
row.running + row.queued,
active === row.flow,
@@ -548,11 +553,11 @@ function RunsTable({
{showFlow && (
<TableCell className="text-sm">
<Link
to="/flows/$flowName"
params={{ flowName: run.flow }}
to="/flows/$flowId"
params={{ flowId: run.flow }}
className="text-muted-foreground hover:underline"
>
{run.flow}
{run.flow_name || run.flow}
</Link>
</TableCell>
)}
@@ -623,12 +628,13 @@ function Compare({
ids,
search,
update,
flow,
run,
}: {
ids: string[]
search: RunsSearch
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 metric =
@@ -666,7 +672,7 @@ function Compare({
}
/>
)}
<OpenInDashboard flow={flow} ids={ids} />
<OpenInDashboard flow={run?.flow} flowName={run?.flow_name} ids={ids} />
<Button
variant="ghost"
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 PanelIndexRouteImport } from './routes/panel.index'
import { Route as PanelIdRouteImport } from './routes/panel.$id'
import { Route as ViewNameRouteImport } from './routes/view.$name'
import { Route as CanvasDashboardsNameRouteImport } from './routes/_canvas/dashboards/$name'
import { Route as CanvasFlowsFlowNameRouteImport } from './routes/_canvas/flows/$flowName'
import { Route as ViewIdRouteImport } from './routes/view.$id'
import { Route as CanvasDashboardsIdRouteImport } from './routes/_canvas/dashboards/$id'
import { Route as CanvasFlowsFlowIdRouteImport } from './routes/_canvas/flows/$flowId'
import { Route as LayoutDashboardsIndexRouteImport } from './routes/_layout/dashboards/index'
import { Route as LayoutDevicesIndexRouteImport } from './routes/_layout/devices/index'
import { Route as LayoutDevicesIdRouteImport } from './routes/_layout/devices/$id'
@@ -114,19 +114,19 @@ const PanelIdRoute = PanelIdRouteImport.update({
path: '/panel/$id',
getParentRoute: () => rootRouteImport,
} as any)
const ViewNameRoute = ViewNameRouteImport.update({
id: '/view/$name',
path: '/view/$name',
const ViewIdRoute = ViewIdRouteImport.update({
id: '/view/$id',
path: '/view/$id',
getParentRoute: () => rootRouteImport,
} as any)
const CanvasDashboardsNameRoute = CanvasDashboardsNameRouteImport.update({
id: '/dashboards/$name',
path: '/dashboards/$name',
const CanvasDashboardsIdRoute = CanvasDashboardsIdRouteImport.update({
id: '/dashboards/$id',
path: '/dashboards/$id',
getParentRoute: () => CanvasRoute,
} as any)
const CanvasFlowsFlowNameRoute = CanvasFlowsFlowNameRouteImport.update({
id: '/flows/$flowName',
path: '/flows/$flowName',
const CanvasFlowsFlowIdRoute = CanvasFlowsFlowIdRouteImport.update({
id: '/flows/$flowId',
path: '/flows/$flowId',
getParentRoute: () => CanvasRoute,
} as any)
const LayoutDashboardsIndexRoute = LayoutDashboardsIndexRouteImport.update({
@@ -179,10 +179,10 @@ export interface FileRoutesByFullPath {
'/workers': typeof LayoutWorkersRoute
'/oauth/authorize': typeof OauthAuthorizeRoute
'/panel/$id': typeof PanelIdRoute
'/view/$name': typeof ViewNameRoute
'/view/$id': typeof ViewIdRoute
'/panel/': typeof PanelIndexRoute
'/dashboards/$name': typeof CanvasDashboardsNameRoute
'/flows/$flowName': typeof CanvasFlowsFlowNameRoute
'/dashboards/$id': typeof CanvasDashboardsIdRoute
'/flows/$flowId': typeof CanvasFlowsFlowIdRoute
'/devices/$id': typeof LayoutDevicesIdRoute
'/runs/$id': typeof LayoutRunsIdRoute
'/runs/new': typeof LayoutRunsNewRoute
@@ -205,10 +205,10 @@ export interface FileRoutesByTo {
'/workers': typeof LayoutWorkersRoute
'/oauth/authorize': typeof OauthAuthorizeRoute
'/panel/$id': typeof PanelIdRoute
'/view/$name': typeof ViewNameRoute
'/view/$id': typeof ViewIdRoute
'/panel': typeof PanelIndexRoute
'/dashboards/$name': typeof CanvasDashboardsNameRoute
'/flows/$flowName': typeof CanvasFlowsFlowNameRoute
'/dashboards/$id': typeof CanvasDashboardsIdRoute
'/flows/$flowId': typeof CanvasFlowsFlowIdRoute
'/devices/$id': typeof LayoutDevicesIdRoute
'/runs/$id': typeof LayoutRunsIdRoute
'/runs/new': typeof LayoutRunsNewRoute
@@ -233,11 +233,11 @@ export interface FileRoutesById {
'/_layout/workers': typeof LayoutWorkersRoute
'/oauth/authorize': typeof OauthAuthorizeRoute
'/panel/$id': typeof PanelIdRoute
'/view/$name': typeof ViewNameRoute
'/view/$id': typeof ViewIdRoute
'/_layout/': typeof LayoutIndexRoute
'/panel/': typeof PanelIndexRoute
'/_canvas/dashboards/$name': typeof CanvasDashboardsNameRoute
'/_canvas/flows/$flowName': typeof CanvasFlowsFlowNameRoute
'/_canvas/dashboards/$id': typeof CanvasDashboardsIdRoute
'/_canvas/flows/$flowId': typeof CanvasFlowsFlowIdRoute
'/_layout/devices/$id': typeof LayoutDevicesIdRoute
'/_layout/runs/$id': typeof LayoutRunsIdRoute
'/_layout/runs/new': typeof LayoutRunsNewRoute
@@ -262,10 +262,10 @@ export interface FileRouteTypes {
| '/workers'
| '/oauth/authorize'
| '/panel/$id'
| '/view/$name'
| '/view/$id'
| '/panel/'
| '/dashboards/$name'
| '/flows/$flowName'
| '/dashboards/$id'
| '/flows/$flowId'
| '/devices/$id'
| '/runs/$id'
| '/runs/new'
@@ -288,10 +288,10 @@ export interface FileRouteTypes {
| '/workers'
| '/oauth/authorize'
| '/panel/$id'
| '/view/$name'
| '/view/$id'
| '/panel'
| '/dashboards/$name'
| '/flows/$flowName'
| '/dashboards/$id'
| '/flows/$flowId'
| '/devices/$id'
| '/runs/$id'
| '/runs/new'
@@ -315,11 +315,11 @@ export interface FileRouteTypes {
| '/_layout/workers'
| '/oauth/authorize'
| '/panel/$id'
| '/view/$name'
| '/view/$id'
| '/_layout/'
| '/panel/'
| '/_canvas/dashboards/$name'
| '/_canvas/flows/$flowName'
| '/_canvas/dashboards/$id'
| '/_canvas/flows/$flowId'
| '/_layout/devices/$id'
| '/_layout/runs/$id'
| '/_layout/runs/new'
@@ -338,7 +338,7 @@ export interface RootRouteChildren {
SignupRoute: typeof SignupRoute
OauthAuthorizeRoute: typeof OauthAuthorizeRoute
PanelIdRoute: typeof PanelIdRoute
ViewNameRoute: typeof ViewNameRoute
ViewIdRoute: typeof ViewIdRoute
PanelIndexRoute: typeof PanelIndexRoute
}
@@ -456,25 +456,25 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof PanelIdRouteImport
parentRoute: typeof rootRouteImport
}
'/view/$name': {
id: '/view/$name'
path: '/view/$name'
fullPath: '/view/$name'
preLoaderRoute: typeof ViewNameRouteImport
'/view/$id': {
id: '/view/$id'
path: '/view/$id'
fullPath: '/view/$id'
preLoaderRoute: typeof ViewIdRouteImport
parentRoute: typeof rootRouteImport
}
'/_canvas/dashboards/$name': {
id: '/_canvas/dashboards/$name'
path: '/dashboards/$name'
fullPath: '/dashboards/$name'
preLoaderRoute: typeof CanvasDashboardsNameRouteImport
'/_canvas/dashboards/$id': {
id: '/_canvas/dashboards/$id'
path: '/dashboards/$id'
fullPath: '/dashboards/$id'
preLoaderRoute: typeof CanvasDashboardsIdRouteImport
parentRoute: typeof CanvasRoute
}
'/_canvas/flows/$flowName': {
id: '/_canvas/flows/$flowName'
path: '/flows/$flowName'
fullPath: '/flows/$flowName'
preLoaderRoute: typeof CanvasFlowsFlowNameRouteImport
'/_canvas/flows/$flowId': {
id: '/_canvas/flows/$flowId'
path: '/flows/$flowId'
fullPath: '/flows/$flowId'
preLoaderRoute: typeof CanvasFlowsFlowIdRouteImport
parentRoute: typeof CanvasRoute
}
'/_layout/dashboards/': {
@@ -530,13 +530,13 @@ declare module '@tanstack/react-router' {
}
interface CanvasRouteChildren {
CanvasDashboardsNameRoute: typeof CanvasDashboardsNameRoute
CanvasFlowsFlowNameRoute: typeof CanvasFlowsFlowNameRoute
CanvasDashboardsIdRoute: typeof CanvasDashboardsIdRoute
CanvasFlowsFlowIdRoute: typeof CanvasFlowsFlowIdRoute
}
const CanvasRouteChildren: CanvasRouteChildren = {
CanvasDashboardsNameRoute: CanvasDashboardsNameRoute,
CanvasFlowsFlowNameRoute: CanvasFlowsFlowNameRoute,
CanvasDashboardsIdRoute: CanvasDashboardsIdRoute,
CanvasFlowsFlowIdRoute: CanvasFlowsFlowIdRoute,
}
const CanvasRouteWithChildren =
@@ -588,7 +588,7 @@ const rootRouteChildren: RootRouteChildren = {
SignupRoute: SignupRoute,
OauthAuthorizeRoute: OauthAuthorizeRoute,
PanelIdRoute: PanelIdRoute,
ViewNameRoute: ViewNameRoute,
ViewIdRoute: ViewIdRoute,
PanelIndexRoute: PanelIndexRoute,
}
export const routeTree = rootRouteImport
@@ -8,33 +8,36 @@ import { useFlowSocket } from "@/components/Flow/useFlowSocket"
type Search = { edit?: boolean }
export const Route = createFileRoute("/_canvas/dashboards/$name")({
export const Route = createFileRoute("/_canvas/dashboards/$id")({
component: DashboardRoute,
// 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.
validateSearch: (search: Record<string, unknown>): Search => ({
edit: search.edit === true || search.edit === "true" || undefined,
}),
head: ({ params }) => ({ meta: [{ title: `${params.name} - Fluksio` }] }),
})
function DashboardRoute() {
const { name } = Route.useParams()
const { id } = Route.useParams()
const { edit } = Route.useSearch()
// Widgets read live values; the canvas shell has no socket of its own.
useFlowSocket()
// 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.
const { data: dashboard } = useQuery(dashboardQueryOptions(name, true))
const { data: dashboard } = useQuery(dashboardQueryOptions(id, true))
if (!dashboard) return null
return (
<DashboardEditor
// Leaving edit mode drops the draft, so the session starts clean.
key={`${name}:${edit ? "edit" : "view"}`}
dashboard={dashboard as Dashboard}
edit={Boolean(edit)}
/>
<>
{/* From the document, since the id in the address can be opaque. */}
<title>{`${dashboard.title || dashboard.name} - Fluksio`}</title>
<DashboardEditor
// Leaving edit mode drops the draft, so the session starts clean.
key={`${id}:${edit ? "edit" : "view"}`}
dashboard={dashboard as Dashboard}
edit={Boolean(edit)}
/>
</>
)
}
@@ -6,7 +6,9 @@ import { Skeleton } from "@/components/ui/skeleton"
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,
// 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
@@ -14,9 +16,6 @@ export const Route = createFileRoute("/_canvas/flows/$flowName")({
validateSearch: (search: Record<string, unknown>): Search => ({
node: typeof search.node === "string" ? search.node : undefined,
}),
head: ({ params }) => ({
meta: [{ title: `${params.flowName} - Fluksio` }],
}),
})
function Loading() {
@@ -28,12 +27,12 @@ function Loading() {
}
function FlowRoute() {
const { flowName } = Route.useParams()
const { flowId } = Route.useParams()
const { node } = Route.useSearch()
return (
<Suspense fallback={<Loading />}>
<FlowEditor flowName={flowName} focus={node} />
<FlowEditor flowId={flowId} focus={node} />
</Suspense>
)
}
@@ -51,14 +51,20 @@ function Dashboards() {
queryClient.invalidateQueries({ queryKey: dashboardKeys.all })
setDialogOpen(false)
navigate({
to: "/dashboards/$name",
params: { name: created.name },
to: "/dashboards/$id",
params: { id: created.id! },
search: { edit: true },
})
},
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
// is based on — so the list already holds everything this needs.
const publishAll = usePublishAll(
@@ -66,11 +72,12 @@ function Dashboards() {
DashboardsService.publishDashboard({
dashboardId: dashboard,
requestBody: {
version: data?.data.find((d) => d.name === dashboard)?.version ?? 1,
version: data?.data.find((d) => d.id === dashboard)?.version ?? 1,
},
}),
"dashboard",
() => queryClient.invalidateQueries({ queryKey: dashboardKeys.all }),
labelOf,
)
// The store only accepts this shape, so say so before the request does.
@@ -84,14 +91,15 @@ function Dashboards() {
)
const drafts = (data?.data ?? [])
.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(
(dashboard) =>
DashboardsService.deleteDashboard({ dashboardId: dashboard }),
"dashboard",
() => queryClient.invalidateQueries({ queryKey: dashboardKeys.all }),
labelOf,
)
const duplicate = useDuplicateSelected(
@@ -102,6 +110,7 @@ function Dashboards() {
selection.clear()
queryClient.invalidateQueries({ queryKey: dashboardKeys.all })
},
labelOf,
)
return (
@@ -167,7 +176,7 @@ function Dashboards() {
<ConfirmDelete
open={deleteOpen}
onOpenChange={setDeleteOpen}
names={selection.selected}
names={selection.selected.map(labelOf)}
noun="dashboard"
pending={remove.isPending}
onConfirm={() => {
@@ -192,10 +201,10 @@ function Dashboards() {
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{dashboards.map((dashboard) => (
<OverviewCard
key={dashboard.name}
key={dashboard.id}
link={{
to: "/dashboards/$name",
params: { name: dashboard.name },
to: "/dashboards/$id",
params: { id: dashboard.id! },
}}
icon={LayoutDashboard}
title={dashboard.title || dashboard.name}
@@ -204,8 +213,8 @@ function Dashboards() {
dashboard.widget_count === 1 ? "" : "s"
}`}
selecting={selection.selecting}
selected={selection.selected.includes(dashboard.name)}
onToggle={() => selection.toggle(dashboard.name)}
selected={selection.selected.includes(dashboard.id!)}
onToggle={() => selection.toggle(dashboard.id!)}
testId="dashboard-card"
/>
))}
+24 -12
View File
@@ -47,20 +47,29 @@ function Flows() {
const [deleteOpen, setDeleteOpen] = 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({
mutationFn: (flow: string) =>
FlowsService.saveFlow({
flowId: flow,
FlowsService.createFlow({
requestBody: { name: flow, nodes: [], inputs: [] },
}),
onSuccess: (_saved, flow) => {
onSuccess: (created) => {
queryClient.invalidateQueries({ queryKey: flowKeys.all })
setDialogOpen(false)
navigate({ to: "/flows/$flowName", params: { flowName: flow } })
navigate({
to: "/flows/$flowId",
params: { flowId: created.definition.id! },
})
},
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
// is based on — so the list already holds everything this needs.
const publishAll = usePublishAll(
@@ -68,11 +77,12 @@ function Flows() {
FlowsService.publishFlow({
flowId: flow,
requestBody: {
version: data?.data.find((f) => f.name === flow)?.version ?? 1,
version: data?.data.find((f) => f.id === flow)?.version ?? 1,
},
}),
"flow",
() => queryClient.invalidateQueries({ queryKey: flowKeys.all }),
labelOf,
)
const slug = name
@@ -85,9 +95,9 @@ function Flows() {
)
const drafts = (data?.data ?? [])
.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(
async (flow) => {
await FlowsService.deleteFlow({ flowId: flow })
@@ -95,6 +105,7 @@ function Flows() {
},
"flow",
() => queryClient.invalidateQueries({ queryKey: flowKeys.all }),
labelOf,
)
const duplicate = useDuplicateSelected(
@@ -104,6 +115,7 @@ function Flows() {
selection.clear()
queryClient.invalidateQueries({ queryKey: flowKeys.all })
},
labelOf,
)
return (
@@ -173,7 +185,7 @@ function Flows() {
<ConfirmDelete
open={deleteOpen}
onOpenChange={setDeleteOpen}
names={selection.selected}
names={selection.selected.map(labelOf)}
noun="flow"
pending={remove.isPending}
onConfirm={() => {
@@ -204,8 +216,8 @@ function Flows() {
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{flows.map((flow) => (
<OverviewCard
key={flow.name}
link={{ to: "/flows/$flowName", params: { flowName: flow.name } }}
key={flow.id}
link={{ to: "/flows/$flowId", params: { flowId: flow.id! } }}
icon={Workflow}
title={flow.title || flow.name}
draft={flow.has_draft}
@@ -215,8 +227,8 @@ function Flows() {
flow.error_count ? ` · ${flow.error_count} to fix` : ""
}`}
selecting={selection.selecting}
selected={selection.selected.includes(flow.name)}
onToggle={() => selection.toggle(flow.name)}
selected={selection.selected.includes(flow.id!)}
onToggle={() => selection.toggle(flow.id!)}
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
* 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
* workshop tablet can carry different sets without either dashboard knowing
* anything about the other.
@@ -51,7 +51,7 @@ function PanelRoute() {
const { data: panel } = useQuery(deviceQueryOptions(id))
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.
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
// 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.
const shown = dashboard?.name
const [turned, setTurned] = useState({ name: shown, by: 1 })
if (shown !== turned.name) {
const shown = dashboard?.id
const [turned, setTurned] = useState({ id: shown, by: 1 })
if (shown !== turned.id) {
const by =
dashboards.indexOf(shown ?? "") - dashboards.indexOf(turned.name ?? "")
setTurned({ name: shown, by: by < 0 ? -1 : 1 })
dashboards.indexOf(shown ?? "") - dashboards.indexOf(turned.id ?? "")
setTurned({ id: shown, by: by < 0 ? -1 : 1 })
}
// 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
@@ -151,10 +151,10 @@ function PanelRoute() {
dashboards={dashboards}
current={current}
horizontal={stacked}
linkFor={(name) => ({
linkFor={(dashboardId) => ({
to: "/panel/$id",
params: { id },
search: { d: name },
search: { d: dashboardId },
})}
/>
) : 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
* 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.
*
* 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
* 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,
beforeLoad: async () => {
if (!isLoggedIn()) {
@@ -40,15 +40,14 @@ export const Route = createFileRoute("/view/$name")({
runs:
typeof search.runs === "string" && search.runs ? search.runs : undefined,
}),
head: ({ params }) => ({ meta: [{ title: `${params.name} - Fluksio` }] }),
})
function PanelView() {
const { name } = Route.useParams()
const { id } = Route.useParams()
const { runs } = Route.useSearch()
const navigate = useNavigate()
useFlowSocket()
const { data: dashboard } = useQuery(dashboardQueryOptions(name))
const { data: dashboard } = useQuery(dashboardQueryOptions(id))
const stacked = useIsMobile()
const runIds = runIdsOf(runs)
// A tab pointed at one dashboard is that dashboard, so its appearance
@@ -73,14 +72,16 @@ function PanelView() {
)}
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 ? (
<RunsContextProvider runIds={runIds} dashboard={dashboard as Dashboard}>
<ContextBarFor
members={runIds}
onChange={(next) =>
navigate({
to: "/view/$name",
params: { name },
to: "/view/$id",
params: { id },
search: next.length ? { runs: next.join(",") } : {},
})
}
+5 -3
View File
@@ -1,7 +1,9 @@
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)}`
/** Issued by the server when the first test creates it in the app. */
let flowId = ""
const KEY = "fluksio.nodeClipboard"
declare global {
@@ -17,7 +19,7 @@ test.use({
})
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 }) => {
@@ -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-name").fill(flowName)
await page.getByTestId("create-flow").click()
await page.waitForURL(`/flows/${flowName}`)
flowId = await openedFlowId(page)
await page.getByTestId("add-node").click()
await page
+51 -51
View File
@@ -1,6 +1,12 @@
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.
@@ -27,27 +33,24 @@ test.beforeAll(async ({ browser }) => {
// 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
// under test, not a flow.
const madeFlow = await api(page, `/flows/${flowName}`, {
method: "PUT",
data: {
name: flowName,
title: "Colour drag",
version: 1,
nodes: [
{
id: "lamp",
type: "python",
provides: [
{ name: "tint", dtype: "list", item: "float" },
{ name: "rgb", dtype: "list", item: "int" },
{ name: "hex", dtype: "str" },
],
},
],
},
const madeFlow = await createFlow(page, {
name: flowName,
title: "Colour drag",
version: 1,
nodes: [
{
id: "lamp",
type: "python",
provides: [
{ name: "tint", dtype: "list", item: "float" },
{ name: "rgb", dtype: "list", item: "int" },
{ name: "hex", dtype: "str" },
],
},
],
})
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()
await api(page, `/flows/${flowName}/publish`, {
method: "POST",
@@ -65,38 +68,35 @@ test.beforeAll(async ({ browser }) => {
}
// 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" })
const madeBoard = await api(page, `/dashboards/${dashboard}`, {
method: "PUT",
data: {
name: dashboard,
title: "Colour drag",
version: 0,
widgets: [
{
id: "tint",
type: "color",
title: "Tint",
layout: { lg: { x: 0, y: 0, w: 6, h: 4 } },
config: { target, dtype: "list", format: "hsv" },
},
{
id: "rgb",
type: "color",
title: "RGB",
layout: { lg: { x: 6, y: 0, w: 3, h: 4 } },
config: { target: `${flowName}.rgb`, dtype: "list", format: "rgb" },
},
{
id: "hex",
type: "color",
title: "Hex",
layout: { lg: { x: 9, y: 0, w: 3, h: 4 } },
config: { target: `${flowName}.hex`, dtype: "str", format: "hex" },
},
],
},
const madeBoard = await createDashboard(page, {
name: dashboard,
title: "Colour drag",
version: 0,
widgets: [
{
id: "tint",
type: "color",
title: "Tint",
layout: { lg: { x: 0, y: 0, w: 6, h: 4 } },
config: { target, dtype: "list", format: "hsv" },
},
{
id: "rgb",
type: "color",
title: "RGB",
layout: { lg: { x: 6, y: 0, w: 3, h: 4 } },
config: { target: `${flowName}.rgb`, dtype: "list", format: "rgb" },
},
{
id: "hex",
type: "color",
title: "Hex",
layout: { lg: { x: 9, y: 0, w: 3, h: 4 } },
config: { target: `${flowName}.hex`, dtype: "str", format: "hex" },
},
],
})
if (!madeBoard.ok())
throw new Error(
+13 -11
View File
@@ -1,5 +1,5 @@
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
@@ -8,13 +8,15 @@ import { api, deleteAll } from "./utils/api"
*/
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.describe.configure({ mode: "serial" })
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 }) => {
@@ -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-name").fill(flowName)
await page.getByTestId("create-flow").click()
await page.waitForURL(`/flows/${flowName}`)
flowId = await openedFlowId(page)
await page.getByTestId("add-node").click()
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.
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)
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("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)
})
test("a save against a version someone else moved on from is refused", async ({
page,
}) => {
await page.goto(`/flows/${flowName}`)
await page.goto(`/flows/${flowId}`)
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.
const first = await api(page, `/flows/${flowName}`, {
const first = await api(page, `/flows/${flowId}`, {
method: "PUT",
data: { ...detail.definition, title: "Theirs" },
})
expect(first.ok()).toBeTruthy()
const stale = await api(page, `/flows/${flowName}`, {
const stale = await api(page, `/flows/${flowId}`, {
method: "PUT",
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 }) => {
await page.goto(`/flows/${flowName}`)
await page.goto(`/flows/${flowId}`)
await page.waitForSelector(".react-flow__node")
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("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.definition.title).not.toBe("Theirs")
})
+2 -2
View File
@@ -1,5 +1,5 @@
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.
@@ -41,7 +41,7 @@ test.describe.configure({ mode: "serial" })
test.beforeAll(async ({ 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 draft, so the setup writes one rather than publishing.
const dashboard = await (
+29 -26
View File
@@ -1,5 +1,11 @@
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.
@@ -21,30 +27,27 @@ test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser)
// A flow reading a message, and a dashboard control that sets it.
await api(page, `/flows/${flowName}`, {
method: "PUT",
data: {
name: flowName,
nodes: [
{
id: "sink",
type: "python",
requires: [
{ name: "level", port: "level", dtype: "float" },
{ name: "ceiling", port: "ceiling", dtype: "float" },
],
provides: [],
},
],
inputs: [
{ spec: { name: "level", port: "level", dtype: "float" }, initial: 0 },
{
spec: { name: "ceiling", port: "ceiling", dtype: "float" },
initial: 30,
},
],
version: 1,
},
await createFlow(page, {
name: flowName,
nodes: [
{
id: "sink",
type: "python",
requires: [
{ name: "level", port: "level", dtype: "float" },
{ name: "ceiling", port: "ceiling", dtype: "float" },
],
provides: [],
},
],
inputs: [
{ spec: { name: "level", port: "level", dtype: "float" }, initial: 0 },
{
spec: { name: "ceiling", port: "ceiling", dtype: "float" },
initial: 30,
},
],
version: 1,
})
const saved = await (await api(page, `/flows/${flowName}`)).json()
await api(page, `/flows/${flowName}/publish`, {
@@ -53,7 +56,7 @@ test.beforeAll(async ({ browser }) => {
})
const dashboard = await (
await api(page, `/dashboards/${dashboardName}`, { method: "POST" })
await createDashboard(page, { name: dashboardName })
).json()
dashboard.widgets = [
{
+44 -47
View File
@@ -1,6 +1,6 @@
import { expect, type Page, test } from "@playwright/test"
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
@@ -9,20 +9,22 @@ import { api, deleteAll } from "./utils/api"
*/
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.describe.configure({ mode: "serial" })
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. */
async function setNodeSource(page: Page, nodeId: string, code: string) {
const token = await page.evaluate(() => localStorage.getItem("access_token"))
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 } },
)
expect(response.ok()).toBeTruthy()
@@ -32,7 +34,7 @@ async function setNodeSource(page: Page, nodeId: string, code: string) {
async function nodeSource(page: Page, nodeId: string) {
const token = await page.evaluate(() => localStorage.getItem("access_token"))
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}` } },
)
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-name").fill(flowName)
await page.getByTestId("create-flow").click()
await page.waitForURL(`/flows/${flowName}`)
flowId = await openedFlowId(page)
await addFunctionNode(page, 1)
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 }) => {
await page.goto(`/flows/${flowName}`)
await page.goto(`/flows/${flowId}`)
await page.waitForSelector(".react-flow__node")
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.
*/
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.locator(".react-flow__node").first().click()
@@ -156,28 +158,25 @@ 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)}`
await page.goto("/")
const saved = await api(page, `/flows/${name}`, {
method: "PUT",
data: {
name,
nodes: [
{
id: "reader",
type: "python",
requires: [
{ name: "command", port: "prompt", dtype: "str" },
{ name: "outdoor", dtype: "float" },
{ name: "a.level", dtype: "float" },
{ name: "b.level", dtype: "float" },
],
provides: [
{ name: "setpoint", port: "living_room_setpoint", dtype: "float" },
{ name: "pv_kw", dtype: "float" },
],
},
],
inputs: [],
},
const saved = await createFlow(page, {
name,
nodes: [
{
id: "reader",
type: "python",
requires: [
{ name: "command", port: "prompt", dtype: "str" },
{ name: "outdoor", dtype: "float" },
{ name: "a.level", dtype: "float" },
{ name: "b.level", dtype: "float" },
],
provides: [
{ name: "setpoint", port: "living_room_setpoint", dtype: "float" },
{ name: "pv_kw", dtype: "float" },
],
},
],
inputs: [],
})
expect(saved.ok()).toBeTruthy()
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 text = "# level, other = 1, 2"
await page.goto("/")
const saved = await api(page, `/flows/${name}`, {
method: "PUT",
data: { name, nodes: [{ id: "writer", type: "python" }], inputs: [] },
const saved = await createFlow(page, {
name,
nodes: [{ id: "writer", type: "python" }],
inputs: [],
})
expect(saved.ok()).toBeTruthy()
try {
@@ -262,21 +262,18 @@ test("code typed into a node's editor is saved", async ({ page }) => {
test("a JSON setting saves only text that parses", async ({ page }) => {
const name = `test_json_${Date.now().toString(36)}`
await page.goto("/")
const saved = await api(page, `/flows/${name}`, {
method: "PUT",
data: {
name,
nodes: [
{
id: "gate",
type: "switch",
params: { rules: [], otherwise: "" },
requires: [{ name: "level", dtype: "float" }],
provides: [{ name: "high", dtype: "float" }],
},
],
inputs: [],
},
const saved = await createFlow(page, {
name,
nodes: [
{
id: "gate",
type: "switch",
params: { rules: [], otherwise: "" },
requires: [{ name: "level", dtype: "float" }],
provides: [{ name: "high", dtype: "float" }],
},
],
inputs: [],
})
expect(saved.ok()).toBeTruthy()
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`)
})
+16 -19
View File
@@ -1,5 +1,5 @@
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
@@ -18,24 +18,21 @@ test.use({ storageState: "playwright/.auth/user.json" })
test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser)
await api(page, `/flows/${flowName}`, {
method: "PUT",
data: {
name: flowName,
title: "Live",
nodes: [
{
id: "source",
type: "python",
provides: [{ name: "reading", dtype: "float" }],
},
{
id: "sink",
type: "python",
requires: [{ name: "reading", dtype: "float" }],
},
],
},
await createFlow(page, {
name: flowName,
title: "Live",
nodes: [
{
id: "source",
type: "python",
provides: [{ name: "reading", dtype: "float" }],
},
{
id: "sink",
type: "python",
requires: [{ name: "reading", dtype: "float" }],
},
],
})
const detail = await (await api(page, `/flows/${flowName}`)).json()
await api(page, `/flows/${flowName}/publish`, {
+51 -51
View File
@@ -1,5 +1,11 @@
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
@@ -81,31 +87,28 @@ test.beforeAll(async ({ browser }) => {
// 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.
await api(page, `/flows/${flowName}`, {
method: "PUT",
data: {
name: flowName,
title: "Mobile",
nodes: [
{
id: "source",
type: "python",
provides: [{ name: "reading", dtype: "float" }],
},
{
id: "scale",
type: "python",
requires: [{ name: "reading", dtype: "float" }],
provides: [{ name: "scaled", dtype: "float" }],
},
...["one", "two", "three", "four"].map((id) => ({
id,
type: "python",
requires: [{ name: "scaled", dtype: "float" }],
})),
],
version: 1,
},
await createFlow(page, {
name: flowName,
title: "Mobile",
nodes: [
{
id: "source",
type: "python",
provides: [{ name: "reading", dtype: "float" }],
},
{
id: "scale",
type: "python",
requires: [{ name: "reading", dtype: "float" }],
provides: [{ name: "scaled", dtype: "float" }],
},
...["one", "two", "three", "four"].map((id) => ({
id,
type: "python",
requires: [{ name: "scaled", dtype: "float" }],
})),
],
version: 1,
})
const saved = await (await api(page, `/flows/${flowName}`)).json()
await api(page, `/flows/${flowName}/publish`, {
@@ -113,29 +116,26 @@ test.beforeAll(async ({ browser }) => {
data: { version: saved.definition.version },
})
await api(page, `/flows/${feedName}`, {
method: "PUT",
data: {
name: feedName,
title: "Feed",
version: 1,
nodes: [
{
id: "emit",
type: "python",
provides: [
{ name: "level", dtype: "float" },
{ name: "pv", dtype: "float" },
{ name: "days", dtype: "list", item: "record" },
// Long, and with nothing to break at: an unlabelled series puts
// this whole name in the chart's legend.
{ name: "climate_series_reading", dtype: "float" },
{ name: "mode", dtype: "str" },
{ name: "lamp", dtype: "bool" },
],
},
],
},
await createFlow(page, {
name: feedName,
title: "Feed",
version: 1,
nodes: [
{
id: "emit",
type: "python",
provides: [
{ name: "level", dtype: "float" },
{ name: "pv", dtype: "float" },
{ name: "days", dtype: "list", item: "record" },
// Long, and with nothing to break at: an unlabelled series puts
// this whole name in the chart's legend.
{ name: "climate_series_reading", dtype: "float" },
{ name: "mode", dtype: "str" },
{ name: "lamp", dtype: "bool" },
],
},
],
})
const feed = await (await api(page, `/flows/${feedName}?draft=true`)).json()
await api(page, `/flows/${feedName}/publish`, {
@@ -175,7 +175,7 @@ test.beforeAll(async ({ browser }) => {
})
const dashboard = await (
await api(page, `/dashboards/${dashboardName}`, { method: "POST" })
await createDashboard(page, { name: dashboardName })
).json()
dashboard.widgets = [
{
@@ -274,7 +274,7 @@ test.beforeAll(async ({ browser }) => {
})
const locked = await (
await api(page, `/dashboards/${lockedName}`, { method: "POST" })
await createDashboard(page, { name: lockedName })
).json()
locked.settings = { ...(locked.settings ?? {}), locked: { value: true } }
locked.widgets = [
+22 -19
View File
@@ -1,5 +1,11 @@
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.
@@ -22,23 +28,20 @@ test.describe.configure({ mode: "serial" })
test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser)
await api(page, `/flows/${flowName}`, {
method: "PUT",
data: {
name: flowName,
title: "Panel",
version: 1,
nodes: [
{
id: "emit",
type: "python",
provides: [
{ name: "level", dtype: "float" },
{ name: "mode", dtype: "str" },
],
},
],
},
await createFlow(page, {
name: flowName,
title: "Panel",
version: 1,
nodes: [
{
id: "emit",
type: "python",
provides: [
{ name: "level", dtype: "float" },
{ name: "mode", dtype: "str" },
],
},
],
})
const flow = await (await api(page, `/flows/${flowName}?draft=true`)).json()
await api(page, `/flows/${flowName}/publish`, {
@@ -51,7 +54,7 @@ test.beforeAll(async ({ browser }) => {
})
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()
doc.settings = { look: { value: "glass" } }
doc.widgets = [
+12 -16
View File
@@ -1,5 +1,5 @@
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.
@@ -48,21 +48,17 @@ test.describe.configure({ mode: "serial" })
test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser)
// Version 0 creates: a first draft is what a save of a name nobody has used
// yet means, and the editor reads the draft.
const made = await api(page, `/dashboards/${dashboardName}`, {
method: "PUT",
data: {
name: dashboardName,
title: "Persistence",
icon: "layout-dashboard",
columns: 12,
canvas_width: 1920,
canvas_height: 1080,
version: 0,
widgets: [MOVED, KEPT],
settings: SETTINGS,
},
// Created as a draft, which is what the editor reads.
const made = await createDashboard(page, {
name: dashboardName,
title: "Persistence",
icon: "layout-dashboard",
columns: 12,
canvas_width: 1920,
canvas_height: 1080,
version: 0,
widgets: [MOVED, KEPT],
settings: SETTINGS,
})
if (!made.ok())
throw new Error(`dashboard PUT ${made.status()}: ${await made.text()}`)
+39 -39
View File
@@ -1,6 +1,12 @@
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.
@@ -21,20 +27,17 @@ test.describe.configure({ mode: "serial" })
test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser)
// One node that only declares: a publish lands without waking a run.
await api(page, `/flows/${flowName}`, {
method: "PUT",
data: {
name: flowName,
title: "Ring",
version: 1,
nodes: [
{
id: "emit",
type: "python",
provides: [{ name: "level", dtype: "float" }],
},
],
},
await createFlow(page, {
name: flowName,
title: "Ring",
version: 1,
nodes: [
{
id: "emit",
type: "python",
provides: [{ name: "level", dtype: "float" }],
},
],
})
const flow = await (await api(page, `/flows/${flowName}?draft=true`)).json()
await api(page, `/flows/${flowName}/publish`, {
@@ -43,30 +46,27 @@ test.beforeAll(async ({ browser }) => {
})
await api(page, `/dashboards/${dashboard}`, { method: "DELETE" })
const made = await api(page, `/dashboards/${dashboard}`, {
method: "PUT",
data: {
name: dashboard,
title: "Ring",
version: 0,
canvas_width: 360,
canvas_height: 360,
shape: "round",
widgets: [
{
id: "level",
type: "slider",
title: "Level",
config: { target, dtype: "float", min: 0, max: 10, step: 0.5 },
},
{
id: "note",
type: "markdown",
title: "Note",
config: { content: "The second face" },
},
],
},
const made = await createDashboard(page, {
name: dashboard,
title: "Ring",
version: 0,
canvas_width: 360,
canvas_height: 360,
shape: "round",
widgets: [
{
id: "level",
type: "slider",
title: "Level",
config: { target, dtype: "float", min: 0, max: 10, step: 0.5 },
},
{
id: "note",
type: "markdown",
title: "Note",
config: { content: "The second face" },
},
],
})
if (!made.ok())
throw new Error(`dashboard PUT ${made.status()}: ${await made.text()}`)
+21 -24
View File
@@ -1,5 +1,5 @@
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.
@@ -28,29 +28,26 @@ test.afterAll(async ({ browser }) => {
test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser)
await api(page, `/flows/${flowName}`, {
method: "PUT",
data: {
name: flowName,
title: "Runs under test",
// `rate` is declared and never passed, which is what puts its declared
// value in the Inputs panel below.
inputs: [
{ spec: { name: "epochs", dtype: "int" }, initial: 2 },
{ spec: { name: "rate", dtype: "float" }, initial: 0.5 },
],
nodes: [
{
id: "train",
type: "python",
requires: [{ name: "epochs", dtype: "int" }],
provides: [
{ name: "loss", dtype: "float", stream: true },
{ name: "score", dtype: "float" },
],
},
],
},
await createFlow(page, {
name: flowName,
title: "Runs under test",
// `rate` is declared and never passed, which is what puts its declared
// value in the Inputs panel below.
inputs: [
{ spec: { name: "epochs", dtype: "int" }, initial: 2 },
{ spec: { name: "rate", dtype: "float" }, initial: 0.5 },
],
nodes: [
{
id: "train",
type: "python",
requires: [{ name: "epochs", dtype: "int" }],
provides: [
{ name: "loss", dtype: "float", stream: true },
{ name: "score", dtype: "float" },
],
},
],
})
await api(page, `/flows/${flowName}/nodes/train/source`, {
method: "PUT",
+16 -19
View File
@@ -1,5 +1,5 @@
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
@@ -29,24 +29,21 @@ test.afterAll(async ({ browser }) => {
test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser)
await api(page, `/flows/${flowName}`, {
method: "PUT",
data: {
name: flowName,
title: "Runtime",
nodes: [
{
id: "sensor",
type: "python",
provides: [{ name: "reading", dtype: "float" }],
},
{
id: "logger",
type: "python",
requires: [{ name: "reading", dtype: "float" }],
},
],
},
await createFlow(page, {
name: flowName,
title: "Runtime",
nodes: [
{
id: "sensor",
type: "python",
provides: [{ name: "reading", dtype: "float" }],
},
{
id: "logger",
type: "python",
requires: [{ name: "reading", dtype: "float" }],
},
],
})
await api(page, `/flows/${flowName}/nodes/sensor/source`, {
method: "PUT",
+13 -16
View File
@@ -1,5 +1,5 @@
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.
@@ -16,21 +16,18 @@ test.describe.configure({ mode: "serial" })
test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser)
await api(page, `/flows/${flowName}`, {
method: "PUT",
data: {
name: flowName,
title: "Searchable flow",
nodes: [
{
id: "findme",
type: "python",
title: "Find me",
params: { tuning_gain: 7, api_token: "s3cr3t-token" },
},
],
inputs: [{ spec: { name: "findme_input", dtype: "float" } }],
},
await createFlow(page, {
name: flowName,
title: "Searchable flow",
nodes: [
{
id: "findme",
type: "python",
title: "Find me",
params: { tuning_gain: 7, api_token: "s3cr3t-token" },
},
],
inputs: [{ spec: { name: "findme_input", dtype: "float" } }],
})
await page.close()
})
+41 -41
View File
@@ -1,6 +1,12 @@
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.
@@ -20,56 +26,50 @@ test.describe.configure({ mode: "serial" })
test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser)
const madeFlow = await api(page, `/flows/${flowName}`, {
method: "PUT",
data: {
name: flowName,
title: "Slider drag",
version: 1,
nodes: [
{
id: "level",
type: "python",
title: "Level",
requires: [{ name: "level", dtype: "float" }],
provides: [{ name: "echo", dtype: "float" }],
},
],
inputs: [{ spec: { name: "level", dtype: "float" }, initial: 0 }],
},
const madeFlow = await createFlow(page, {
name: flowName,
title: "Slider drag",
version: 1,
nodes: [
{
id: "level",
type: "python",
title: "Level",
requires: [{ name: "level", dtype: "float" }],
provides: [{ name: "echo", dtype: "float" }],
},
],
inputs: [{ spec: { name: "level", dtype: "float" }, initial: 0 }],
})
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`, {
method: "PUT",
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
// create with a version conflict.
// create with a conflict.
await api(page, `/dashboards/${dashboard}`, { method: "DELETE" })
const madeBoard = await api(page, `/dashboards/${dashboard}`, {
method: "PUT",
data: {
name: dashboard,
title: "Slider drag",
version: 0,
widgets: [
{
id: "level",
type: "slider",
title: "Level",
layout: { lg: { x: 0, y: 0, w: 6, h: 3 } },
config: {
target: `${flowName}.level`,
dtype: "float",
min: 0,
max: 100,
step: 1,
},
const madeBoard = await createDashboard(page, {
name: dashboard,
title: "Slider drag",
version: 0,
widgets: [
{
id: "level",
type: "slider",
title: "Level",
layout: { lg: { x: 0, y: 0, w: 6, h: 3 } },
config: {
target: `${flowName}.level`,
dtype: "float",
min: 0,
max: 100,
step: 1,
},
],
},
},
],
})
if (!madeBoard.ok())
throw new Error(
+47
View File
@@ -32,6 +32,53 @@ export async function apiPage(browser: Browser) {
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. */
export async function deleteAll(browser: Browser, paths: string[]) {
const page = await apiPage(browser)
+15 -18
View File
@@ -1,5 +1,5 @@
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
@@ -21,23 +21,20 @@ test.describe.configure({ mode: "serial" })
test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser)
await api(page, `/flows/${flowName}`, {
method: "PUT",
data: {
name: flowName,
title: "Values",
version: 1,
nodes: [
{
id: "emit",
type: "python",
provides: [
{ name: "shape", dtype: "record" },
{ name: "label", dtype: "str" },
],
},
],
},
await createFlow(page, {
name: flowName,
title: "Values",
version: 1,
nodes: [
{
id: "emit",
type: "python",
provides: [
{ name: "shape", dtype: "record" },
{ name: "label", dtype: "str" },
],
},
],
})
// Saving writes a draft and moves the version on, so publish what is
// actually there rather than what it was a moment ago.
+32 -31
View File
@@ -1,5 +1,11 @@
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.
@@ -39,31 +45,28 @@ test.beforeAll(async ({ browser }) => {
// One node that only declares: nothing consumes these, so publishing a value
// fills the panel without waking an engine run.
await api(page, `/flows/${flowName}`, {
method: "PUT",
data: {
name: flowName,
title: "Widgets",
version: 1,
nodes: [
{
id: "emit",
type: "python",
provides: [
{ name: "level", dtype: "float" },
{ name: "pv", dtype: "float" },
{ name: "grid", dtype: "float" },
{ name: "condition", dtype: "str" },
{ name: "days", dtype: "list", item: "record" },
{ name: "mode", dtype: "str" },
{ name: "lamp", dtype: "bool" },
{ name: "setpoint", dtype: "float" },
{ name: "idle", dtype: "float" },
{ name: "tint", dtype: "list", item: "float" },
],
},
],
},
await createFlow(page, {
name: flowName,
title: "Widgets",
version: 1,
nodes: [
{
id: "emit",
type: "python",
provides: [
{ name: "level", dtype: "float" },
{ name: "pv", dtype: "float" },
{ name: "grid", dtype: "float" },
{ name: "condition", dtype: "str" },
{ name: "days", dtype: "list", item: "record" },
{ name: "mode", dtype: "str" },
{ name: "lamp", dtype: "bool" },
{ name: "setpoint", dtype: "float" },
{ name: "idle", dtype: "float" },
{ name: "tint", dtype: "list", item: "float" },
],
},
],
})
// Saving writes a draft and moves the version on, so publish what is
// actually there rather than what it was a moment ago.
@@ -92,7 +95,7 @@ test.beforeAll(async ({ browser }) => {
])
const dashboard = await (
await api(page, `/dashboards/${dashboardName}`, { method: "POST" })
await createDashboard(page, { name: dashboardName })
).json()
// 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.
@@ -236,9 +239,7 @@ test.beforeAll(async ({ browser }) => {
data: { version: draft.version },
})
const stack = await (
await api(page, `/dashboards/${stackName}`, { method: "POST" })
).json()
const stack = await (await createDashboard(page, { name: stackName })).json()
stack.widgets = [
{
id: "split",
@@ -284,7 +285,7 @@ test.beforeAll(async ({ browser }) => {
})
const locked = await (
await api(page, `/dashboards/${lockedName}`, { method: "POST" })
await createDashboard(page, { name: lockedName })
).json()
locked.settings = { ...(locked.settings ?? {}), locked: { value: true } }
locked.widgets = [