feat(workflow): orchestrate resumable dataflow handoffs

This commit is contained in:
2026-07-30 03:11:56 +02:00
parent a1654e70cf
commit a6e0e89829
18 changed files with 3938 additions and 27 deletions
@@ -0,0 +1,516 @@
import {
useCallback,
useEffect,
useMemo,
useState
} from "react";
import {
ExternalLink,
Play,
RefreshCw,
RotateCcw,
XCircle
} from "lucide-react";
import {
Button,
ConfirmDialog,
Dialog,
DismissibleAlert,
FormField,
IconButton,
LoadingFrame,
StatusBadge,
type ApiSettings
} from "@govoplan/core-webui";
import {
cancelWorkflowInstance,
listWorkflowInstances,
reconcileWorkflowInstance,
resolveWorkflowStep,
startWorkflowInstance,
type WorkflowDefinition,
type WorkflowInstance,
type WorkflowInstanceStep
} from "../../api/workflow";
type WorkflowAction =
| "complete"
| "approve"
| "changes"
| "reject"
| "resume"
| "retry"
| "cancel";
export default function WorkflowRunsDialog({
open,
settings,
definition,
canStart,
canTransition,
onClose
}: {
open: boolean;
settings: ApiSettings;
definition: WorkflowDefinition | null;
canStart: boolean;
canTransition: boolean;
onClose: () => void;
}) {
const [instances, setInstances] = useState<WorkflowInstance[]>([]);
const [selectedId, setSelectedId] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [working, setWorking] = useState(false);
const [error, setError] = useState("");
const [comment, setComment] = useState("");
const [evidence, setEvidence] = useState("");
const [cancelOpen, setCancelOpen] = useState(false);
const selected = useMemo(
() => instances.find((item) => item.id === selectedId) ?? instances[0] ?? null,
[instances, selectedId]
);
const currentStep = useMemo(
() => currentInstanceStep(selected),
[selected]
);
const allowedActions = useMemo(
() => handoffActions(currentStep),
[currentStep]
);
const mergeInstance = useCallback((instance: WorkflowInstance) => {
setInstances((current) => [
instance,
...current.filter((item) => item.id !== instance.id)
]);
setSelectedId(instance.id);
}, []);
const load = useCallback(async () => {
if (!open || !definition?.id) return;
setLoading(true);
setError("");
try {
const items = await listWorkflowInstances(settings, definition.id);
setInstances(items);
setSelectedId((current) => (
items.some((item) => item.id === current)
? current
: items[0]?.id ?? null
));
} catch (loadError) {
setError(errorMessage(loadError));
} finally {
setLoading(false);
}
}, [definition?.id, open, settings]);
useEffect(() => {
if (!open) return;
setComment("");
setEvidence("");
void load();
}, [load, open]);
useEffect(() => {
if (
!open
|| !canTransition
|| !selected
|| !currentStep
|| currentStep.node_type !== "workflow.dataflow"
|| !["queued", "retrying", "running"].includes(
String(currentStep.handoff.state ?? "")
)
) {
return;
}
let stopped = false;
const poll = window.setInterval(() => {
void reconcileWorkflowInstance(settings, selected.id)
.then((instance) => {
if (!stopped) mergeInstance(instance);
})
.catch((pollError) => {
if (!stopped) setError(errorMessage(pollError));
});
}, 2500);
return () => {
stopped = true;
window.clearInterval(poll);
};
}, [
canTransition,
currentStep,
mergeInstance,
open,
selected,
settings
]);
const start = async () => {
if (!definition?.id) return;
setWorking(true);
setError("");
try {
const instance = await startWorkflowInstance(settings, definition.id, {
idempotency_key: crypto.randomUUID(),
input: {}
});
mergeInstance(instance);
} catch (startError) {
setError(errorMessage(startError));
} finally {
setWorking(false);
}
};
const refreshSelected = async () => {
if (!selected) {
await load();
return;
}
setWorking(true);
setError("");
try {
const instance = canTransition
? await reconcileWorkflowInstance(settings, selected.id)
: (await listWorkflowInstances(settings, definition?.id))
.find((item) => item.id === selected.id);
if (instance) mergeInstance(instance);
else await load();
} catch (refreshError) {
setError(errorMessage(refreshError));
} finally {
setWorking(false);
}
};
const performAction = async (action: WorkflowAction) => {
if (!selected || !currentStep) return;
setWorking(true);
setError("");
try {
const instance = await resolveWorkflowStep(
settings,
selected.id,
currentStep.id,
{
action,
comment: comment.trim() || null,
evidence: evidence
.split("\n")
.map((item) => item.trim())
.filter(Boolean)
}
);
mergeInstance(instance);
setComment("");
setEvidence("");
} catch (actionError) {
setError(errorMessage(actionError));
} finally {
setWorking(false);
}
};
const cancel = async () => {
if (!selected) return;
setWorking(true);
setError("");
try {
mergeInstance(await cancelWorkflowInstance(settings, selected.id));
setCancelOpen(false);
} catch (cancelError) {
setError(errorMessage(cancelError));
} finally {
setWorking(false);
}
};
const actionUrl = typeof currentStep?.handoff.action_url === "string"
? currentStep.handoff.action_url
: "";
return (
<>
<Dialog
open={open}
title={`Runs${definition ? ` · ${definition.name}` : ""}`}
className="workflow-runs-dialog"
bodyClassName="workflow-runs-dialog-body"
onClose={onClose}
footer={<Button onClick={onClose}>Close</Button>}
>
<div className="workflow-runs-toolbar">
<span>
<strong>Workflow instances</strong>
<small>Revision-pinned runs and human handoffs</small>
</span>
<span>
<IconButton
label="Refresh runs"
icon={<RefreshCw size={16} />}
variant="ghost"
onClick={() => void refreshSelected()}
disabled={loading || working}
/>
<Button
variant="primary"
onClick={() => void start()}
disabled={!canStart || working || definition?.status !== "active"}
disabledReason={
definition?.status !== "active"
? "Activate a definition revision before starting it."
: undefined
}
>
<Play size={16} /> Start
</Button>
</span>
</div>
{error ? (
<DismissibleAlert tone="danger" resetKey={error}>
{error}
</DismissibleAlert>
) : null}
<LoadingFrame loading={loading} className="workflow-runs-frame">
<div className="workflow-runs-layout">
<div className="workflow-run-list">
{instances.map((instance) => (
<button
key={instance.id}
type="button"
className={instance.id === selected?.id ? "is-selected" : ""}
onClick={() => {
setSelectedId(instance.id);
setComment("");
setEvidence("");
}}
>
<span>
<strong>{formatDateTime(instance.started_at)}</strong>
<small>
Revision {instance.definition_revision} · {instance.steps.length} steps
</small>
</span>
<StatusBadge
status={instance.status}
label={instance.status}
/>
</button>
))}
{!instances.length ? (
<div className="workflow-run-empty">No runs yet</div>
) : null}
</div>
<div className="workflow-run-detail">
{selected ? (
<>
<header>
<span>
<strong>{selected.definition_name}</strong>
<small>
Revision {selected.definition_revision} · {selected.definition_hash.slice(0, 12)}
</small>
</span>
<span>
<StatusBadge status={selected.status} label={selected.status} />
{["running", "waiting"].includes(selected.status) ? (
<IconButton
label="Cancel workflow run"
icon={<XCircle size={16} />}
variant="danger"
onClick={() => setCancelOpen(true)}
disabled={!canTransition || working}
/>
) : null}
</span>
</header>
{selected.error ? (
<DismissibleAlert tone="danger" resetKey={selected.error}>
{selected.error}
</DismissibleAlert>
) : null}
{currentStep ? (
<section className="workflow-run-handoff">
<div>
<span>
<strong>
{String(
currentStep.handoff.title
?? currentStep.handoff.kind
?? currentStep.node_type
)}
</strong>
<small>
Step {currentStep.sequence} · attempt {currentStep.attempt}
</small>
</span>
<StatusBadge
status={String(currentStep.handoff.state ?? currentStep.status)}
label={String(currentStep.handoff.state ?? currentStep.status)}
/>
</div>
{typeof currentStep.handoff.message === "string" ? (
<p>{currentStep.handoff.message}</p>
) : null}
{typeof currentStep.handoff.instructions === "string"
&& currentStep.handoff.instructions ? (
<p>{currentStep.handoff.instructions}</p>
) : null}
{actionUrl ? (
<a href={actionUrl}>
Open linked Dataflow result <ExternalLink size={14} />
</a>
) : null}
{allowedActions.some((action) => action !== "cancel") ? (
<div className="workflow-run-action-form">
<FormField label="Comment">
<textarea
value={comment}
onChange={(event) => setComment(event.target.value)}
rows={2}
disabled={!canTransition || working}
/>
</FormField>
<FormField
label="Evidence references"
help="Enter one durable evidence reference per line."
>
<textarea
value={evidence}
onChange={(event) => setEvidence(event.target.value)}
rows={2}
disabled={!canTransition || working}
/>
</FormField>
<div className="workflow-run-actions">
{allowedActions
.filter((action) => action !== "cancel")
.map((action) => (
<Button
key={action}
variant={
action === "reject"
? "danger"
: action === "approve"
|| action === "complete"
|| action === "resume"
? "primary"
: undefined
}
onClick={() => void performAction(action)}
disabled={!canTransition || working}
>
{action === "retry" ? <RotateCcw size={15} /> : null}
{actionLabel(action)}
</Button>
))}
</div>
</div>
) : null}
</section>
) : null}
<section className="workflow-run-history">
<h3>Progress</h3>
<div>
{selected.steps.map((step) => (
<span key={step.id}>
<strong>{step.node_id}</strong>
<small>
{step.node_type} · attempt {step.attempt}
</small>
<StatusBadge status={step.status} label={step.status} />
</span>
))}
</div>
</section>
<section className="workflow-run-events">
<h3>Evidence trail</h3>
<div>
{[...selected.events].reverse().map((event) => (
<span key={event.id}>
<strong>{event.kind}</strong>
<small>
{formatDateTime(event.created_at)}
{event.actor_id ? ` · ${event.actor_id}` : ""}
</small>
</span>
))}
</div>
</section>
</>
) : (
<div className="workflow-run-empty">
Start a run to track its progress here.
</div>
)}
</div>
</div>
</LoadingFrame>
</Dialog>
<ConfirmDialog
open={cancelOpen}
title="Cancel workflow run"
message="Cancel this workflow instance and its active Dataflow run?"
confirmLabel="Cancel run"
tone="danger"
busy={working}
onCancel={() => setCancelOpen(false)}
onConfirm={() => void cancel()}
/>
</>
);
}
function currentInstanceStep(
instance: WorkflowInstance | null
): WorkflowInstanceStep | null {
if (!instance?.current_step_id) return null;
return instance.steps.find(
(step) => step.id === instance.current_step_id
) ?? null;
}
function handoffActions(step: WorkflowInstanceStep | null): WorkflowAction[] {
const actions = step?.handoff.allowed_actions;
if (!Array.isArray(actions)) return [];
return actions.filter((action): action is WorkflowAction => (
typeof action === "string"
&& [
"complete",
"approve",
"changes",
"reject",
"resume",
"retry",
"cancel"
].includes(action)
));
}
function actionLabel(action: WorkflowAction): string {
return {
complete: "Complete",
approve: "Approve",
changes: "Request changes",
reject: "Reject",
resume: "Resume",
retry: "Retry",
cancel: "Cancel"
}[action];
}
function formatDateTime(value: string): string {
return new Intl.DateTimeFormat(undefined, {
dateStyle: "medium",
timeStyle: "short"
}).format(new Date(value));
}
function errorMessage(error: unknown): string {
if (error instanceof Error) return error.message;
return "The Workflow request failed.";
}