Spaces:
Running
Running
File size: 12,372 Bytes
03608f2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 | "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>
);
}
|