Button gains a danger variant and an autofocus prop; ConfirmDialog gains danger (red confirm, focus on cancel). Destroy, delete linked account, delete claude login, remove schedule and delete flow use it. New useConfirm hook asks from inside a handler (await confirm({...})) without a dialog's state at the call site. It now guards: removing a swarm-wide egress domain, removing a domain for every agent from an agent's popover, removing a stored API-key environment, firing a schedule now, moving an agent's internet to a looser mode, the /clear message, and reload over unsaved instructions (replacing window.confirm). The review try-out's button is now called push a branch for a PR, since it pushes a branch and does not open one, and asks first. loosensInternet is a tested helper.
436 lines
14 KiB
TypeScript
436 lines
14 KiB
TypeScript
// <FlowEditorPage> — edit one custom notification flow: a canvas of its
|
|
// nodes, an inspector for the picked one, and a Save that sends the whole
|
|
// document back at the revision it was read. Edits stay in a draft until
|
|
// then, so a half-built flow never reaches the router.
|
|
//
|
|
// The same page makes a flow: `NEW_FLOW_PATH` is an empty draft, and
|
|
// `?from=<id>` a copy of a flow to start from. Nothing exists until Save, which
|
|
// gives the flow an id made of its name.
|
|
//
|
|
// The controller is the authority on what may be saved; its refusal is shown
|
|
// as it comes. A save at an old revision is told apart from that: the flows
|
|
// were changed elsewhere, and the editor offers to reload or to keep the draft
|
|
// on top of the latest.
|
|
import { useCallback, useEffect, useState } from "preact/hooks";
|
|
import { usePageTitle } from "../../shell/page-title.js";
|
|
import {
|
|
Link,
|
|
useLocation,
|
|
useSearch,
|
|
type RouteComponentProps,
|
|
} from "wouter-preact";
|
|
import { ApiErrorPanel } from "@hive/shared/api-error-panel.js";
|
|
import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
|
|
import { Button } from "../../ui/button/Button.js";
|
|
import { CheckboxField } from "../../ui/checkbox-field/CheckboxField.js";
|
|
import { ActionRow } from "../../ui/action-row/ActionRow.js";
|
|
import { ConfirmDialog } from "../../ui/confirm-dialog/ConfirmDialog.js";
|
|
import { Hint } from "../../ui/hint/Hint.js";
|
|
import { Panel } from "../../ui/panel/Panel.js";
|
|
import { SkeletonLines } from "../../ui/skeleton/Skeleton.js";
|
|
import { TextField } from "../../ui/text-field/TextField.js";
|
|
import { fetchJson, ProblemError } from "../../ui/polled/usePolled.js";
|
|
import { FlowCanvas } from "./FlowCanvas.js";
|
|
import {
|
|
addChild,
|
|
blankNode,
|
|
isDirty,
|
|
limitsOf,
|
|
moveAmongSiblings,
|
|
paletteKinds,
|
|
removeNode,
|
|
reparent,
|
|
savedAs,
|
|
saveOutcome,
|
|
previewRequest,
|
|
saveRequest,
|
|
disabledOnSave,
|
|
seedFlow,
|
|
parentOf,
|
|
withFlow,
|
|
withoutFlow,
|
|
type Edit,
|
|
} from "./FlowDraft.js";
|
|
import { useLeaveGuard } from "./useLeaveGuard.js";
|
|
import { NodeInspector } from "./NodeInspector.js";
|
|
import { markersIn, SOURCE_URLS, type Sources } from "./FlowChoices.js";
|
|
import { FALLBACK_SCHEMA, type Flow, type FlowsView } from "./FlowTypes.js";
|
|
import { DRY_RUN_URL, hitsOf, type DryRun } from "./RouterLive.js";
|
|
import "./NotificationsPage.css";
|
|
|
|
const FLOWS_URL = "/api/notify/flows";
|
|
|
|
function rootOf(flow: Flow): string | null {
|
|
return flow.nodes.find((n) => n.kind === "source")?.id ?? null;
|
|
}
|
|
|
|
export function FlowEditorPage({
|
|
params,
|
|
isNew = false,
|
|
}: RouteComponentProps<{ flowId: string }> & {
|
|
// The page for a flow not saved yet, which has no flow id.
|
|
isNew?: boolean;
|
|
}) {
|
|
const flowId = decodeURIComponent(params.flowId);
|
|
const search = new URLSearchParams(useSearch());
|
|
const from = search.get("from");
|
|
// With `from` an archetype flow: the one agent this copy is for.
|
|
const agent = search.get("agent");
|
|
const [, navigate] = useLocation();
|
|
usePageTitle(isNew ? "new flow" : `flow ${flowId}`);
|
|
const [view, setView] = useState<FlowsView | null>(null);
|
|
const [draft, setDraft] = useState<Flow | null>(null);
|
|
// What a new draft started as, so leaving it untouched is not "unsaved".
|
|
const [seed, setSeed] = useState<Flow | null>(null);
|
|
const [selected, setSelected] = useState<string | null>(null);
|
|
const [loadError, setLoadError] = useState<ProblemDetails | null>(null);
|
|
const [saveError, setSaveError] = useState<ProblemDetails | null>(null);
|
|
const [stale, setStale] = useState(false);
|
|
const [notice, setNotice] = useState<string | null>(null);
|
|
// The last preview and the draft it ran, which stops counting once the
|
|
// draft is edited.
|
|
const [preview, setPreview] = useState<{
|
|
draft: Flow;
|
|
flowId: string;
|
|
dry: DryRun;
|
|
} | null>(null);
|
|
const [previewError, setPreviewError] = useState<ProblemDetails | null>(null);
|
|
const [sources, setSources] = useState<Sources>({});
|
|
const [busy, setBusy] = useState(false);
|
|
const [confirmDelete, setConfirmDelete] = useState(false);
|
|
|
|
// Read the flows. With `keepDraft` the edits stay and only the revision
|
|
// they will be saved at moves on.
|
|
const load = useCallback(
|
|
async (keepDraft: boolean) => {
|
|
try {
|
|
const next = await fetchJson<FlowsView>(
|
|
FLOWS_URL,
|
|
new AbortController().signal,
|
|
);
|
|
setView(next);
|
|
setLoadError(null);
|
|
setStale(false);
|
|
setSaveError(null);
|
|
if (!keepDraft) {
|
|
const flow = isNew
|
|
? seedFlow(next, from, agent)
|
|
: next.flows.find((f) => f.id === flowId);
|
|
setSeed(isNew && flow ? structuredClone(flow) : null);
|
|
setDraft(flow ? structuredClone(flow) : null);
|
|
setSelected(flow ? rootOf(flow) : null);
|
|
}
|
|
} catch (err) {
|
|
setLoadError(
|
|
err instanceof ProblemError ? err.problem : { detail: String(err) },
|
|
);
|
|
}
|
|
},
|
|
[flowId, isNew, from, agent],
|
|
);
|
|
useEffect(() => {
|
|
void load(false);
|
|
}, [load]);
|
|
|
|
// The lists the schema's values come from. One that cannot be fetched is
|
|
// left out and its field falls back to a box that takes any text.
|
|
const markers = view?.schema ? markersIn(view.schema).join(",") : "";
|
|
useEffect(() => {
|
|
const abort = new AbortController();
|
|
for (const marker of markers === "" ? [] : markers.split(",")) {
|
|
fetchJson<string[]>(SOURCE_URLS[marker], abort.signal)
|
|
.then((names) => setSources((all) => ({ ...all, [marker]: names })))
|
|
.catch(() => undefined);
|
|
}
|
|
return () => abort.abort();
|
|
}, [markers]);
|
|
|
|
const dirty =
|
|
view !== null &&
|
|
draft !== null &&
|
|
(isNew
|
|
? JSON.stringify(draft) !== JSON.stringify(seed)
|
|
: isDirty(view, withFlow(view.flows, draft), view.disabled_builtins));
|
|
|
|
// Leaving the page with edits not saved asks first, whether by closing the
|
|
// tab, following a link or pressing back.
|
|
const leaving = useLeaveGuard(dirty);
|
|
|
|
// Send `flows` and `disabled` as the document; true when the controller took it.
|
|
async function put(
|
|
flows: Flow[],
|
|
disabled: string[] = view?.disabled_builtins ?? [],
|
|
): Promise<boolean> {
|
|
if (!view) return false;
|
|
setBusy(true);
|
|
setSaveError(null);
|
|
try {
|
|
const r = await fetch(FLOWS_URL, saveRequest(view, flows, disabled));
|
|
const outcome = saveOutcome(r.status);
|
|
if (outcome === "saved") {
|
|
const next = (await r.json()) as FlowsView;
|
|
setView({ ...next, schema: next.schema ?? view.schema });
|
|
return true;
|
|
}
|
|
if (outcome === "conflict") setStale(true);
|
|
else setSaveError(await readApiError(r));
|
|
} catch (err) {
|
|
setSaveError({ detail: String(err) });
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// Run the draft, saved or not, over the newest forge events, and put the
|
|
// number each node would have caught on its box.
|
|
async function runPreview() {
|
|
if (!view || !draft) return;
|
|
const flow = isNew ? savedAs(view, draft) : draft;
|
|
setBusy(true);
|
|
setPreviewError(null);
|
|
try {
|
|
const r = await fetch(
|
|
DRY_RUN_URL,
|
|
previewRequest(withFlow(view.flows, flow), view.disabled_builtins),
|
|
);
|
|
if (r.ok) {
|
|
setPreview({ draft, flowId: flow.id, dry: (await r.json()) as DryRun });
|
|
} else {
|
|
setPreview(null);
|
|
setPreviewError(await readApiError(r));
|
|
}
|
|
} catch (err) {
|
|
setPreview(null);
|
|
setPreviewError({ detail: String(err) });
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
|
|
function onEdit(result: Edit, select?: string) {
|
|
if (!result.ok) {
|
|
setNotice(result.reason);
|
|
return;
|
|
}
|
|
setNotice(null);
|
|
setDraft(result.flow);
|
|
if (select !== undefined) setSelected(select);
|
|
else if (!result.flow.nodes.some((n) => n.id === selected)) {
|
|
setSelected(rootOf(result.flow));
|
|
}
|
|
}
|
|
|
|
// Save the draft. A new flow is added under its name's id, and the page
|
|
// moves on to editing it.
|
|
async function save() {
|
|
if (!view || !draft) return;
|
|
const flow = isNew ? savedAs(view, draft) : draft;
|
|
// The first save of a copy made for one agent also switches the
|
|
// archetype's flow off for it, in the same write.
|
|
const disabled = isNew
|
|
? disabledOnSave(view.disabled_builtins, from, agent)
|
|
: view.disabled_builtins;
|
|
if (!(await put(withFlow(view.flows, flow), disabled)) || !isNew) return;
|
|
leaving.release();
|
|
navigate(`/notifications/${encodeURIComponent(flow.id)}`, {
|
|
replace: true,
|
|
});
|
|
}
|
|
|
|
async function onDelete() {
|
|
if (!view) return;
|
|
setConfirmDelete(false);
|
|
if (await put(withoutFlow(view.flows, flowId))) {
|
|
// The flow is gone; there is nothing left to lose by leaving.
|
|
leaving.release();
|
|
navigate("/notifications");
|
|
}
|
|
}
|
|
|
|
const back = <Link href="/notifications">all flows</Link>;
|
|
|
|
if (loadError) {
|
|
return (
|
|
<Panel title="notification flow" icon="🔔" actions={back}>
|
|
<ApiErrorPanel context="failed to load the flows" problem={loadError} />
|
|
</Panel>
|
|
);
|
|
}
|
|
if (!view) {
|
|
return (
|
|
<Panel title="notification flow" icon="🔔" actions={back}>
|
|
<SkeletonLines label="the flow" />
|
|
</Panel>
|
|
);
|
|
}
|
|
if (!draft) {
|
|
const builtin = view.builtins.some((b) => b.id === flowId);
|
|
return (
|
|
<Panel title="notification flow" icon="🔔" actions={back}>
|
|
<p>
|
|
{isNew
|
|
? `There is no flow ${from} to copy; it may have been deleted.`
|
|
: builtin
|
|
? "A built-in flow cannot be edited: duplicate it from the list and edit the copy."
|
|
: `There is no flow ${flowId}; it may have been deleted.`}
|
|
</p>
|
|
</Panel>
|
|
);
|
|
}
|
|
|
|
const schema = view.schema ?? FALLBACK_SCHEMA;
|
|
const limits = limitsOf(view.schema);
|
|
const node = draft.nodes.find((n) => n.id === selected) ?? null;
|
|
const shown = preview?.draft === draft ? preview : null;
|
|
const hits = shown ? hitsOf(shown.dry, shown.flowId) : undefined;
|
|
|
|
return (
|
|
<Panel
|
|
title={isNew ? "new flow" : `flow ${draft.id}`}
|
|
icon="🔔"
|
|
actions={back}
|
|
>
|
|
{stale ? (
|
|
<div class="notify-stale" role="alert">
|
|
<p>
|
|
The flows were changed somewhere else since you opened this one, so
|
|
this was not saved.
|
|
</p>
|
|
<Button onClick={() => void load(false)}>
|
|
reload and drop my edits
|
|
</Button>
|
|
<Button onClick={() => void load(true)}>
|
|
keep my edits (replaces this flow's latest version)
|
|
</Button>
|
|
</div>
|
|
) : null}
|
|
{saveError ? (
|
|
<ApiErrorPanel context="the flow was not saved" problem={saveError} />
|
|
) : null}
|
|
{previewError ? (
|
|
<ApiErrorPanel
|
|
context="the preview did not run"
|
|
problem={previewError}
|
|
/>
|
|
) : null}
|
|
{notice ? (
|
|
<p class="notify-notice" role="status">
|
|
{notice}
|
|
</p>
|
|
) : null}
|
|
|
|
<div class="notify-editor-head">
|
|
<div class="notify-name">
|
|
<TextField
|
|
id="flow-name"
|
|
label="name"
|
|
value={draft.name}
|
|
placeholder="what the flow is for"
|
|
onInput={(name) => setDraft({ ...draft, name })}
|
|
/>
|
|
</div>
|
|
<CheckboxField
|
|
id="flow-enabled"
|
|
label="on"
|
|
checked={draft.enabled}
|
|
onChange={(enabled) => setDraft({ ...draft, enabled })}
|
|
/>
|
|
<ActionRow class="notify-editor-actions">
|
|
{dirty ? (
|
|
<Hint as="span" role="status" class="notify-hint">
|
|
not saved yet
|
|
</Hint>
|
|
) : null}
|
|
<Button
|
|
variant="primary"
|
|
disabled={(!isNew && !dirty) || busy || draft.name.trim() === ""}
|
|
onClick={() => void save()}
|
|
>
|
|
save
|
|
</Button>
|
|
<Button
|
|
disabled={!dirty || busy}
|
|
onClick={() => {
|
|
const start = isNew
|
|
? seed
|
|
: view.flows.find((f) => f.id === flowId);
|
|
if (start) setDraft(structuredClone(start));
|
|
setNotice(null);
|
|
}}
|
|
>
|
|
discard edits
|
|
</Button>
|
|
<Button disabled={busy} onClick={() => void runPreview()}>
|
|
preview
|
|
</Button>
|
|
{isNew ? null : (
|
|
<Button disabled={busy} onClick={() => setConfirmDelete(true)}>
|
|
delete flow
|
|
</Button>
|
|
)}
|
|
</ActionRow>
|
|
</div>
|
|
{shown ? (
|
|
<p class="notify-hint" role="status">
|
|
{hits
|
|
? `Preview: each box shows how many of the newest ${shown.dry.events} forge events reached it. Edit the flow and the numbers go.`
|
|
: "The preview skipped this flow because it is off."}
|
|
</p>
|
|
) : null}
|
|
|
|
<div class="notify-editor-body">
|
|
<FlowCanvas
|
|
flow={draft}
|
|
selected={selected}
|
|
limits={limits}
|
|
palette={paletteKinds(schema)}
|
|
hits={hits}
|
|
onSelect={setSelected}
|
|
onAdd={(kind, parentId) => {
|
|
const added = blankNode(draft, kind);
|
|
onEdit(addChild(draft, parentId, added, limits), added.id);
|
|
}}
|
|
onMove={(id, parentId) =>
|
|
onEdit(reparent(draft, id, parentId, limits), id)
|
|
}
|
|
onReorder={(id, delta) =>
|
|
onEdit(moveAmongSiblings(draft, id, delta), id)
|
|
}
|
|
onRemove={(id) => onEdit(removeNode(draft, id), parentOf(draft, id))}
|
|
onRefused={setNotice}
|
|
/>
|
|
{node ? (
|
|
<NodeInspector
|
|
flow={draft}
|
|
node={node}
|
|
schema={schema}
|
|
limits={limits}
|
|
sources={sources}
|
|
onEdit={onEdit}
|
|
/>
|
|
) : null}
|
|
</div>
|
|
|
|
<ConfirmDialog
|
|
open={confirmDelete}
|
|
label="delete this flow"
|
|
confirmLabel="delete"
|
|
danger
|
|
onCancel={() => setConfirmDelete(false)}
|
|
onConfirm={() => void onDelete()}
|
|
>
|
|
<p>Delete the flow {draft.name}? The router stops running it.</p>
|
|
</ConfirmDialog>
|
|
<ConfirmDialog
|
|
open={leaving.pending}
|
|
label="leave without saving"
|
|
confirmLabel="leave and drop edits"
|
|
onCancel={leaving.stay}
|
|
onConfirm={leaving.leave}
|
|
>
|
|
<p>This flow has edits that are not saved. Leaving drops them.</p>
|
|
</ConfirmDialog>
|
|
</Panel>
|
|
);
|
|
}
|