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
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
"use client";

import {
  CheckIcon,
  FlaskConicalIcon,
  PlayIcon,
  RocketIcon,
  RotateCcwIcon,
  SaveIcon,
  ShieldCheckIcon,
  Undo2Icon,
} from "lucide-react";
import dynamic from "next/dynamic";
import Link from "next/link";
import { useState } from "react";
import { toast } from "sonner";

import { RunStatusBadge } from "@/components/runs/status-badge";
import { ErrorState, PageHeader } from "@/components/shell/page";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { api, ApiError } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { formatDateTime } from "@/lib/format";
import { useI18n } from "@/lib/i18n";
import { useApi } from "@/lib/use-api";
import { cn } from "@/lib/utils";

import {
  describe,
  formatDefinition,
  issuesFromBody,
  parseDefinition,
  sameDefinition,
  versionActions,
  type IssueReport,
} from "./dsl";
import { DryRunView, IssueList, WfBadge } from "./parts";
import type {
  CatalogTool,
  ValidateResult,
  Version,
  WorkflowDefinition,
  WorkflowDetail as Detail,
  WorkflowRun,
} from "./types";
import { ProposalList } from "./workflows-view";

const WorkflowCanvas = dynamic(() => import("./workflow-canvas"), {
  loading: () => <Skeleton className="h-[32rem] w-full" />,
});

function errorText(e: unknown, fallback: string): string {
  if (e instanceof ApiError) return issuesFromBody(e.body)?.message || e.detail || fallback;
  return e instanceof Error ? e.message : fallback;
}

/** JSON view: local text, applied to the shared definition whenever it parses. */
function JsonEditor({

  defn,

  onChange,

}: {

  defn: WorkflowDefinition;

  onChange: (d: WorkflowDefinition) => void;

}) {
  const { t } = useI18n();
  const [text, setText] = useState(() => formatDefinition(defn));
  const [err, setErr] = useState<string | null>(null);
  return (
    <div className="space-y-2">

      <Textarea

        aria-label={t("workflows.tabs.json")}

        data-testid="json-editor"

        dir="ltr"

        spellCheck={false}

        className="min-h-[28rem] font-mono text-xs leading-relaxed"

        value={text}

        onChange={(e) => {

          setText(e.target.value);

          const r = parseDefinition(e.target.value);

          if (r.ok) {

            setErr(null);

            onChange(r.value);

          } else {

            setErr(r.error);

          }

        }}

      />

      {err && (

        <p className="text-sm text-destructive" role="alert" data-testid="json-error">

          {t("workflows.jsonError")}: {err}

        </p>

      )}

    </div>
  );
}

function PlainView({ defn, nl }: { defn: WorkflowDefinition; nl: string | null }) {
  const { t } = useI18n();
  const lines = describe(defn);
  return (
    <div className="space-y-3">

      {nl && (

        <div className="rounded-lg border bg-card px-3 py-2">

          <p className="text-xs text-muted-foreground">{t("workflows.nlSource")}</p>

          <p className="text-sm italic">“{nl}”</p>

        </div>

      )}

      <ol className="space-y-1 rounded-lg border bg-card px-3 py-2 font-mono text-sm" dir="ltr" data-testid="plain-plan">

        {lines.map((l, i) => (

          <li key={i} className={i === 0 ? "font-semibold" : "ps-3"}>

            {l}

          </li>

        ))}

      </ol>

    </div>
  );
}

