Spaces:
Running

WorkPilot-AI / web /src /components /workflows /workflows-view.tsx
Aynkhn's picture
Deploy WorkPilot demo (part 3)
03608f2 verified
Raw History Blame Contribute Delete
12.4 kB
"use client";
import { LayoutTemplateIcon, SparklesIcon, WorkflowIcon, WrenchIcon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState, type FormEvent } from "react";
import { toast } from "sonner";
import { EmptyState, ErrorState, PageHeader } from "@/components/shell/page";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import { api, ApiError } from "@/lib/api";
import { formatDateTime } from "@/lib/format";
import { useI18n } from "@/lib/i18n";
import { useApi } from "@/lib/use-api";
import { issuesFromBody, type IssueReport } from "./dsl";
import { IssueList, WfBadge } from "./parts";
import type { Proposal, Template, WorkflowDetail, WorkflowList } from "./types";
/** POST /workflows; returns the created workflow or throws with the 422 issue report. */
export async function createWorkflow(
body: { text: string } | { template: string },
): Promise<{ ok: true; wf: WorkflowDetail } | { ok: false; report: IssueReport | null; error: Error }> {
try {
const wf = await api<WorkflowDetail>("/workflows", { method: "POST", body });
return { ok: true, wf };
} catch (e) {
const err = e instanceof Error ? e : new Error(String(e));
return { ok: false, report: e instanceof ApiError ? issuesFromBody(e.body) : null, error: err };
}
}
function NewWorkflowForm() {
const { t } = useI18n();
const router = useRouter();
const [text, setText] = useState("");
const [busy, setBusy] = useState(false);
const [report, setReport] = useState<IssueReport | null>(null);
const submit = async (e: FormEvent) => {
e.preventDefault();
if (!text.trim()) return;
setBusy(true);
setReport(null);
const res = await createWorkflow({ text: text.trim() });
setBusy(false);
if (res.ok) {
toast.success(t("workflows.created"));
router.push(`/workflows/${res.wf.id}`);
} else {
setReport(res.report);
if (!res.report) toast.error(res.error.message || t("common.error"));
}
};
return (
<form onSubmit={submit} className="space-y-3 rounded-lg border bg-card p-4" data-testid="new-workflow">
<div className="space-y-1">
<Label htmlFor="wf-nl" className="flex items-center gap-1.5">
<SparklesIcon className="size-4 text-primary" aria-hidden />
{t("workflows.newTitle")}
</Label>
<p className="text-xs text-muted-foreground">{t("workflows.newHint")}</p>
</div>
<Textarea
id="wf-nl"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder={t("workflows.newPlaceholder")}
className="min-h-24"
/>
{report && (
<div className="space-y-2" data-testid="create-errors">
{report.message && <p className="text-sm text-destructive">{report.message}</p>}
<IssueList errors={report.errors} warnings={report.warnings} />
</div>
)}
<div className="flex justify-end">
<Button type="submit" disabled={busy || !text.trim()}>
{busy ? t("workflows.compiling") : t("workflows.create")}
</Button>
</div>
</form>
);
}
function Templates() {
const { t, m } = useI18n();
const router = useRouter();
const tpls = useApi<Template[]>("/workflows/templates");
const [busy, setBusy] = useState<string | null>(null);
const use = async (id: string) => {
setBusy(id);
const res = await createWorkflow({ template: id });
setBusy(null);
if (res.ok) {
toast.success(t("workflows.created"));
router.push(`/workflows/${res.wf.id}`);
} else {
toast.error(res.report?.message || res.error.message || t("common.error"));
}
};
if (tpls.error && !tpls.data) return <ErrorState error={tpls.error} onRetry={tpls.reload} />;
if (!tpls.data) return <Skeleton className="h-40 w-full" />;
if (!tpls.data.length) return <p className="text-sm text-muted-foreground">{t("workflows.noTemplates")}</p>;
return (
<div className="grid gap-3 md:grid-cols-2" data-testid="template-gallery">
{tpls.data.map((tp) => (
<div
key={tp.id}
className="flex flex-col gap-2 rounded-lg border bg-card p-4"
data-testid="template-card"
data-template={tp.id}
>
<div className="flex items-start gap-2">
<LayoutTemplateIcon className="mt-0.5 size-4 text-muted-foreground" aria-hidden />
<div className="min-w-0 flex-1">
<p className="font-medium">{tp.name}</p>
<p className="text-xs text-muted-foreground">{tp.description}</p>
</div>
<Badge variant="outline">{m.workflows.triggers[tp.trigger]}</Badge>
</div>
<p className="rounded-md bg-muted/50 px-2 py-1.5 text-sm italic">“{tp.nl}”</p>
<div className="mt-auto flex flex-wrap items-center gap-1.5">
<span className="text-[11px] text-muted-foreground">{tp.pack}</span>
{tp.tags.map((tag) => (
<Badge key={tag} variant="secondary">
{tag}
</Badge>
))}
<Button
size="sm"
className="ms-auto"
disabled={busy !== null || !tp.ok}
onClick={() => void use(tp.id)}
>
{t("workflows.useTemplate")}
</Button>
</div>
</div>
))}
</div>
);
}
export function ProposalList({
proposals,
onChanged,
showWorkflow = false,
}: {
proposals: Proposal[];
onChanged: () => void;
showWorkflow?: boolean;
}) {
const { t, m, locale } = useI18n();
const [busy, setBusy] = useState<string | null>(null);
const act = async (p: Proposal, action: "apply" | "dismiss") => {
setBusy(p.id);
try {
const out = await api<{ version?: number }>(`/workflows/proposals/${p.id}/${action}`, {
method: "POST",
});
toast.success(
action === "apply"
? t("workflows.proposalApplied", { n: out.version ?? "" })
: t("workflows.proposalDismissed"),
);
onChanged();
} catch (e) {
const r = e instanceof ApiError ? issuesFromBody(e.body) : null;
toast.error(r?.message || (e instanceof Error ? e.message : t("common.error")));
} finally {
setBusy(null);
}
};
return (
<ul className="space-y-2" data-testid="proposals">
{proposals.map((p) => (
<li key={p.id} className="space-y-1.5 rounded-lg border bg-card px-3 py-2" data-testid="proposal">
<div className="flex flex-wrap items-center gap-2">
<WrenchIcon className="size-4 text-warning" aria-hidden />
<span className="text-sm font-medium">{p.summary}</span>
<Badge variant="outline">{m.workflows.failureClasses[p.failure_class] ?? p.failure_class}</Badge>
<WfBadge status={p.status} />
<span className="ms-auto text-xs text-muted-foreground">{formatDateTime(p.created_at, locale)}</span>
</div>
<p className="font-mono text-xs text-muted-foreground" dir="ltr">
{showWorkflow && (
<Link href={`/workflows/${p.workflow_id}`} className="me-2 underline">
{t("workflows.open")}
</Link>
)}
v{p.version} · [{p.step_id}] {p.error}
</p>
{p.patch.length > 0 && (
<pre className="overflow-x-auto rounded bg-muted/50 p-2 font-mono text-[11px]" dir="ltr">
{p.patch.map((op) => `${op.op} ${op.path} ${op.value !== undefined ? JSON.stringify(op.value) : ""}`).join("\n")}
</pre>
)}
{p.status === "pending" && (
<div className="flex gap-2">
<Button size="sm" disabled={busy !== null || !p.patch.length} onClick={() => void act(p, "apply")}>
{t("workflows.apply")}
</Button>
<Button size="sm" variant="outline" disabled={busy !== null} onClick={() => void act(p, "dismiss")}>
{t("workflows.dismiss")}
</Button>
</div>
)}
</li>
))}
</ul>
);
}
export function WorkflowsView() {
const { t, locale } = useI18n();
const list = useApi<WorkflowList>("/workflows", { pollMs: 15_000 });
const pending = useApi<Proposal[]>(
list.data && list.data.pending_proposals > 0 ? "/workflows/proposals" : null,
{ query: { status: "pending" } },
);
const reload = () => {
list.reload();
pending.reload();
};
return (
<div className="space-y-6">
<PageHeader title={t("workflows.title")} subtitle={t("workflows.subtitle")} />
{list.data && list.data.pending_proposals > 0 && (
<div className="space-y-2 rounded-lg border border-warning/40 bg-warning-soft/40 p-3" data-testid="proposals-banner">
<p className="text-sm font-medium">
{t("workflows.pendingProposals", { n: list.data.pending_proposals })}
</p>
{pending.data && <ProposalList proposals={pending.data} onChanged={reload} showWorkflow />}
</div>
)}
{list.error && !list.data ? (
<ErrorState error={list.error} onRetry={list.reload} />
) : !list.data ? (
<Skeleton className="h-40 w-full" />
) : !list.data.items.length ? (
<EmptyState icon={WorkflowIcon} title={t("workflows.empty")} hint={t("workflows.emptyHint")} />
) : (
<div className="overflow-hidden rounded-lg border bg-card">
<Table data-testid="workflows-table">
<TableHeader>
<TableRow>
<TableHead>{t("workflows.name")}</TableHead>
<TableHead>{t("workflows.status")}</TableHead>
<TableHead>{t("workflows.activeVersion")}</TableHead>
<TableHead>{t("workflows.latestVersion")}</TableHead>
<TableHead className="hidden md:table-cell">{t("workflows.updated")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{list.data.items.map((w) => (
<TableRow key={w.id} className="relative" data-testid="workflow-row">
<TableCell className="max-w-80">
<Link
href={`/workflows/${w.id}`}
className="font-medium after:absolute after:inset-0 hover:underline"
>
{w.name}
</Link>
<p className="truncate text-xs text-muted-foreground">{w.description}</p>
</TableCell>
<TableCell>
<WfBadge status={w.status} />
</TableCell>
<TableCell className="tabular">{w.active_version ? `v${w.active_version}` : "—"}</TableCell>
<TableCell>
{w.latest_version ? (
<span className="flex items-center gap-2">
<span className="tabular">v{w.latest_version.version}</span>
<WfBadge status={w.latest_version.status} />
</span>
) : (
"—"
)}
</TableCell>
<TableCell className="tabular hidden text-muted-foreground md:table-cell">
{formatDateTime(w.updated_at, locale)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
<NewWorkflowForm />
<section className="space-y-3">
<h2 className="text-base font-semibold">{t("workflows.templates")}</h2>
<Templates />
</section>
</div>
);
}