622 lines
20 KiB
TypeScript
622 lines
20 KiB
TypeScript
import {
|
|
useCallback,
|
|
useEffect,
|
|
useMemo,
|
|
useState
|
|
} from "react";
|
|
import {
|
|
AlertTriangle,
|
|
Check,
|
|
Circle,
|
|
Clock3,
|
|
ExternalLink,
|
|
Play,
|
|
RefreshCw,
|
|
RotateCcw,
|
|
XCircle
|
|
} from "lucide-react";
|
|
import { ActionToolbar,
|
|
Button,
|
|
ConfirmDialog,
|
|
Dialog,
|
|
DismissibleAlert,
|
|
ContentGrid,
|
|
FormField,
|
|
IconButton,
|
|
LoadingFrame,
|
|
StageRail,
|
|
StatusBadge,
|
|
dispatchWorkflowViewChanged,
|
|
usePlatformUiCapability,
|
|
type StageRailTone,
|
|
type ApiSettings,
|
|
type ViewsRuntimeUiCapability
|
|
} 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"
|
|
| "confirm_effect"
|
|
| "confirm_absent"
|
|
| "cancel";
|
|
|
|
export default function WorkflowRunsDialog({
|
|
open,
|
|
settings,
|
|
definition,
|
|
initialInstanceId,
|
|
canStart,
|
|
canTransition,
|
|
onClose
|
|
}: {
|
|
open: boolean;
|
|
settings: ApiSettings;
|
|
definition: WorkflowDefinition | null;
|
|
initialInstanceId?: string | 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 viewsRuntime = usePlatformUiCapability<ViewsRuntimeUiCapability>(
|
|
"views.runtime"
|
|
);
|
|
|
|
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) => (
|
|
initialInstanceId
|
|
&& items.some((item) => item.id === initialInstanceId)
|
|
? initialInstanceId
|
|
: items.some((item) => item.id === current)
|
|
? current
|
|
: items[0]?.id ?? null
|
|
));
|
|
} catch (loadError) {
|
|
setError(errorMessage(loadError));
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [definition?.id, initialInstanceId, open, settings]);
|
|
|
|
useEffect(() => {
|
|
if (!open) return;
|
|
setComment("");
|
|
setEvidence("");
|
|
void load();
|
|
}, [load, open]);
|
|
|
|
useEffect(() => {
|
|
if (!open || !selected) return;
|
|
const context = selected.view_context;
|
|
if (!context || !viewsRuntime) {
|
|
dispatchWorkflowViewChanged(null);
|
|
return;
|
|
}
|
|
let cancelled = false;
|
|
void viewsRuntime.resolveWorkflowView(settings, {
|
|
viewId: context.view_id,
|
|
revisionId: context.revision_id,
|
|
visibleSurfaceIds: context.visible_surface_ids
|
|
}).then((projection) => {
|
|
if (!cancelled) {
|
|
dispatchWorkflowViewChanged(projection, selected.id);
|
|
}
|
|
}).catch((viewError) => {
|
|
if (!cancelled) {
|
|
dispatchWorkflowViewChanged(null);
|
|
setError(errorMessage(viewError));
|
|
}
|
|
});
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [
|
|
open,
|
|
selected?.id,
|
|
selected?.updated_at,
|
|
settings,
|
|
viewsRuntime
|
|
]);
|
|
|
|
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
|
|
: "";
|
|
const unavailableOptionalCapabilities = Array.isArray(
|
|
currentStep?.handoff.unavailable_optional_capabilities
|
|
)
|
|
? currentStep.handoff.unavailable_optional_capabilities.filter(
|
|
(value): value is string => typeof value === "string" && Boolean(value)
|
|
)
|
|
: [];
|
|
const close = () => {
|
|
dispatchWorkflowViewChanged(null);
|
|
onClose();
|
|
};
|
|
|
|
return (
|
|
<>
|
|
<Dialog
|
|
open={open}
|
|
title={`Runs${definition ? ` · ${definition.name}` : ""}`}
|
|
className="workflow-runs-dialog"
|
|
bodyClassName="workflow-runs-dialog-body"
|
|
onClose={close}
|
|
footer={<Button onClick={close}>Close</Button>}
|
|
>
|
|
<ActionToolbar 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>
|
|
</ActionToolbar>
|
|
{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}
|
|
{selected.view_context && !viewsRuntime ? (
|
|
<DismissibleAlert
|
|
tone="warning"
|
|
resetKey={`view-unavailable:${selected.id}:${selected.current_step_id ?? "none"}`}
|
|
>
|
|
The focused View is unavailable. Workflow position is preserved;
|
|
use the linked module action or ask an administrator to enable Views.
|
|
</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}
|
|
{unavailableOptionalCapabilities.length ? (
|
|
<DismissibleAlert
|
|
tone="info"
|
|
resetKey={`optional:${currentStep.id}:${unavailableOptionalCapabilities.join(",")}`}
|
|
>
|
|
Optional integration unavailable: {unavailableOptionalCapabilities.join(", ")}.
|
|
The hand-off remains valid and resumable.
|
|
</DismissibleAlert>
|
|
) : null}
|
|
{actionUrl ? (
|
|
<a href={actionUrl}>
|
|
Open linked work <ExternalLink size={14} />
|
|
</a>
|
|
) : null}
|
|
{allowedActions.some((action) => action !== "cancel") ? (
|
|
<ContentGrid columns={2} gap="compact" collapseAt="narrow" 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"
|
|
|| action === "confirm_effect"
|
|
? "primary"
|
|
: undefined
|
|
}
|
|
onClick={() => void performAction(action)}
|
|
disabled={!canTransition || working}
|
|
>
|
|
{action === "retry" ? <RotateCcw size={15} /> : null}
|
|
{actionLabel(action)}
|
|
</Button>
|
|
))}
|
|
</div>
|
|
</ContentGrid>
|
|
) : null}
|
|
</section>
|
|
) : null}
|
|
<section className="workflow-run-history">
|
|
<h3>Progress</h3>
|
|
<StageRail
|
|
ariaLabel="Workflow instance progress"
|
|
items={selected.steps.map((step) => ({
|
|
id: step.id,
|
|
label: step.node_id,
|
|
detail: `${step.node_type} · attempt ${step.attempt}`,
|
|
statusLabel: step.status,
|
|
current: step.id === selected.current_step_id,
|
|
tone: stepTone(step.status),
|
|
icon: step.status === "completed" ? (
|
|
<Check size={15} aria-hidden="true" />
|
|
) : step.status === "failed" ? (
|
|
<AlertTriangle size={15} aria-hidden="true" />
|
|
) : ["running", "waiting"].includes(step.status) ? (
|
|
<Clock3 size={15} aria-hidden="true" />
|
|
) : (
|
|
<Circle size={13} aria-hidden="true" />
|
|
)
|
|
}))}
|
|
/>
|
|
</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",
|
|
"confirm_effect",
|
|
"confirm_absent",
|
|
"cancel"
|
|
].includes(action)
|
|
));
|
|
}
|
|
|
|
function actionLabel(action: WorkflowAction): string {
|
|
return {
|
|
complete: "Complete",
|
|
approve: "Approve",
|
|
changes: "Request changes",
|
|
reject: "Reject",
|
|
resume: "Resume",
|
|
retry: "Retry",
|
|
confirm_effect: "Effect confirmed",
|
|
confirm_absent: "Effect absent",
|
|
cancel: "Cancel"
|
|
}[action];
|
|
}
|
|
|
|
function stepTone(
|
|
status: WorkflowInstanceStep["status"]
|
|
): StageRailTone {
|
|
if (status === "completed") return "success";
|
|
if (status === "running" || status === "waiting") return "active";
|
|
if (status === "failed" || status === "cancelled") return "danger";
|
|
return "neutral";
|
|
}
|
|
|
|
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.";
|
|
}
|