/** Editor + lifecycle for one saved version. Remounted when the version (or its content) changes. */
function VersionWorkspace({

  wf,

  v,

  tools,

  onSaved,

  onChanged,

}: {

  wf: Detail;

  v: Version;

  tools: CatalogTool[];

  onSaved: (n: number) => void;

  onChanged: () => void;

}) {
  const { t, locale } = useI18n();
  const { me } = useAuth();
  const isOwner = me?.role === "owner";
  const [defn, setDefn] = useState<WorkflowDefinition>(v.definition);
  const [jsonKey, setJsonKey] = useState(0);
  const [panelKey, setPanelKey] = useState(0);
  const [tab, setTab] = useState("plain");
  const [busy, setBusy] = useState<string | null>(null);
  const [report, setReport] = useState<IssueReport | null>(null);
  const [validation, setValidation] = useState<ValidateResult | null>(null);
  const dirty = !sameDefinition(defn, v.definition);
  const can = versionActions(v, wf.active_version);

  const edit = (d: WorkflowDefinition, from: "json" | "canvas" | "reset") => {
    setDefn(d);
    setValidation(null);
    if (from !== "json") setJsonKey((k) => k + 1);
    if (from !== "canvas") setPanelKey((k) => k + 1);
  };

  const run = async (name: string, fn: () => Promise<void>) => {
    setBusy(name);
    try {
      await fn();
    } catch (e) {
      toast.error(errorText(e, t("common.error")));
    } finally {
      setBusy(null);
    }
  };

  const base = `/workflows/${wf.id}/versions/${v.version}`;

  const save = () =>
    run("save", async () => {
      setReport(null);
      try {
        const nv = await api<Version>(`/workflows/${wf.id}/versions`, {
          method: "POST",
          body: { definition: defn },
        });
        toast.success(t("workflows.saved", { n: nv.version }));
        onSaved(nv.version);
      } catch (e) {
        const r = e instanceof ApiError ? issuesFromBody(e.body) : null;
        if (!r) throw e;
        setReport(r);
      }
    });

  const validate = () =>
    run("validate", async () => {
      setReport(null);
      const r = await api<ValidateResult>("/workflows/validate", {
        method: "POST",
        body: { definition: defn },
      });
      setValidation(r);
    });

  const lifecycle = (name: string, path: string, msg: string) =>
    run(name, async () => {
      await api<Version>(`${base}/${path}`, { method: "POST", body: path === "dry-run" ? {} : undefined });
      toast.success(msg);
      onChanged();
    });

  return (
    <div className="space-y-5">

      <section className="space-y-3 rounded-lg border bg-card p-4" data-testid="version-panel" data-version={v.version}>

        <div className="flex flex-wrap items-center gap-2">

          <h2 className="font-semibold">

            {t("workflows.version")} {v.version}

          </h2>

          <WfBadge status={v.status} className="" />

          {v.note && <span className="text-xs text-muted-foreground">{v.note}</span>}

          <span className="ms-auto text-xs text-muted-foreground">

            {formatDateTime(v.created_at, locale)}

            {v.parent_version ? ` · ${t("workflows.from", { n: v.parent_version })}` : ""}

          </span>

        </div>

        <div className="flex flex-wrap gap-2">

          <Button

            size="sm"

            variant="outline"

            disabled={busy !== null}

            onClick={() => void lifecycle("dry", "dry-run", t("workflows.dryRunDone"))}

            data-testid="dry-run-btn"

          >

            <FlaskConicalIcon aria-hidden /> {t("workflows.dryRun")}

          </Button>

          <Button

            size="sm"

            variant="outline"

            disabled={busy !== null || !can.approve || !isOwner}

            title={!isOwner ? t("workflows.ownerOnly") : undefined}

            onClick={() => void lifecycle("approve", "approve", t("workflows.approvedToast"))}

            data-testid="approve-btn"

          >

            <ShieldCheckIcon aria-hidden /> {t("workflows.approve")}

          </Button>

          <Button

            size="sm"

            disabled={busy !== null || !can.activate || !isOwner}

            title={!isOwner ? t("workflows.ownerOnly") : undefined}

            onClick={() => void lifecycle("activate", "activate", t("workflows.activatedToast"))}

            data-testid="activate-btn"

          >

            <RocketIcon aria-hidden /> {t("workflows.activate")}

          </Button>

        </div>

        <IssueList errors={v.checks?.errors ?? []} warnings={v.checks?.warnings ?? []} testId="version-checks" />

        {v.dry_run && (

          <div className="space-y-2 border-t pt-3">

            <p className="text-sm font-medium">

              {t("workflows.dryRunTitle")}

              {v.dry_run_at && (

                <span className="ms-2 text-xs font-normal text-muted-foreground">

                  {formatDateTime(v.dry_run_at, locale)}

                </span>

              )}

            </p>

            <DryRunView dryRun={v.dry_run} current={v.dry_run_current} />

          </div>

        )}

      </section>



      <section className="space-y-3">

        <div className="flex flex-wrap items-center gap-2">

          <h2 className="font-semibold">{t("workflows.definition")}</h2>

          {dirty && (

            <span className="text-xs text-warning" data-testid="unsaved">

              {t("workflows.unsaved")}

            </span>

          )}

          <div className="ms-auto flex flex-wrap gap-2">

            {dirty && (

              <Button size="sm" variant="ghost" onClick={() => edit(v.definition, "reset")}>

                <Undo2Icon aria-hidden /> {t("workflows.discard")}

              </Button>

            )}

            <Button size="sm" variant="outline" disabled={busy !== null} onClick={() => void validate()} data-testid="validate-btn">

              <CheckIcon aria-hidden /> {t("workflows.validate")}

            </Button>

            {dirty && (

              <Button size="sm" disabled={busy !== null} onClick={() => void save()} data-testid="save-version">

                <SaveIcon aria-hidden /> {t("workflows.saveVersion")}

              </Button>

            )}

          </div>

        </div>

        {report && (

          <div className="space-y-1" data-testid="save-errors">

            <p className="text-sm text-destructive">{report.message || t("workflows.saveFailed")}</p>

            <IssueList errors={report.errors} warnings={report.warnings} />

          </div>

        )}

        {validation && (

          <div className="space-y-1" data-testid="validation">

            <p className={cn("text-sm font-medium", validation.ok ? "text-success" : "text-destructive")}>

              {validation.ok ? t("workflows.valid") : t("workflows.invalid")}

            </p>

            <IssueList errors={validation.errors} warnings={validation.warnings} />

          </div>

        )}

        <Tabs value={tab} onValueChange={setTab}>

          <TabsList>

            <TabsTrigger value="plain">{t("workflows.tabs.plain")}</TabsTrigger>

            <TabsTrigger value="canvas">{t("workflows.tabs.canvas")}</TabsTrigger>

            <TabsTrigger value="json">{t("workflows.tabs.json")}</TabsTrigger>

          </TabsList>

          <TabsContent value="plain" className="pt-2">

            <PlainView defn={defn} nl={v.nl_source} />

          </TabsContent>

          <TabsContent value="canvas" className="pt-2">

            {tab === "canvas" && (

              <WorkflowCanvas

                defn={defn}

                tools={tools}

                panelKey={panelKey}

                onChange={(d) => edit(d, "canvas")}

              />

            )}

          </TabsContent>

          <TabsContent value="json" className="pt-2">

            <JsonEditor key={jsonKey} defn={defn} onChange={(d) => edit(d, "json")} />

          </TabsContent>

        </Tabs>

      </section>

    </div>
  );
}

function RecentRuns({ id }: { id: string }) {
  const { t, locale } = useI18n();
  const runs = useApi<WorkflowRun[]>(`/workflows/${id}/runs`, { pollMs: 10_000 });
  if (!runs.data) return null;
  if (!runs.data.length) return <p className="text-sm text-muted-foreground">{t("workflows.noRuns")}</p>;
  return (
    <ul className="divide-y rounded-lg border bg-card" data-testid="workflow-runs">

      {runs.data.map((r) => (

        <li key={r.run_id} className="flex flex-wrap items-center gap-3 px-3 py-2 text-sm">

          <RunStatusBadge status={r.status} />

          <Link href={`/runs/${r.run_id}`} className="font-mono text-xs hover:underline">

            {r.run_id.slice(0, 8)}

          </Link>

          <span className="text-xs text-muted-foreground">

            {r.version ? `v${r.version}` : ""} {r.trigger ?? ""}

          </span>

          <span className="truncate text-xs text-muted-foreground">{r.error ?? r.output ?? ""}</span>

          <span className="tabular ms-auto text-xs text-muted-foreground">{formatDateTime(r.started_at, locale)}</span>

        </li>

      ))}

    </ul>
  );
}

export function WorkflowDetailView({ id }: { id: string }) {
  const { t } = useI18n();
  const { me } = useAuth();
  const wf = useApi<Detail>(`/workflows/${id}`);
  const tools = useApi<CatalogTool[]>("/workflows/tools");
  const [selected, setSelected] = useState<number | null>(null);
  const [busy, setBusy] = useState(false);

  if (wf.error && !wf.data) return <ErrorState error={wf.error} onRetry={wf.reload} />;
  if (!wf.data) return <Skeleton className="h-96 w-full" />;
  const d = wf.data;
  const v = d.versions.find((x) => x.version === selected) ?? d.versions[0];

  const action = async (path: "rollback" | "run" | "deactivate") => {
    setBusy(true);
    try {
      const out = await api<{ active_version?: number | null; version?: number }>(
        `/workflows/${d.id}/${path}`,
        { method: "POST", body: path === "run" ? { input: {} } : undefined },
      );
      if (path === "run") toast.success(t("workflows.runQueued", { n: out.version ?? "" }));
      else if (path === "rollback")
        toast.success(
          out.active_version
            ? t("workflows.rolledBackTo", { n: out.active_version })
            : t("workflows.paused"),
        );
      else toast.success(t("workflows.paused"));
      wf.reload();
    } catch (e) {
      toast.error(errorText(e, t("common.error")));
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="space-y-6">

      <PageHeader

        title={d.name}

        subtitle={d.description}

        actions={

          <>

            <Button

              size="sm"

              variant="outline"

              disabled={busy || d.active_version === null}

              onClick={() => void action("rollback")}

              data-testid="rollback-btn"

            >

              <RotateCcwIcon aria-hidden /> {t("workflows.rollback")}

            </Button>

            <Button

              size="sm"

              disabled={busy || d.active_version === null || me?.role === "viewer"}

              onClick={() => void action("run")}

              data-testid="run-now-btn"

            >

              <PlayIcon aria-hidden /> {t("workflows.runNow")}

            </Button>

          </>

        }

      />
      <div className="flex flex-wrap items-center gap-3 text-sm">

        <WfBadge status={d.status} />

        <span data-testid="active-version">

          {t("workflows.activeVersion")}: <b className="tabular">{d.active_version ? `v${d.active_version}` : "—"}</b>

        </span>

        <span className="font-mono text-xs text-muted-foreground" dir="ltr">

          {d.key}

        </span>

      </div>

      <div className="flex flex-wrap gap-2" role="tablist" aria-label={t("workflows.versions")} data-testid="versions">

        {d.versions.map((x) => (

          <button

            key={x.version}

            type="button"

            role="tab"

            aria-selected={x.version === v?.version}

            onClick={() => setSelected(x.version)}

            data-testid={`version-${x.version}`}

            data-status={x.status}

            className={cn(

              "flex items-center gap-2 rounded-md border px-2.5 py-1 text-sm transition-colors",

              x.version === v?.version ? "border-primary bg-primary/5" : "hover:bg-muted",

            )}

          >

            <span className="tabular font-medium">v{x.version}</span>

            <WfBadge status={x.status} />

          </button>

        ))}

      </div>

      {v && (
        <VersionWorkspace

          key={`${v.version}:${v.definition_hash}`}

          wf={d}

          v={v}

          tools={tools.data ?? []}

          onSaved={(n) => {

            setSelected(n);

            wf.reload();

          }}

          onChanged={wf.reload}

        />
      )}

      {d.proposals.length > 0 && (
        <section className="space-y-2">

          <h2 className="font-semibold">{t("workflows.proposals")}</h2>

          <ProposalList proposals={d.proposals} onChanged={wf.reload} />

        </section>
      )}

      <section className="space-y-2">
        <h2 className="font-semibold">{t("workflows.recentRuns")}</h2>
        <RecentRuns id={d.id} />
      </section>
    </div>
  );
}