diff --git a/changelog.d/added-workflowmodel-editor.md b/changelog.d/added-workflowmodel-editor.md new file mode 100644 index 0000000000..73ecde8b2c --- /dev/null +++ b/changelog.d/added-workflowmodel-editor.md @@ -0,0 +1 @@ +- Workflow models, RFC phase 4 UI: Settings → Workflows grows an **Editor** — a visual design surface for lifecycle models rather than a form. Columns are vertical lanes (add, rename by double-click, reorder and resize by dragging the header, toggle terminal); states are chips you drag within and between lanes or drop from a templates palette (common states and columns, hive-default stages); transitions are drawn by dragging a chip's port onto another chip, with backward edges dashed and self-loops drawn as loops. The canvas pans, zooms, fits, shows a minimap, supports marquee and shift-click multi-select, keyboard nudging and Delete, undo/redo, and an Auto-layout that orders lanes by topological depth. An inspector edits the selected state, transition, column or the model itself; a bottom drawer hosts Problems (live compile diagnostics, badged on the canvas and clickable), YAML (two-way via the new `POST /api/workflows/yaml`), Diff (client-side structural diff against the last save, or the stored versions diff) and Simulate (facts → `POST /api/workflows/simulate` against the unsaved model, highlighting the decided state). Save assigns the next version through `POST /api/workflows` with an empty `meta.version`; Save as… and Revert are one click; inferred states carry a ✓ Confirm affordance with a toolbar "Confirm all inferred". Export offers self-contained SVG, PNG, model JSON and YAML. Library rows and detail gain Edit (owner) / Edit a copy (hive-default), and ingest results gain "Open in editor" ([#17620](https://github.com/hivecommons/hive/issues/17620)) diff --git a/changelog.d/added-workflowmodel-versions-diff-confirm.md b/changelog.d/added-workflowmodel-versions-diff-confirm.md new file mode 100644 index 0000000000..c1b23e4869 --- /dev/null +++ b/changelog.d/added-workflowmodel-versions-diff-confirm.md @@ -0,0 +1 @@ +- Workflow models (RFC phase 4, backend): `GET /api/workflows/{name}/versions`, a deterministic structural diff between two versions (`GET …/{name}/diff?from&to`, optionally cross-model against hive-default), `POST …/{name}/{version}/confirm` to confirm an ingested model's inferred elements as a new local version (owner, audited `workflow_confirm`), `GET …/{name}/{version}/labels` to preview the labels and commands a model regenerates, and the stage-label provisioner now creates or recolours a bound model's own label vocabulary and re-provisions when the binding changes ([#17620](https://github.com/hivecommons/hive/issues/17620)) diff --git a/dashboard/openapi.json b/dashboard/openapi.json index ec82036abe..d9d38ba87a 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -35459,6 +35459,116 @@ } } }, + "/api/workflows/yaml": { + "post": { + "tags": [ + "Workflows" + ], + "summary": "Convert a workflow model between JSON and YAML", + "description": "Editor helper. Send `model` to get its YAML (field names are the JSON tags), or `yaml` to get the parsed model back. A YAML parse or schema error answers 200 with `error` set so the editor can show it inline. Read-only; no store or owner role needed.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "model": { + "$ref": "#/components/schemas/WorkflowModel" + }, + "yaml": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "yaml, or model (or error) depending on the input", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "yaml": { + "type": "string" + }, + "model": { + "$ref": "#/components/schemas/WorkflowModel" + }, + "error": { + "type": "string" + } + } + } + } + } + }, + "400": { + "description": "Neither model nor yaml supplied, or malformed body" + } + } + } + }, + "/api/workflows/simulate": { + "post": { + "tags": [ + "Workflows" + ], + "summary": "Simulate an issue or PR against an unsaved workflow model", + "description": "Editor variant of /api/workflows/{name}/{version}/simulate: the model travels in the body and `facts` are required (no forge fetch). Same decision and trace shape. Read-only; no store or owner role needed.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "model", + "kind", + "facts" + ], + "properties": { + "model": { + "$ref": "#/components/schemas/WorkflowModel" + }, + "kind": { + "type": "string", + "enum": [ + "issue", + "pr" + ] + }, + "facts": { + "$ref": "#/components/schemas/WorkflowSimulateFacts" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Decision, trace and normalized facts", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WorkflowSimulateResult" + } + } + } + }, + "400": { + "description": "Missing model, kind or facts" + }, + "422": { + "description": "Model does not compile; body carries diagnostics" + } + } + } + }, "/api/workflows/bindings": { "get": { "tags": [ diff --git a/src/docs/design/workflow-models.md b/src/docs/design/workflow-models.md index 97fdf14eb3..326f491425 100644 --- a/src/docs/design/workflow-models.md +++ b/src/docs/design/workflow-models.md @@ -332,6 +332,117 @@ exactly the pre-P4 path: one list, the built-in family, no model labels. - A model without a `labels` block regenerates nothing (TechDocs as shipped); the preview still shows its commands and the built-in stages its numbered states land on. +## Editor (RFC phase 4, UI) + +The owner's brief was "the editor needs to be a good design tool too": a design surface in the +spirit of a lightweight draw.io for state machines, not a form over the JSON. Settings → Workflows +grows an **Editor** nav item (`config-workflows-editor.js`, `workflows-editor.css`, registered +right after the library module), and the library rows and detail page grow **Edit** (owner) or +**Edit a copy** (hive-default and other built-ins, which are read-only); an ingest result gains +**Open in editor** so an ingested draft can be reviewed on the canvas before it is saved. + +**Layout.** Toolbar · left templates palette · centre SVG canvas · right inspector · bottom +tabbed drawer (Problems · YAML · Diff · Simulate). With no model loaded the Editor shows a start +screen: New blank model, Duplicate hive-default, Open from Library, From Ingest, Marketplace +(disabled placeholder for phase 7). + +**Canvas.** Columns are vertical lanes: `+ Column` adds one, double-click the header renames it, +drag the header horizontally to reorder, drag its right edge to resize (snapped to an 8px grid, +`view.laneWidths`), terminal lanes are shaded and dashed. States are chips inside lanes: drag +within or between lanes (rewrites `columns[].states` and `lifecycle.column`), double-click to +rename the label, Delete/Backspace removes the selection and its transitions (confirmed when more +than one), marquee on empty canvas, shift-click to extend, arrow keys nudge order. Each chip has +a right-edge port; dragging it onto another chip creates a transition with `on: ''`, selects it +and focuses the inspector's `on` field; clicking an edge selects it. Pan with space+drag, middle button or wheel; zoom with +ctrl/⌘+wheel or the toolbar ± / Fit; a minimap appears when the model outgrows the viewport. +**Auto-layout** orders lanes by BFS depth from the initial state (terminal lanes last), drops +unassigned states into the nearest lane by depth, and sorts each lane by stage number then +label. Compile diagnostics appear as badges on chips (error red, warning amber, tooltip text); +inferred states are dashed with a one-click ✓ **Confirm** that sets `confidence: local` locally, +and a toolbar **Confirm all inferred** that, for a stored ingested version, also calls +`POST /api/workflows/{name}/{version}/confirm` after saving. The initial state carries a marker. + +**Edge layer: quiet by default, detail on focus.** A real model (hive-default has 22 states and +~90 transitions) turns a naive one-bezier-per-transition drawing into a knot, so the canvas and +the read-only library diagram share one pure router (`wfRouteEdges` in +`config-workflows-library.js`) and a set of rules: + +- *No labels by default.* Every edge renders its event as a floating pill, but CSS shows it only + while that edge is hovered or selected. A toolbar **Labels** toggle shows labels for the + exceptional events only — the model's most common `on` (e.g. `stage-change`, detected by + `wfEdgeCommonEvent`) is never worth labelling and stays quiet. +- *Orthogonal routing through gutters, bundled per lane pair.* Edges leave the source chip's + right port, run into the gutter between the lanes, drop vertically in a channel reserved for + that (from-lane → to-lane) pair and enter the target's left port with rounded corners + (`wfOrthoPath`). Edges that share a lane pair share one vertical trunk, so the Actionable → + Claimed bundle is one line that fans out at both ends. Same-lane edges hug the lane's right + margin, stacked by distance. Edges that skip lanes run below the lanes in a corridor row; + backward edges between adjacent lanes run down the shared gutter (both ports face it), and + backward edges that skip lanes route around the *outside* above the lane headers, dashed and + muted. `wfEdgeChannels` counts the corridor rows so the layout reserves that space. +- *Focus mode.* Hovering or selecting a state dims every edge not incident to it + (`--wf-edge-dim`), lifts the incident edges into a front layer in the accent colour with + arrowheads (`fill="context-stroke"`), and outlines the neighbouring chips; hovering an edge + highlights it and both end chips and reveals its label. The hover handler + (`wfEdgeFocusHover`) is DOM-only and shared by the editor canvas and the library diagram. +- *Fan-out collapse.* More than four transitions from one state into the same lane collapse to + one trunk with a **+N** badge at the source port; hovering expands the fan, and in the editor + clicking the badge pins it open (`view.fansOpen`). + +Ports, drag-to-connect, arrowheads and the initial/terminal styling are unchanged; every colour, +opacity and size is a token so the style ratchet stays green. + +**Pure core.** Everything that mutates or lays out the model is a pure function over plain JSON +(never mutates its input, deterministic), so the undo stack is a snapshot list and the core is +unit-tested under node (`workflows_editor_ui_test.go`): `wfEdNewModel`, `wfEdNormalize`, +`wfEdAddColumn` / `wfEdMoveColumn` / `wfEdRenameColumn` / `wfEdRemoveColumn(model, id, +moveStatesTo)`, `wfEdAddState` / `wfEdMoveState` / `wfEdRenameState` (rewrites transitions, +initial, label entries, derivation rules, lanes and agent grants) / `wfEdRemoveState`, +`wfEdAddTransition` / `wfEdRemoveTransition`, `wfEdUpdate(model, path, value)` with paths like +`spec.states[id=open].lifecycle.number` (empty value deletes), `wfEdUniqueId` (slug + `-N`), +`wfEdAutoLayout`, `wfEdLayout(model, profile, view)` → lanes/chips/edges/fans geometry (edges via the shared `wfRouteEdges` / `wfOrthoPath` / `wfEdgeChannels` router), +`wfEdLaneAt` / `wfEdSlotAt` for drops, `wfEdLocalProblems` (mirrors the compiler's refusals — +`state-no-exit`, `state-no-column`, `unknown-column`, `unknown-state`, `column-empty`, +`no-terminal-column`, `duplicate-stage-number`, `unknown-event`, `inferred-element` — for +instant feedback before the server answers), `wfEdDiff(a, b)` (the client twin of +`workflowmodel.Diff`: keyed change sets for columns, states, transitions, labels and rules plus +meta field changes and a summary), `wfEdSvg(model, layout, state)` and `wfEdMinimapSvg`. + +**Runtime.** `_wfEd = {model, saved, history[], future[], selection, view{panX,panY,zoom, +laneWidths}, compile{busy,profile,diags}, drawer, sim, yaml, …}`. `wfEdCommit(next)` pushes a +deep-copy snapshot (cap 200), bumps a revision, re-renders only the affected regions and +schedules a live compile: 300 ms after the last change the model is posted to +`POST /api/workflows/compile` and the toolbar pill reads `compiles` / `N warnings` / `does not +compile`. Pointer interactions attach once per render (`wfEdAttach(root)`, idempotent) to the +canvas root; every other control is a delegated `data-action`. Cmd/Ctrl-Z, Shift-Cmd-Z and Cmd-S +work when the editor has focus. Leaving the editor with unsaved changes asks via `hiveConfirm`. + +**Drawers.** *Problems* lists diagnostics (click selects the element). *YAML* is a textarea +bound two-way through the new `POST /api/workflows/yaml` (`{model}` → `{yaml}` and `{yaml}` → +`{model, error?}`; model→YAML refreshes while the tab is visible and the textarea is not focused; +Apply parses back and commits; parse errors show inline). *Diff* shows the client-side +`wfEdDiff` of the working copy against the last save as grouped lists, and, for a stored +version, the stored-versions diff (`GET …/diff?from&to`) against any earlier version. *Simulate* +uses the library's declarative `WF_SIM_FIELDS` form and posts `{model, kind, facts}` to the new +`POST /api/workflows/simulate`, which compiles the unsaved body and runs `stageengine.Explain` +(422 with diagnostics when the model does not compile); the decided state is highlighted on the +canvas (`.wf-ed-sim-hit`, others dimmed) and the reason and trace render below the form. + +**Persistence.** *Save* posts the model with `meta.version: ''`, which `handleWorkflowSave` now +resolves through `store.NextVersion(name)`, then reloads the library and reopens the saved entry +in the editor. *Save as…* prompts a new name (version 1, provenance local). *Revert* restores the +last saved snapshot. hive-default opens read-only with an *Edit a copy* button. + +**Export.** SVG (the canvas serialized with the CSS custom-property values resolved via +`getComputedStyle`, so it is self-contained), PNG (drawn to a canvas and shown in a dialog with +open-in-new-tab — no forced download), model JSON and model YAML, all through +`hiveExportViewer`. + +**Deferred.** Editing events, gates, roles and derivation rules (they round-trip untouched and +are editable through the YAML drawer); nested regions beyond flattening; marketplace (phase 7); +keyboard-only lane reorder; collaborative/locking semantics; server-side layout persistence +(lane widths live in the session). + ## Ingest: intake, triage, roles and branch rules (RFC phase 5) `ingest.Lifecycle` now reads the repository's process conventions next to its pipelines and adds diff --git a/src/pkg/dashboard/api_workflows.go b/src/pkg/dashboard/api_workflows.go index 0ab4374b2b..76f88eac14 100644 --- a/src/pkg/dashboard/api_workflows.go +++ b/src/pkg/dashboard/api_workflows.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "net/http" + "strings" "time" "github.com/hivecommons/hive/pkg/config" @@ -28,6 +29,7 @@ func (s *Server) registerWorkflowRoutes() { s.mux.HandleFunc("DELETE /api/workflows/{name}/{version}", s.handleWorkflowDelete) s.registerWorkflowVersionRoutes() s.mux.HandleFunc("POST /api/workflows/{name}/{version}/simulate", s.handleWorkflowSimulate) + s.registerWorkflowEditorRoutes() s.registerWorkflowIngestSourceRoutes() } @@ -130,6 +132,15 @@ func (s *Server) handleWorkflowSave(w http.ResponseWriter, r *http.Request) { jsonError(w, fmt.Sprintf("body is %s@%s, path is %s@%s", m.Metadata.Name, m.Spec.Meta.Version, name, r.PathValue("version")), http.StatusBadRequest) return } + // The editor posts meta.version "" to mean "next free integer version". + if r.PathValue("name") == "" && strings.TrimSpace(m.Spec.Meta.Version) == "" && m.Metadata.Name != "" { + v, err := st.NextVersion(m.Metadata.Name) + if err != nil { + workflowStoreError(w, err) + return + } + m.Spec.Meta.Version = v + } e, err := st.Save(&m, requestUser(r), time.Now().UTC()) if err != nil { workflowStoreError(w, err) diff --git a/src/pkg/dashboard/api_workflows_editor.go b/src/pkg/dashboard/api_workflows_editor.go new file mode 100644 index 0000000000..e9596da9c0 --- /dev/null +++ b/src/pkg/dashboard/api_workflows_editor.go @@ -0,0 +1,222 @@ +package dashboard + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "strings" + + "github.com/hivecommons/hive/pkg/stageengine" + "github.com/hivecommons/hive/pkg/stagelabels" + "github.com/hivecommons/hive/pkg/workflowmodel" + "gopkg.in/yaml.v3" +) + +// Workflow-model editor support (hivecommons/hive#17620, RFC phase 4 UI). +// +// The editor works on an unsaved model in the browser, so the read-only +// computations it needs — YAML round-trip and a what-if derivation — take +// the model in the request body rather than a stored name@version. Like +// POST /api/workflows/compile they need no store and no owner role. +func (s *Server) registerWorkflowEditorRoutes() { + s.mux.HandleFunc("POST /api/workflows/yaml", s.handleWorkflowYAML) + s.mux.HandleFunc("POST /api/workflows/simulate", s.handleWorkflowSimulateModel) +} + +// workflowYAMLRequest carries either a model (→ yaml) or yaml (→ model). +type workflowYAMLRequest struct { + Model json.RawMessage `json:"model,omitempty"` + YAML string `json:"yaml,omitempty"` +} + +// handleWorkflowYAML converts between the JSON model and its YAML form. +// Field names are the json tags on both sides: the JSON document is parsed +// as YAML (JSON is a YAML subset) and re-encoded, so a round-trip changes +// nothing but whitespace. A YAML parse or schema error answers 200 with +// `error` set so the editor can show it inline next to the text. +func (s *Server) handleWorkflowYAML(w http.ResponseWriter, r *http.Request) { + var req workflowYAMLRequest + if err := decodeBody(r, &req); err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + switch { + case len(req.Model) > 0 && strings.TrimSpace(string(req.Model)) != "null": + var m workflowmodel.Model + if err := json.Unmarshal(req.Model, &m); err != nil { + jsonError(w, "model: "+err.Error(), http.StatusBadRequest) + return + } + out, err := workflowModelToYAML(&m) + if err != nil { + jsonError(w, err.Error(), http.StatusInternalServerError) + return + } + jsonResponse(w, map[string]interface{}{"yaml": out}) + case strings.TrimSpace(req.YAML) != "": + m, err := workflowModelFromYAML(req.YAML) + if err != nil { + jsonResponse(w, map[string]interface{}{"error": err.Error()}) + return + } + jsonResponse(w, map[string]interface{}{"model": m}) + default: + jsonError(w, "set model (to get yaml) or yaml (to get a model)", http.StatusBadRequest) + } +} + +func workflowModelToYAML(m *workflowmodel.Model) (string, error) { + b, err := json.Marshal(m) + if err != nil { + return "", err + } + var node yaml.Node + if err := yaml.Unmarshal(b, &node); err != nil { + return "", err + } + // The JSON decoder leaves flow style on every mapping; clear it so the + // encoder writes block YAML. + workflowYAMLBlockStyle(&node) + var buf bytes.Buffer + enc := yaml.NewEncoder(&buf) + enc.SetIndent(2) + if err := enc.Encode(&node); err != nil { + return "", err + } + if err := enc.Close(); err != nil { + return "", err + } + return buf.String(), nil +} + +func workflowYAMLBlockStyle(n *yaml.Node) { + if n == nil { + return + } + if n.Kind == yaml.MappingNode || n.Kind == yaml.SequenceNode { + n.Style = 0 + } + if n.Kind == yaml.ScalarNode && n.Style == yaml.DoubleQuotedStyle { + n.Style = 0 + } + for _, c := range n.Content { + workflowYAMLBlockStyle(c) + } +} + +func workflowModelFromYAML(text string) (*workflowmodel.Model, error) { + var generic interface{} + if err := yaml.Unmarshal([]byte(text), &generic); err != nil { + return nil, err + } + generic = workflowYAMLToJSONValue(generic) + b, err := json.Marshal(generic) + if err != nil { + return nil, err + } + var m workflowmodel.Model + dec := json.NewDecoder(bytes.NewReader(b)) + dec.DisallowUnknownFields() + if err := dec.Decode(&m); err != nil { + return nil, err + } + return &m, nil +} + +// workflowYAMLToJSONValue turns yaml.v3's map[string]interface{} and +// []interface{} trees into JSON-marshalable values (yaml.v3 already uses +// string keys for string-keyed maps; non-string keys are stringified). +func workflowYAMLToJSONValue(v interface{}) interface{} { + switch t := v.(type) { + case map[string]interface{}: + out := make(map[string]interface{}, len(t)) + for k, val := range t { + out[k] = workflowYAMLToJSONValue(val) + } + return out + case map[interface{}]interface{}: + out := make(map[string]interface{}, len(t)) + for k, val := range t { + out[fmt.Sprint(k)] = workflowYAMLToJSONValue(val) + } + return out + case []interface{}: + for i := range t { + t[i] = workflowYAMLToJSONValue(t[i]) + } + return t + } + return v +} + +// workflowSimulateModelRequest is the editor's variant of the stored-model +// simulate request: the model travels in the body and facts are required +// (no forge fetch — the canvas may hold something that was never saved). +type workflowSimulateModelRequest struct { + Model *workflowmodel.Model `json:"model"` + Kind string `json:"kind"` + Facts *SimulateFacts `json:"facts"` +} + +// handleWorkflowSimulateModel answers POST /api/workflows/simulate with the +// same SimulateResponse as the stored-model variant. 422 with diagnostics +// when the posted model does not compile, so the editor can point at the +// offending element instead of a bare "does not compile". +func (s *Server) handleWorkflowSimulateModel(w http.ResponseWriter, r *http.Request) { + var req workflowSimulateModelRequest + if err := decodeBody(r, &req); err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + if req.Model == nil { + jsonError(w, "model is required", http.StatusBadRequest) + return + } + req.Kind = strings.ToLower(strings.TrimSpace(req.Kind)) + if req.Kind == "" { + jsonError(w, "kind must be issue or pr", http.StatusBadRequest) + return + } + if req.Facts == nil { + jsonError(w, "facts are required when simulating an unsaved model", http.StatusBadRequest) + return + } + profile, diags, cerr := workflowmodel.Compile(req.Model) + if cerr != nil { + if diags == nil { + diags = []workflowmodel.Diagnostic{} + } + jsonStatusResponse(w, http.StatusUnprocessableEntity, map[string]interface{}{ + "error": fmt.Sprintf("model does not compile: %d diagnostics", len(diags)), + "diagnostics": diags, + }) + return + } + ref, err := stageengine.SimulateRef(req.Kind, "sim", "sim", 0) + if err != nil { + jsonError(w, err.Error(), http.StatusBadRequest) + return + } + var notes []string + norm := normalizeSimulateFacts(req.Kind, *req.Facts) + ef := norm.toEngine(ref) + if ref.Kind == stagelabels.PRItem && len(ef.PR.Lanes) == 0 { + lane := stageengine.SimulatedLane(ef) + ef.PR.Lanes = []stageengine.LaneFact{lane} + norm.PR.Lane = &SimulateLane{Lane: lane.Lane, Reason: lane.Reason} + notes = append(notes, fmt.Sprintf("no lane observation supplied; simulated lane %s with reason %q from the head facts", lane.Lane, lane.Reason)) + } + dec, trace := stageengine.Explain(profile, ref.Kind, ef) + if trace == nil { + trace = []stageengine.RuleTrace{} + } + jsonResponse(w, SimulateResponse{ + Decision: simulateDecision(profile, dec), + Trace: trace, + Facts: norm, + Filled: []string{}, + Unknown: []string{}, + Notes: notes, + }) +} diff --git a/src/pkg/dashboard/api_workflows_editor_test.go b/src/pkg/dashboard/api_workflows_editor_test.go new file mode 100644 index 0000000000..2e16349e68 --- /dev/null +++ b/src/pkg/dashboard/api_workflows_editor_test.go @@ -0,0 +1,124 @@ +package dashboard + +import ( + "encoding/json" + "net/http" + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/workflowmodel" + "github.com/hivecommons/hive/pkg/workflowmodel/hivedefault" +) + +func TestWorkflowYAMLRoundTrip(t *testing.T) { + s := workflowTestServer(t, false) + m := techdocsModel(t) + rec := wfReq(s, http.MethodPost, "/api/workflows/yaml", map[string]any{"model": m}, false) + if rec.Code != http.StatusOK { + t.Fatalf("to yaml: %d %s", rec.Code, rec.Body) + } + var out struct { + YAML string `json:"yaml"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(out.YAML, "apiVersion: ") || !strings.Contains(out.YAML, "\nspec:\n") || strings.Contains(out.YAML, "{") { + t.Fatalf("expected block yaml, got:\n%s", out.YAML) + } + rec = wfReq(s, http.MethodPost, "/api/workflows/yaml", map[string]any{"yaml": out.YAML}, false) + if rec.Code != http.StatusOK { + t.Fatalf("from yaml: %d %s", rec.Code, rec.Body) + } + var back struct { + Model *workflowmodel.Model `json:"model"` + Error string `json:"error"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &back); err != nil { + t.Fatal(err) + } + if back.Error != "" || back.Model == nil { + t.Fatalf("round trip: %s", rec.Body) + } + a, _ := json.Marshal(m) + b, _ := json.Marshal(back.Model) + if string(a) != string(b) { + t.Fatalf("model changed across yaml round trip:\n%s\n%s", a, b) + } +} + +func TestWorkflowYAMLErrorsInline(t *testing.T) { + s := workflowTestServer(t, false) + for _, text := range []string{"spec: [unclosed", "metadata:\n name: x\nbogus: 1\n"} { + rec := wfReq(s, http.MethodPost, "/api/workflows/yaml", map[string]any{"yaml": text}, false) + if rec.Code != http.StatusOK { + t.Fatalf("%q: %d %s", text, rec.Code, rec.Body) + } + var out map[string]any + _ = json.Unmarshal(rec.Body.Bytes(), &out) + if e, _ := out["error"].(string); e == "" { + t.Fatalf("%q: expected inline error, got %s", text, rec.Body) + } + } + rec := wfReq(s, http.MethodPost, "/api/workflows/yaml", map[string]any{}, false) + if rec.Code != http.StatusBadRequest { + t.Fatalf("empty body: %d", rec.Code) + } +} + +func TestWorkflowSimulateUnsavedModel(t *testing.T) { + s := workflowTestServer(t, false) + rec := wfReq(s, http.MethodPost, "/api/workflows/simulate", map[string]any{ + "model": hivedefault.Generate(), "kind": "pr", + "facts": map[string]any{ + "labels": []string{"role/trusted"}, "open": true, + "author": map[string]any{"login": "andy", "kind": "human", "role": "trusted"}, + "pr": map[string]any{"checks": "green", "review": "approved", "dco": "yes"}, + }, + }, false) + if rec.Code != http.StatusOK { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + var out SimulateResponse + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatal(err) + } + if out.Decision.Stage != 80 || out.Decision.State != "awaiting-merge-admission" || len(out.Trace) != 1 { + t.Fatalf("decision %+v trace %+v", out.Decision, out.Trace) + } + + // Missing facts and missing kind are 400s; a non-compiling model is a + // 422 that carries the diagnostics. + rec = wfReq(s, http.MethodPost, "/api/workflows/simulate", map[string]any{"model": hivedefault.Generate(), "kind": "pr"}, false) + if rec.Code != http.StatusBadRequest { + t.Fatalf("no facts: %d", rec.Code) + } + rec = wfReq(s, http.MethodPost, "/api/workflows/simulate", map[string]any{"model": hivedefault.Generate(), "facts": map[string]any{}}, false) + if rec.Code != http.StatusBadRequest { + t.Fatalf("no kind: %d", rec.Code) + } + broken := techdocsModel(t) + broken.Spec.Transitions = nil + rec = wfReq(s, http.MethodPost, "/api/workflows/simulate", map[string]any{"model": broken, "kind": "issue", "facts": map[string]any{"open": true}}, false) + if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), `"diagnostics"`) { + t.Fatalf("broken model: %d %s", rec.Code, rec.Body) + } +} + +func TestWorkflowSaveAssignsNextVersionWhenEmpty(t *testing.T) { + s := workflowTestServer(t, true) + m := techdocsModel(t) + m.Metadata.Name = "editor-draft" + m.Spec.Meta.Version = "" + rec := wfReq(s, http.MethodPost, "/api/workflows", m, true) + if rec.Code != http.StatusCreated { + t.Fatalf("first save: %d %s", rec.Code, rec.Body) + } + if !strings.Contains(rec.Body.String(), `"version":"1"`) { + t.Fatalf("expected version 1: %s", rec.Body) + } + rec = wfReq(s, http.MethodPost, "/api/workflows", m, true) + if rec.Code != http.StatusCreated || !strings.Contains(rec.Body.String(), `"version":"2"`) { + t.Fatalf("second save: %d %s", rec.Code, rec.Body) + } +} diff --git a/src/pkg/dashboard/static-src/css/workflows-editor.css b/src/pkg/dashboard/static-src/css/workflows-editor.css new file mode 100644 index 0000000000..7d8276cd3d --- /dev/null +++ b/src/pkg/dashboard/static-src/css/workflows-editor.css @@ -0,0 +1,146 @@ +/* Settings → Workflows → Editor (#17620 phase 4): toolbar, palette, canvas, inspector, drawer */ + .wf-ed { display: flex; flex-direction: column; gap: var(--sp-2); min-height: 32rem; height: calc(100vh - 22rem); } + .wf-ed-toolbar { display: flex; align-items: center; gap: var(--sp-2); flex-wrap: wrap; padding: var(--sp-2) var(--sp-3); background: var(--panel); border: var(--line-width) solid var(--border); border-radius: var(--r-sm); } + .wf-ed-title { display: inline-flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-sm); font-weight: 700; margin-right: var(--sp-2); } + .wf-ed-dirty { color: var(--status-warn); } + .wf-ed-ro { color: var(--muted); font-weight: 400; font-size: var(--fs-xs); border: var(--line-width) solid var(--border); border-radius: var(--r-pill); padding: var(--sp-0) var(--sp-2); } + .wf-ed-status { display: inline-block; border-radius: var(--r-pill); padding: var(--sp-1) var(--sp-3); font-size: var(--fs-xs); font-weight: 700; cursor: pointer; border: var(--line-width) solid var(--border); white-space: nowrap; max-width: 24rem; overflow: hidden; text-overflow: ellipsis; } + .wf-ed-status.ok { color: var(--status-ok); border-color: color-mix(in srgb, var(--status-ok) 40%, transparent); } + .wf-ed-status.warn { color: var(--status-warn); border-color: color-mix(in srgb, var(--status-warn) 40%, transparent); } + .wf-ed-status.error { color: var(--status-error); border-color: color-mix(in srgb, var(--status-error) 40%, transparent); } + .wf-ed-status.busy { opacity: .7; } + .wf-ed-sep { width: var(--line-width); align-self: stretch; background: var(--border); margin: var(--sp-0) var(--sp-1); } + .wf-ed-grow { flex: 1 1 auto; } + .wf-ed-zoom { font-size: var(--fs-xs); color: var(--muted); min-width: 3em; text-align: center; } + .wf-ed-menu { position: relative; display: inline-block; } + .wf-ed-menu-items { position: absolute; top: 100%; left: 0; z-index: 5; display: flex; flex-direction: column; min-width: 10rem; background: var(--panel-strong); border: var(--line-width) solid var(--border); border-radius: var(--r-sm); padding: var(--sp-1); box-shadow: 0 var(--sp-2) var(--sp-5) color-mix(in srgb, var(--text) 20%, transparent); } + .wf-ed-menu-items button { background: none; border: none; color: var(--text); font: inherit; font-size: var(--fs-sm); text-align: left; padding: var(--sp-2) var(--sp-3); border-radius: var(--r-sm); cursor: pointer; } + .wf-ed-menu-items button:hover { background: var(--bg-soft); } + + .wf-ed-main { display: grid; grid-template-columns: 13rem minmax(0, 1fr) 18rem; gap: var(--sp-2); flex: 1 1 auto; min-height: 0; } + .wf-ed-palette, .wf-ed-inspector { background: var(--panel); border: var(--line-width) solid var(--border); border-radius: var(--r-sm); padding: var(--sp-3); overflow: auto; font-size: var(--fs-sm); min-height: 0; } + .wf-ed-palette h4, .wf-ed-inspector h4 { margin: var(--sp-0) var(--sp-0) var(--sp-3); font-size: var(--fs-base); } + .wf-ed-inspector h5 { margin: var(--sp-4) var(--sp-0) var(--sp-2); font-size: var(--fs-sm); color: var(--muted); } + .wf-ed-pal-section summary { cursor: pointer; font-weight: 700; font-size: var(--fs-xs); text-transform: uppercase; letter-spacing: .04em; color: var(--muted); padding: var(--sp-2) var(--sp-0); } + .wf-ed-pal-list { display: flex; flex-direction: column; gap: var(--sp-1); padding-bottom: var(--sp-2); } + .wf-ed-pal-item { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: var(--sp-2) var(--sp-3); border: var(--line-width) solid var(--line-strong); border-radius: var(--r-sm); background: var(--panel-strong); cursor: grab; font-size: var(--fs-sm); user-select: none; } + .wf-ed-pal-item:hover { border-color: var(--brand); } + .wf-ed-pal-item.disabled { opacity: .5; cursor: default; } + .wf-ed-pal-sub { color: var(--muted); font-size: var(--fs-2xs); } + + .wf-ed-canvas { position: relative; background: var(--bg); border: var(--line-width) solid var(--border); border-radius: var(--r-sm); overflow: hidden; min-height: 20rem; touch-action: none; } + .wf-ed-svg { display: block; width: 100%; height: 100%; font-family: var(--font-ui); outline: none; cursor: default; } + .wf-ed-svg:focus-visible { box-shadow: inset 0 0 0 2px var(--brand); } + .wf-ed-bg { cursor: crosshair; } + .wf-ed-gridline { stroke: color-mix(in srgb, var(--border) 60%, transparent); stroke-width: .5; fill: none; } + .wf-ed-lane { fill: color-mix(in srgb, var(--panel) 70%, var(--bg)); stroke: var(--border); stroke-width: 1; } + .wf-ed-col.terminal .wf-ed-lane { fill: color-mix(in srgb, var(--status-ok) 6%, var(--bg)); stroke-dasharray: 4 3; } + .wf-ed-col.virtual .wf-ed-lane { fill: none; stroke-dasharray: 2 4; } + .wf-ed-col.selected .wf-ed-lane { stroke: var(--brand); stroke-width: 2; } + .wf-ed-col.drop .wf-ed-lane { stroke: var(--brand); fill: color-mix(in srgb, var(--brand) 8%, var(--bg)); } + .wf-ed-lanehead { fill: var(--panel-strong); cursor: grab; } + .wf-ed-lanehead:focus-visible { stroke: var(--brand); stroke-width: 2; outline: none; } + .wf-ed-colname { fill: var(--muted); font-size: var(--fs-xs); font-weight: 700; text-transform: uppercase; letter-spacing: .04em; pointer-events: none; } + .wf-ed-resize { fill: transparent; cursor: col-resize; } + .wf-ed-resize:hover { fill: color-mix(in srgb, var(--brand) 25%, transparent); } + .wf-ed-chip { fill: var(--panel-strong); stroke: var(--line-strong); stroke-width: 1; } + .wf-ed-state { cursor: grab; outline: none; } + .wf-ed-state:hover .wf-ed-chip { stroke: var(--text); } + .wf-ed-state:focus-visible .wf-ed-chip, .wf-ed-state.selected .wf-ed-chip { stroke: var(--brand); stroke-width: 2; } + .wf-ed-state.initial .wf-ed-chip { stroke: var(--status-info); stroke-width: 1.5; } + .wf-ed-state.initial.selected .wf-ed-chip { stroke: var(--brand); } + .wf-ed-state.terminal .wf-ed-chip { stroke-width: 2; } + .wf-ed-state.inferred .wf-ed-chip { stroke-dasharray: 4 3; stroke: var(--status-warn); } + .wf-ed-state.error .wf-ed-chip { stroke: var(--status-error); } + .wf-ed-state.dragging { opacity: .4; } + .wf-ed-state.wf-ed-sim-hit .wf-ed-chip { stroke: var(--status-ok); stroke-width: 3; fill: color-mix(in srgb, var(--status-ok) 12%, var(--panel-strong)); } + .wf-ed-state.wf-ed-sim-dim { opacity: .45; } + .wf-ed-initial { fill: var(--status-info); } + .wf-ed-label { fill: var(--text); font-size: var(--fs-sm); pointer-events: none; } + .wf-ed-num { fill: var(--muted); font-size: var(--fs-2xs); font-family: var(--font-mono); pointer-events: none; } + .wf-ed-port { fill: var(--panel-strong); stroke: var(--muted); stroke-width: 1.5; cursor: crosshair; opacity: 0; } + .wf-ed-state:hover .wf-ed-port, .wf-ed-state.selected .wf-ed-port, .wf-ed-state:focus-visible .wf-ed-port { opacity: 1; } + .wf-ed-port:hover { fill: var(--brand); stroke: var(--brand); } + .wf-ed-edge { cursor: pointer; } + .wf-ed-edge-hit { fill: none; stroke: transparent; stroke-width: 12; } + .wf-ed-edge-line { fill: none; stroke: var(--muted); stroke-width: 1.25; opacity: var(--wf-edge-quiet); } + .wf-ed-edge.back .wf-ed-edge-line { stroke-dasharray: 3 3; opacity: var(--wf-edge-back); } + .wf-focus .wf-ed-edge:not(.focus):not(.selected) .wf-ed-edge-line, .wf-focus .wf-fan-trunk { opacity: var(--wf-edge-dim); } + .wf-focus .wf-ed-state:not(.focus):not(.selected) .wf-ed-chip, .wf-focus .wf-ed-state:not(.focus):not(.selected) text { opacity: var(--wf-edge-quiet); } + .wf-ed-edge.focus .wf-ed-edge-line, .wf-ed-edge:hover .wf-ed-edge-line { stroke: var(--brand); stroke-width: 2; opacity: 1; } + .wf-ed-edge.selected .wf-ed-edge-line { stroke: var(--brand); stroke-width: 2.5; opacity: 1; } + .wf-ed-state.focus .wf-ed-chip { stroke: var(--brand); } + .wf-ed-edge.error .wf-ed-edge-line { stroke: var(--status-error); opacity: 1; } + .wf-ed-edge.warning .wf-ed-edge-line { stroke: var(--status-warn); opacity: 1; } + .wf-ed-edge-label { display: none; } + .wf-ed-edge.selected .wf-ed-edge-label, .wf-ed-edge:hover .wf-ed-edge-label, + .wf-ed-edge.error .wf-ed-edge-label, .wf-ed-edge.warning .wf-ed-edge-label, + .wf-edge-layer.show-labels .wf-ed-edge:not(.common) .wf-ed-edge-label { display: inline; } + .wf-ed-edge-label text { fill: var(--brand); font-size: var(--fs-2xs); font-weight: 600; pointer-events: none; } + .wf-ed-edge-label-bg { fill: var(--panel); stroke: var(--brand); stroke-width: 1; } + .wf-ed-edge.error .wf-ed-edge-label text { fill: var(--status-error); } + .wf-ed-edge.error .wf-ed-edge-label-bg { stroke: var(--status-error); } + .wf-ed-edge.warning .wf-ed-edge-label text { fill: var(--status-warn); } + .wf-ed-edge.warning .wf-ed-edge-label-bg { stroke: var(--status-warn); } + .wf-ed-edge-pending { fill: none; stroke: var(--brand); stroke-width: 1.5; stroke-dasharray: 4 3; pointer-events: none; } + .wf-ed-arrowhead { fill: var(--muted); } + .wf-ed-badge circle { fill: var(--status-warn); } + .wf-ed-badge.error circle { fill: var(--status-error); } + .wf-ed-badge text { fill: var(--panel); font-size: var(--fs-2xs); font-weight: 700; pointer-events: none; } + .wf-ed-badge { cursor: help; } + .wf-ed-confirm { cursor: pointer; } + .wf-ed-confirm rect { fill: color-mix(in srgb, var(--status-ok) 18%, var(--panel-strong)); stroke: var(--status-ok); stroke-width: 1; } + .wf-ed-confirm text { fill: var(--status-ok); font-size: var(--fs-2xs); font-weight: 700; pointer-events: none; } + .wf-ed-confirm:hover rect { fill: var(--status-ok); } + .wf-ed-confirm:hover text { fill: var(--panel); } + .wf-ed-marquee { fill: color-mix(in srgb, var(--brand) 10%, transparent); stroke: var(--brand); stroke-dasharray: 4 2; stroke-width: 1; pointer-events: none; } + .wf-ed-minimap { position: absolute; right: var(--sp-3); bottom: var(--sp-8); background: color-mix(in srgb, var(--panel) 85%, transparent); border: var(--line-width) solid var(--border); border-radius: var(--r-sm); padding: var(--sp-1); cursor: pointer; } + .wf-ed-minimap-svg { display: block; } + .wf-ed-mm-lane { fill: var(--panel-strong); stroke: var(--border); stroke-width: .5; } + .wf-ed-mm-lane.terminal { fill: color-mix(in srgb, var(--status-ok) 10%, var(--panel-strong)); } + .wf-ed-mm-chip { fill: var(--muted); } + .wf-ed-mm-view { fill: color-mix(in srgb, var(--brand) 10%, transparent); stroke: var(--brand); stroke-width: 1; } + .wf-ed-hint { position: absolute; left: var(--sp-3); bottom: var(--sp-2); font-size: var(--fs-2xs); pointer-events: none; } + + .wf-ed-field { display: block; margin-bottom: var(--sp-3); } + .wf-ed-field > span { display: block; margin-top: var(--sp-1); } + .wf-ed-field input[type="text"], .wf-ed-field input[type="number"], .wf-ed-field select, .wf-ed-field textarea { width: 100%; } + .wf-ed-field input[readonly] { color: var(--muted); } + .wf-ed-inline { display: flex; gap: var(--sp-2); align-items: center; } + .wf-ed-inline input { flex: 1 1 auto; min-width: 0; } + .wf-ed-checks { display: flex; gap: var(--sp-4); align-items: center; flex-wrap: wrap; } + .wf-ed-warn { color: var(--status-warn); } + .wf-ed-translist { margin: var(--sp-0); padding-left: var(--sp-5); font-size: var(--fs-xs); } + .wf-ed-translist a { color: var(--text); text-decoration: none; } + .wf-ed-translist a:hover { text-decoration: underline; } + + .wf-ed-drawer { background: var(--panel); border: var(--line-width) solid var(--border); border-radius: var(--r-sm); display: flex; flex-direction: column; flex: 0 0 auto; max-height: 2.5rem; overflow: hidden; } + .wf-ed-drawer.open { max-height: 16rem; } + .wf-ed-drawer-tabs { display: flex; gap: var(--sp-1); border-bottom: var(--line-width) solid var(--border); padding: var(--sp-0) var(--sp-2); } + .wf-ed-drawer-tab { background: none; border: none; border-bottom: 2px solid transparent; color: var(--muted); font: inherit; font-size: var(--fs-xs); font-weight: 700; padding: var(--sp-2) var(--sp-3); cursor: pointer; } + .wf-ed-drawer-tab.active { color: var(--text); border-bottom-color: var(--brand); } + .wf-ed-drawer-body { overflow: auto; padding: var(--sp-3); font-size: var(--fs-sm); min-height: 0; } + .wf-ed-drawer-body .wf-sim-form { grid-template-columns: repeat(auto-fill, minmax(11rem, 1fr)); } + .wf-ed-problems { margin: var(--sp-0); padding-left: var(--sp-5); } + .wf-ed-problem a { color: var(--text); text-decoration: none; } + .wf-ed-problem a:hover { text-decoration: underline; } + .wf-ed-problem.error .wf-diag-code { color: var(--status-error); } + .wf-ed-problem.warning .wf-diag-code { color: var(--status-warn); } + .wf-ed-yaml-bar { display: flex; align-items: center; gap: var(--sp-2); margin-bottom: var(--sp-2); } + .wf-ed-yaml-bar span { flex: 1 1 auto; } + .wf-ed-yaml { width: 100%; min-height: 10rem; font-size: var(--fs-xs); background: var(--bg-soft); border: var(--line-width) solid var(--border); border-radius: var(--r-sm); padding: var(--sp-2); resize: vertical; } + .wf-ed-diff-group h5 { margin: var(--sp-3) var(--sp-0) var(--sp-1); font-size: var(--fs-xs); color: var(--muted); text-transform: uppercase; letter-spacing: .04em; } + .wf-ed-diff-row { padding: var(--sp-0) var(--sp-2); font-size: var(--fs-xs); border-left: 3px solid var(--border); margin-bottom: var(--sp-1); } + .wf-ed-diff-row.added { border-left-color: var(--status-ok); } + .wf-ed-diff-row.removed { border-left-color: var(--status-error); } + .wf-ed-diff-row.changed { border-left-color: var(--status-warn); } + .wf-ed-diff-row ul { margin: var(--sp-0); padding-left: var(--sp-5); } + + .wf-ed-start-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr)); gap: var(--sp-3); margin: var(--sp-4) var(--sp-0); } + .wf-ed-start-card { display: flex; flex-direction: column; gap: var(--sp-1); align-items: flex-start; text-align: left; padding: var(--sp-4); background: var(--panel); border: var(--line-width) solid var(--border); border-radius: var(--r-lg); color: var(--text); font: inherit; cursor: pointer; } + .wf-ed-start-card:hover:not([disabled]) { border-color: var(--brand); } + .wf-ed-start-card[disabled] { opacity: .55; cursor: not-allowed; } + .wf-ed-start-card span { color: var(--muted); font-size: var(--fs-xs); } + .wf-ed-start h4 { margin: var(--sp-5) var(--sp-0) var(--sp-2); font-size: var(--fs-base); } + .wf-ed-start-list { margin: var(--sp-0); padding-left: var(--sp-5); font-size: var(--fs-sm); display: flex; flex-direction: column; gap: var(--sp-1); } + .wf-ed-png { max-width: 100%; height: auto; display: block; border: var(--line-width) solid var(--border); border-radius: var(--r-sm); } diff --git a/src/pkg/dashboard/static-src/css/workflows.css b/src/pkg/dashboard/static-src/css/workflows.css index 020cf4b6db..7ae7bc94b8 100644 --- a/src/pkg/dashboard/static-src/css/workflows.css +++ b/src/pkg/dashboard/static-src/css/workflows.css @@ -30,10 +30,33 @@ .wf-dg-state.inferred .wf-dg-chip { stroke-dasharray: 4 3; stroke: var(--status-warn); } .wf-dg-label { fill: var(--text); font-size: var(--fs-sm); } .wf-dg-num { fill: var(--muted); font-size: var(--fs-2xs); } - .wf-dg-edge { fill: none; stroke: var(--muted); stroke-width: 1.25; opacity: .8; } - .wf-dg-edge.back { stroke-dasharray: 3 3; } - .wf-dg-edge:hover { stroke: var(--text); stroke-width: 2; opacity: 1; } + /* Edge layer: quiet by default, detail on focus. Hovering a state or an + edge (wfEdgeFocusHover) dims everything not incident and lifts the + focused edges into .wf-edge-front with the accent colour. */ + .wf-diagram, .wf-ed-svg { --wf-edge-dim: .18; --wf-edge-quiet: .7; --wf-edge-back: .55; } + .wf-dg-edge { cursor: default; } + .wf-dg-edge-hit { fill: none; stroke: transparent; stroke-width: 10; } + .wf-dg-edge-line { fill: none; stroke: var(--muted); stroke-width: 1.25; opacity: var(--wf-edge-quiet); } + .wf-dg-edge.back .wf-dg-edge-line { stroke-dasharray: 3 3; opacity: var(--wf-edge-back); } + .wf-focus .wf-dg-edge:not(.focus) .wf-dg-edge-line, .wf-focus .wf-fan-trunk { opacity: var(--wf-edge-dim); } + .wf-focus .wf-dg-state:not(.focus) .wf-dg-chip, .wf-focus .wf-dg-state:not(.focus) text { opacity: var(--wf-edge-quiet); } + .wf-dg-edge.focus .wf-dg-edge-line, .wf-dg-edge:hover .wf-dg-edge-line { stroke: var(--brand); stroke-width: 2; opacity: 1; } + .wf-dg-state.focus .wf-dg-chip { stroke: var(--brand); } .wf-dg-arrowhead { fill: var(--muted); } + .wf-dg-edge-label { display: none; } + .wf-dg-edge:hover .wf-dg-edge-label { display: inline; } + .wf-dg-edge-label text { fill: var(--brand); font-size: var(--fs-2xs); font-weight: 600; pointer-events: none; } + .wf-dg-edge-label-bg { fill: var(--panel); stroke: var(--brand); stroke-width: 1; } + /* Fan-out bundles: >N edges from one state into one lane collapse to a trunk with a +N badge; hover expands. */ + .wf-fan .wf-fan-edge { display: none; } + .wf-fan:hover .wf-fan-edge, .wf-fan.open .wf-fan-edge, .wf-fan:focus-within .wf-fan-edge { display: inline; } + .wf-fan:hover .wf-fan-trunk, .wf-fan.open .wf-fan-trunk { display: none; } + .wf-fan-trunk { stroke-width: 2.5; } + .wf-fan-badge { cursor: pointer; } + .wf-fan-badge rect { fill: var(--panel-strong); stroke: var(--muted); stroke-width: 1; } + .wf-fan-badge text { fill: var(--text); font-size: var(--fs-2xs); font-weight: 700; pointer-events: none; } + .wf-fan-badge:hover rect { stroke: var(--brand); } + .wf-fan-badge:hover text { fill: var(--brand); } .wf-diags, .wf-citations, .wf-pipelines { margin: var(--sp-0); padding-left: var(--sp-6); font-size: var(--fs-sm); } .wf-diag-code { color: var(--muted); margin-right: var(--sp-2); } .wf-diag-error .wf-diag-code { color: var(--status-error); } diff --git a/src/pkg/dashboard/static-src/js/config-tabs.js b/src/pkg/dashboard/static-src/js/config-tabs.js index 858f7df9df..c16d315d5b 100644 --- a/src/pkg/dashboard/static-src/js/config-tabs.js +++ b/src/pkg/dashboard/static-src/js/config-tabs.js @@ -63,6 +63,9 @@ if (tabId === 'Appearance') loadThemeConfig(); if (tabId === 'Knowledge') { renderPublicKnowledgeControls(); loadKnowledgeConnectors(); loadKnowledgePipeline(); } if (tabId === 'Compliance') loadComplianceStatus(); + // The workflow editor's canvas needs real pointer listeners and a + // measured viewport once its SVG is in the DOM. + if (tabId === 'Workflows' && typeof wfEdAfterRender === 'function') wfEdAfterRender(); } // Keep the Save button's enabled state in lockstep with the repos/default // invariant on every render (requirement #4). Cheap and idempotent — a diff --git a/src/pkg/dashboard/static-src/js/config-workflows-editor.js b/src/pkg/dashboard/static-src/js/config-workflows-editor.js new file mode 100644 index 0000000000..6649151761 --- /dev/null +++ b/src/pkg/dashboard/static-src/js/config-workflows-editor.js @@ -0,0 +1,1846 @@ +// Settings → Workflows → Editor (hivecommons/hive#17620, RFC phase 4 UI). + // + // A design surface for workflow models: columns are vertical lanes on an + // SVG canvas, states are chips inside them, transitions are edges drawn + // by dragging from a chip's port. Everything that changes the model goes + // through the pure functions in the first half of this file (wfEd* that + // take a model and return a new one) so the node harness + // (workflows_editor_ui_test.go) can exercise them without a DOM. The + // second half is the runtime: _wfEd state, render, pointer handling, + // live compile, the YAML/Diff/Simulate drawers and persistence. + const WF_ED = { colW: 200, colGap: 32, chipH: 34, chipGap: 12, headH: 36, pad: 16, grid: 8, minRows: 4, portR: 5, minColW: 120, maxColW: 480 }; + const WF_ED_HISTORY_CAP = 200; + const WF_ED_COMPILE_DEBOUNCE_MS = 300; + const WF_ED_YAML_DEBOUNCE_MS = 500; + const WF_ED_UNASSIGNED = '__unassigned'; + const WF_ED_API_VERSION = 'workflow.hivecommons.dev/v1alpha1'; + const WF_ED_KINDS = ['issue', 'pr']; + const WF_ED_OWNERS = ['human', 'registered-agent', 'external-service', 'external-observation']; + const WF_ED_STATE_TYPES = ['', 'parallel', 'final']; + const WF_ED_DERIVATIONS = ['builtin', 'rules']; + const WF_ED_DRAWERS = ['problems', 'yaml', 'diff', 'simulate']; + // Palette: common states and columns. Numbers follow hive-default's + // stage ladder so a palette-built model lines up with builtin derivation. + const WF_ED_PALETTE_STATES = [ + { id: 'open', label: 'Open', number: 10 }, + { id: 'triage', label: 'Triage', number: 20 }, + { id: 'needs-decision', label: 'Needs decision', number: 25, kinds: ['issue'] }, + { id: 'claimed', label: 'Claimed', number: 30, kinds: ['issue'] }, + { id: 'in-progress', label: 'Work in progress', number: 40 }, + { id: 'in-review', label: 'In review', number: 60, kinds: ['pr'] }, + { id: 'ci-failing', label: 'CI failing', number: 65, kinds: ['pr'] }, + { id: 'merge-queue', label: 'Merge queue', number: 80, kinds: ['pr'] }, + { id: 'merged', label: 'Merged', number: 90, kinds: ['pr'] }, + { id: 'released', label: 'Released', number: 95 }, + { id: 'deployed-staging', label: 'Deployed · staging', number: 96 }, + { id: 'deployed-production', label: 'Deployed · production', number: 97 }, + { id: 'done', label: 'Done', number: 100 }, + { id: 'blocked', label: 'Blocked', number: 50 }, + ]; + const WF_ED_PALETTE_COLUMNS = [ + { id: 'intake', label: 'Intake' }, + { id: 'analysis', label: 'Analysis' }, + { id: 'writing', label: 'Writing' }, + { id: 'review', label: 'Review' }, + { id: 'publish', label: 'Publish' }, + { id: 'done', label: 'Done', terminal: true }, + ]; + + // --- Pure model core ---------------------------------------------------- + + function wfEdClone(v) { return v === undefined ? undefined : JSON.parse(JSON.stringify(v)); } + + function wfEdSlug(s) { + return String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48) || 'item'; + } + + function wfEdSpec(model) { return (model && model.spec) || {}; } + + // wfEdStates flattens states including regions (the compiler does too). + function wfEdStates(model) { + const out = []; + (function walk(list) { (list || []).forEach(s => { if (s && s.id) { out.push(s); walk(s.regions); } }); })(wfEdSpec(model).states); + return out; + } + + function wfEdFindState(model, id) { return wfEdStates(model).find(s => s.id === id) || null; } + function wfEdFindColumn(model, id) { return (wfEdSpec(model).columns || []).find(c => c.id === id) || null; } + + function wfEdUniqueId(model, base) { + const taken = {}; + wfEdStates(model).forEach(s => { taken[s.id] = true; }); + (wfEdSpec(model).columns || []).forEach(c => { taken[c.id] = true; }); + const root = wfEdSlug(base); + if (!taken[root]) return root; + for (let i = 2; ; i++) { const cand = root + '-' + i; if (!taken[cand]) return cand; } + } + + function wfEdNewModel(name) { + return { + apiVersion: WF_ED_API_VERSION, kind: 'WorkflowModel', + metadata: { name: wfEdSlug(name || 'my-lifecycle') }, + spec: { + meta: { version: '1', provenance: 'local', source: 'hand', description: '' }, + scope: { forge: 'github.com', repository: '*' }, + initial: 'open', + columns: [{ id: 'intake', label: 'Intake', states: ['open'] }], + states: [{ id: 'open', label: 'Open', owner: 'human', lifecycle: { column: 'intake', number: 10 } }], + transitions: [], + derivation: { mode: 'builtin' }, + labels: { prefix: 'stage/' }, + }, + }; + } + + // wfEdNormalize makes the two column/state links agree: every column's + // states list is rebuilt from membership plus lifecycle.column fallbacks, + // and each state's lifecycle.column names the lane it sits in. + function wfEdNormalize(model) { + const m = wfEdClone(model) || {}; + m.spec = m.spec || {}; + const spec = m.spec; + spec.columns = Array.isArray(spec.columns) ? spec.columns : []; + spec.states = Array.isArray(spec.states) ? spec.states : []; + spec.transitions = Array.isArray(spec.transitions) ? spec.transitions : []; + const states = wfEdStates(m); + const known = {}; states.forEach(s => { known[s.id] = s; }); + const placed = {}; + spec.columns.forEach(c => { + c.states = (Array.isArray(c.states) ? c.states : []).filter(id => known[id] && !placed[id]); + c.states.forEach(id => { placed[id] = c.id; }); + }); + states.forEach(s => { + if (placed[s.id]) { s.lifecycle = Object.assign({}, s.lifecycle, { column: placed[s.id] }); return; } + const want = s.lifecycle && s.lifecycle.column; + const col = want && spec.columns.find(c => c.id === want); + if (col) { col.states.push(s.id); placed[s.id] = col.id; } + else if (s.lifecycle && s.lifecycle.column) { s.lifecycle = Object.assign({}, s.lifecycle); delete s.lifecycle.column; } + }); + return m; + } + + function wfEdAddColumn(model, col, index) { + const m = wfEdNormalize(model); + const c = Object.assign({ label: '' }, col || {}); + c.id = wfEdUniqueId(m, c.id || c.label || 'column'); + if (!c.label) c.label = c.id; + c.states = []; + if (!c.terminal) delete c.terminal; + if (!c.hint) delete c.hint; + const at = (index === undefined || index === null || index < 0 || index > m.spec.columns.length) ? m.spec.columns.length : index; + m.spec.columns.splice(at, 0, c); + return m; + } + + function wfEdMoveColumn(model, id, toIndex) { + const m = wfEdNormalize(model); + const from = m.spec.columns.findIndex(c => c.id === id); + if (from < 0) return m; + const col = m.spec.columns.splice(from, 1)[0]; + const to = Math.max(0, Math.min(toIndex, m.spec.columns.length)); + m.spec.columns.splice(to, 0, col); + return m; + } + + function wfEdRenameColumn(model, oldId, newId) { + const m = wfEdNormalize(model); + const id = wfEdSlug(newId); + if (!id || id === oldId) return m; + if (m.spec.columns.some(c => c.id === id) || wfEdStates(m).some(s => s.id === id)) return m; + m.spec.columns.forEach(c => { if (c.id === oldId) c.id = id; }); + wfEdStates(m).forEach(s => { if (s.lifecycle && s.lifecycle.column === oldId) s.lifecycle.column = id; }); + return m; + } + + // wfEdRemoveColumn drops a lane. Its states move to moveStatesTo when + // given, otherwise they become unassigned (drawn in the trailing lane). + function wfEdRemoveColumn(model, id, moveStatesTo) { + const m = wfEdNormalize(model); + const idx = m.spec.columns.findIndex(c => c.id === id); + if (idx < 0) return m; + const gone = m.spec.columns.splice(idx, 1)[0]; + const target = moveStatesTo && moveStatesTo !== id ? m.spec.columns.find(c => c.id === moveStatesTo) : null; + (gone.states || []).forEach(sid => { + const s = wfEdFindState(m, sid); + if (target) { target.states.push(sid); if (s) s.lifecycle = Object.assign({}, s.lifecycle, { column: target.id }); } + else if (s && s.lifecycle) { delete s.lifecycle.column; } + }); + return m; + } + + function wfEdAddState(model, state, columnId, index) { + const m = wfEdNormalize(model); + const s = Object.assign({ label: '', owner: 'human' }, state || {}); + s.id = wfEdUniqueId(m, s.id || s.label || 'state'); + if (!s.label) s.label = s.id; + if (!s.owner) s.owner = 'human'; + s.lifecycle = Object.assign({}, s.lifecycle || {}); + const col = columnId ? m.spec.columns.find(c => c.id === columnId) : null; + if (col) { + s.lifecycle.column = col.id; + const at = (index === undefined || index === null || index < 0 || index > col.states.length) ? col.states.length : index; + col.states.splice(at, 0, s.id); + } else { + delete s.lifecycle.column; + } + m.spec.states.push(s); + if (!m.spec.initial) m.spec.initial = s.id; + return m; + } + + // wfEdMoveState puts a state into a lane at a position (columnId '' or + // unknown → unassigned). Moving within the same lane re-orders it. + function wfEdMoveState(model, id, columnId, index) { + const m = wfEdNormalize(model); + const s = wfEdFindState(m, id); + if (!s) return m; + m.spec.columns.forEach(c => { c.states = c.states.filter(x => x !== id); }); + const col = columnId && columnId !== WF_ED_UNASSIGNED ? m.spec.columns.find(c => c.id === columnId) : null; + s.lifecycle = Object.assign({}, s.lifecycle || {}); + if (col) { + const at = (index === undefined || index === null || index < 0 || index > col.states.length) ? col.states.length : index; + col.states.splice(at, 0, id); + s.lifecycle.column = col.id; + } else { + delete s.lifecycle.column; + } + return m; + } + + // wfEdRenameState changes an id and every reference to it: column + // membership, transitions, initial, label entries, derivation rules, + // lanes and agent grants. + function wfEdRenameState(model, oldId, newId) { + const m = wfEdNormalize(model); + const id = wfEdSlug(newId); + if (!id || id === oldId || !wfEdFindState(m, oldId)) return m; + if (wfEdFindState(m, id) || m.spec.columns.some(c => c.id === id)) return m; + const spec = m.spec; + wfEdStates(m).forEach(s => { if (s.id === oldId) s.id = id; }); + spec.columns.forEach(c => { c.states = c.states.map(x => x === oldId ? id : x); }); + spec.transitions.forEach(t => { if (t.from === oldId) t.from = id; if (t.to === oldId) t.to = id; }); + if (spec.initial === oldId) spec.initial = id; + ((spec.labels && spec.labels.entries) || []).forEach(l => { if (l.state === oldId) l.state = id; }); + ((spec.derivation && spec.derivation.rules) || []).forEach(r => { if (r.state === oldId) r.state = id; }); + (spec.lanes || []).forEach(l => { if (l.stateRef === oldId) l.stateRef = id; }); + (spec.agents || []).forEach(a => { if (Array.isArray(a.states)) a.states = a.states.map(x => x === oldId ? id : x); }); + return m; + } + + function wfEdRemoveState(model, id) { + const m = wfEdNormalize(model); + const spec = m.spec; + (function prune(list) { + for (let i = list.length - 1; i >= 0; i--) { + if (list[i].id === id) list.splice(i, 1); + else if (Array.isArray(list[i].regions)) prune(list[i].regions); + } + })(spec.states); + spec.columns.forEach(c => { c.states = c.states.filter(x => x !== id); }); + spec.transitions = spec.transitions.filter(t => t.from !== id && t.to !== id); + if (spec.labels && Array.isArray(spec.labels.entries)) spec.labels.entries = spec.labels.entries.filter(l => l.state !== id); + if (spec.derivation && Array.isArray(spec.derivation.rules)) spec.derivation.rules = spec.derivation.rules.filter(r => r.state !== id); + if (spec.initial === id) { const rest = wfEdStates(m); spec.initial = rest.length ? rest[0].id : ''; } + return m; + } + + function wfEdAddTransition(model, from, to, on) { + const m = wfEdNormalize(model); + if (!wfEdFindState(m, from) || !wfEdFindState(m, to)) return m; + const ev = on == null ? '' : String(on); + if (m.spec.transitions.some(t => t.from === from && t.to === to && (t.on || '') === ev)) return m; + m.spec.transitions.push({ from: from, to: to, on: ev }); + return m; + } + + function wfEdRemoveTransition(model, index) { + const m = wfEdNormalize(model); + if (index >= 0 && index < m.spec.transitions.length) m.spec.transitions.splice(index, 1); + return m; + } + + // wfEdPath splits "spec.states[id=open].lifecycle.number" or + // "spec.transitions[2].on" into segments; [k=v] selects an array item by + // field, [n] by index. + function wfEdPath(path) { + const out = []; + String(path || '').split('.').forEach(part => { + const re = /([^[\]]+)|\[([^\]]+)\]/g; + let mt; + while ((mt = re.exec(part)) !== null) { + if (mt[1] !== undefined) out.push({ key: mt[1] }); + else if (mt[2].indexOf('=') > 0) { const kv = mt[2].split('='); out.push({ field: kv[0], value: kv.slice(1).join('=') }); } + else out.push({ index: parseInt(mt[2], 10) }); + } + }); + return out; + } + + // wfEdUpdate sets one field by path and returns a new model. Empty + // string / null / undefined deletes optional scalars so the saved JSON + // stays tidy. Fields that re-link structure (state column, ids) have + // their own functions; this one never touches links. + function wfEdUpdate(model, path, value) { + const m = wfEdClone(model); + const segs = wfEdPath(path); + if (!segs.length) return m; + let cur = m; + for (let i = 0; i < segs.length - 1; i++) { + const s = segs[i]; + let next; + if (s.key !== undefined) { if (cur[s.key] === undefined || cur[s.key] === null) cur[s.key] = (segs[i + 1].key !== undefined) ? {} : []; next = cur[s.key]; } + else if (s.index !== undefined) { next = cur[s.index]; } + else { next = Array.isArray(cur) ? cur.find(x => x && String(x[s.field]) === s.value) : undefined; } + if (next === undefined || next === null) return m; + cur = next; + } + const last = segs[segs.length - 1]; + const remove = value === undefined || value === null || value === '' || (Array.isArray(value) && !value.length); + if (last.key !== undefined) { if (remove) delete cur[last.key]; else cur[last.key] = value; } + else if (last.index !== undefined) { if (remove) cur.splice(last.index, 1); else cur[last.index] = value; } + return m; + } + + // wfEdDepths is the BFS distance of every state from the initial state + // along transitions; unreachable states get Infinity. + function wfEdDepths(model) { + const spec = wfEdSpec(model); + const depth = {}; + wfEdStates(model).forEach(s => { depth[s.id] = Infinity; }); + const start = spec.initial && depth[spec.initial] !== undefined ? spec.initial : (wfEdStates(model)[0] || {}).id; + if (!start) return depth; + depth[start] = 0; + const queue = [start]; + while (queue.length) { + const cur = queue.shift(); + (spec.transitions || []).forEach(t => { + if (t.from === cur && depth[t.to] !== undefined && depth[t.to] === Infinity) { depth[t.to] = depth[cur] + 1; queue.push(t.to); } + }); + } + return depth; + } + + // wfEdAutoLayout orders columns by the depth of their states from the + // initial state (terminal lanes last), places unassigned states by + // depth into the nearest lane, and sorts each lane by stage number then + // label. Pure: returns a new model. + function wfEdAutoLayout(model) { + const m = wfEdNormalize(model); + const depth = wfEdDepths(m); + const states = wfEdStates(m); + const byId = {}; states.forEach(s => { byId[s.id] = s; }); + const cols = m.spec.columns; + if (!cols.length) return m; + const colDepth = cols.map((c, i) => { + const ds = c.states.map(id => depth[id]).filter(d => isFinite(d)); + return { col: c, i: i, d: ds.length ? Math.min.apply(null, ds) : Infinity }; + }); + colDepth.sort((a, b) => { + if (!!a.col.terminal !== !!b.col.terminal) return a.col.terminal ? 1 : -1; + if (a.d !== b.d) return (isFinite(a.d) ? a.d : 1e9) - (isFinite(b.d) ? b.d : 1e9); + return a.i - b.i; + }); + m.spec.columns = colDepth.map(x => x.col); + // Unassigned states join the lane whose depth is closest. + const placed = {}; m.spec.columns.forEach(c => c.states.forEach(id => { placed[id] = true; })); + states.forEach(s => { + if (placed[s.id]) return; + const d = depth[s.id]; + let best = null, bestGap = Infinity; + colDepth.forEach(x => { const gap = Math.abs((isFinite(x.d) ? x.d : 1e9) - (isFinite(d) ? d : 1e9)); if (gap < bestGap) { bestGap = gap; best = x.col; } }); + if (!best) best = m.spec.columns[m.spec.columns.length - 1]; + best.states.push(s.id); + s.lifecycle = Object.assign({}, s.lifecycle, { column: best.id }); + }); + m.spec.columns.forEach(c => { + c.states.sort((a, b) => { + const na = (byId[a].lifecycle || {}).number || 0, nb = (byId[b].lifecycle || {}).number || 0; + if (na !== nb) return (na || 1e9) - (nb || 1e9); + const da = depth[a], db = depth[b]; + if (da !== db) return (isFinite(da) ? da : 1e9) - (isFinite(db) ? db : 1e9); + return String(byId[a].label || a).localeCompare(String(byId[b].label || b)); + }); + }); + return m; + } + + function wfEdSnap(v) { return Math.round(v / WF_ED.grid) * WF_ED.grid; } + + // wfEdLayout computes lane and chip geometry in model space (before + // pan/zoom). view.laneWidths may override a lane's width by id. States + // not in any lane are drawn in a trailing dashed "unassigned" lane. + function wfEdLayout(model, profile, view) { + const D = WF_ED; + const spec = wfEdSpec(model); + const widths = (view && view.laneWidths) || {}; + const states = wfEdStates(model); + const byId = {}; states.forEach(s => { byId[s.id] = s; }); + const lanes = (spec.columns || []).map(c => ({ id: c.id, label: c.label || c.id, hint: c.hint || '', terminal: !!c.terminal, states: (c.states || []).filter(id => byId[id]), virtual: false })); + const placed = {}; lanes.forEach(l => l.states.forEach(id => { placed[id] = true; })); + const loose = states.filter(s => !placed[s.id]).map(s => s.id); + if (loose.length || !lanes.length) lanes.push({ id: WF_ED_UNASSIGNED, label: 'Unassigned', hint: 'drag states into a lane', terminal: false, states: loose, virtual: true }); + let maxRows = D.minRows; + lanes.forEach(l => { maxRows = Math.max(maxRows, l.states.length + 1); }); + const laneH = D.headH + maxRows * (D.chipH + D.chipGap) + D.chipGap; + const laneIndex = {}; lanes.forEach((l, ci) => l.states.forEach(id => { laneIndex[id] = ci; })); + const channels = wfEdgeChannels(spec.transitions || [], id => (laneIndex[id] == null ? null : laneIndex[id])); + const topCorr = wfEdgeCorridor(channels.top), bottomCorr = wfEdgeCorridor(channels.bottom); + const laneY = D.pad + topCorr; + let x = D.pad; + const cols = [], chips = {}; + lanes.forEach((l, ci) => { + const w = Math.max(D.minColW, Math.min(D.maxColW, wfEdSnap(widths[l.id] || D.colW))); + cols.push({ id: l.id, label: l.label, hint: l.hint, terminal: l.terminal, virtual: l.virtual, index: ci, x: x, y: laneY, w: w, h: laneH }); + l.states.forEach((id, ri) => { + chips[id] = { id: id, col: l.id, colIndex: ci, index: ri, x: x + D.grid, y: laneY + D.headH + D.chipGap + ri * (D.chipH + D.chipGap), w: w - D.grid * 2, h: D.chipH }; + }); + x += w + D.colGap; + }); + const width = x - D.colGap + D.pad, height = D.pad * 2 + topCorr + laneH + bottomCorr; + const routed = wfRouteEdges(spec.transitions || [], { cols: cols, chips: chips, gap: D.colGap, pad: D.pad }, { expanded: (view && view.fansOpen) || {} }); + const edges = routed.edges, fans = routed.fans; + return { width: width, height: height, cols: cols, chips: chips, edges: edges, fans: fans, commonEvent: routed.common, laneH: laneH }; + } + + // wfEdLaneAt / wfEdSlotAt map a model-space point onto a lane and a chip + // slot index, for drops. + function wfEdLaneAt(layout, x) { + for (const c of layout.cols) { if (x >= c.x - WF_ED.colGap / 2 && x < c.x + c.w + WF_ED.colGap / 2) return c; } + return null; + } + function wfEdSlotAt(layout, lane, y) { + const top = lane.y + WF_ED.headH + WF_ED.chipGap; + const n = Object.keys(layout.chips).filter(id => layout.chips[id].col === lane.id).length; + return Math.max(0, Math.min(n, Math.round((y - top) / (WF_ED.chipH + WF_ED.chipGap)))); + } + + // wfEdLocalProblems mirrors the compiler's refusals so the canvas can + // flag them before the server answers. Codes match workflowmodel. + function wfEdLocalProblems(model) { + const spec = wfEdSpec(model); + const out = []; + const push = (code, severity, subject, detail) => out.push({ code: code, severity: severity, subject: subject, detail: detail }); + const states = wfEdStates(model); + const byId = {}; states.forEach(s => { byId[s.id] = s; }); + const cols = spec.columns || []; + const colById = {}; cols.forEach(c => { colById[c.id] = c; }); + if (!(model && model.metadata && model.metadata.name)) push('invalid', 'error', '', 'metadata.name is required'); + if (!states.length) push('invalid', 'error', '', 'the model has no states'); + if (!spec.initial) push('invalid', 'error', '', 'spec.initial is empty'); + else if (!byId[spec.initial]) push('unknown-state', 'error', spec.initial, 'spec.initial names a state that does not exist'); + const seenIds = {}; + states.forEach(s => { if (seenIds[s.id]) push('invalid', 'error', s.id, 'duplicate state id'); seenIds[s.id] = true; }); + const terminalStates = {}; + cols.forEach(c => { if (c.terminal) (c.states || []).forEach(id => { terminalStates[id] = true; }); }); + const hasExit = {}; + (spec.transitions || []).forEach((t, i) => { + const subj = t.from + '->' + t.to; + if (!byId[t.from]) push('unknown-state', 'error', subj, 'transition from unknown state ' + t.from); + if (!byId[t.to]) push('unknown-state', 'error', subj, 'transition to unknown state ' + t.to); + if (t.from !== t.to) hasExit[t.from] = true; + if (Array.isArray(spec.events) && spec.events.length && t.on && !spec.events.some(e => e.id === t.on)) push('unknown-event', 'error', subj, 'event ' + t.on + ' is not declared in spec.events'); + }); + const memberOf = {}; + cols.forEach(c => { + if (!(c.states || []).length) push('column-empty', 'warning', c.id, 'column has no states'); + (c.states || []).forEach(id => { + if (!byId[id]) push('unknown-state', 'error', c.id, 'column lists unknown state ' + id); + if (memberOf[id]) push('state-no-column', 'error', id, 'state is listed in both ' + memberOf[id] + ' and ' + c.id); + memberOf[id] = c.id; + }); + }); + if (cols.length && !cols.some(c => c.terminal)) push('no-terminal-column', 'error', '', 'no column is marked terminal'); + const numbers = {}; + states.forEach(s => { + const lc = s.lifecycle || {}; + if (!s.owner) push('invalid', 'error', s.id, 'state has no owner'); + if (s.type === 'parallel' && !(Array.isArray(s.regions) && s.regions.length)) push('invalid', 'error', s.id, 'parallel state has no regions'); + if (cols.length && !memberOf[s.id]) push('state-no-column', 'error', s.id, 'state is not in any column'); + if (lc.column && !colById[lc.column]) push('unknown-column', 'error', s.id, 'lifecycle.column names unknown column ' + lc.column); + if (lc.column && memberOf[s.id] && lc.column !== memberOf[s.id]) push('state-no-column', 'error', s.id, 'lifecycle.column is ' + lc.column + ' but the state sits in ' + memberOf[s.id]); + if (!terminalStates[s.id] && s.type !== 'final' && s.type !== 'parallel' && !hasExit[s.id]) push('state-no-exit', 'error', s.id, 'non-terminal state has no outgoing transition'); + if (lc.number) { + const kinds = Array.isArray(lc.kinds) && lc.kinds.length ? lc.kinds : WF_ED_KINDS; + kinds.forEach(k => { + const key = k + ':' + lc.number; + if (numbers[key] && numbers[key] !== s.id) push('duplicate-stage-number', 'error', s.id, 'stage ' + lc.number + ' for ' + k + ' is also used by ' + numbers[key]); + numbers[key] = s.id; + }); + } + if (lc.confidence === 'inferred') push('inferred-element', 'warning', s.id, 'state was inferred and not confirmed'); + }); + return out; + } + + // wfEdDiff is the client-side twin of workflowmodel.Diff for the unsaved + // working copy: same keyed collections and the same flat field changes. + function wfEdDiff(a, b) { + const flat = v => v === undefined || v === null ? '' : (Array.isArray(v) ? v.map(x => typeof x === 'object' ? JSON.stringify(x) : String(x)).join(',') : (typeof v === 'object' ? JSON.stringify(v) : String(v))); + const diffItems = (ia, ib) => { + const out = { added: [], removed: [], changed: [] }; + Object.keys(ib).forEach(k => { if (!(k in ia)) out.added.push(k); }); + Object.keys(ia).forEach(k => { if (!(k in ib)) out.removed.push(k); }); + Object.keys(ia).forEach(k => { + if (!(k in ib)) return; + const fields = []; + const keys = {}; Object.keys(ia[k]).concat(Object.keys(ib[k])).forEach(f => { keys[f] = true; }); + Object.keys(keys).sort().forEach(f => { const fa = flat(ia[k][f]), fb = flat(ib[k][f]); if (fa !== fb) fields.push({ field: f, from: fa, to: fb }); }); + if (fields.length) out.changed.push({ key: k, fields: fields }); + }); + out.added.sort(); out.removed.sort(); out.changed.sort((x, y) => x.key.localeCompare(y.key)); + return out; + }; + const strip = (o, drop) => { const c = Object.assign({}, o); drop.forEach(k => { delete c[k]; }); return c; }; + const colItems = m => { const o = {}; (wfEdSpec(m).columns || []).forEach(c => { o[c.id] = strip(c, ['id']); }); return o; }; + const stateItems = m => { const o = {}; wfEdStates(m).forEach(s => { const c = strip(s, ['id', 'regions', 'lifecycle']); Object.keys(s.lifecycle || {}).forEach(k => { c['lifecycle.' + k] = s.lifecycle[k]; }); o[s.id] = c; }); return o; }; + const transItems = m => { + const o = {}, count = {}; + (wfEdSpec(m).transitions || []).forEach(t => { const k = t.from + '>' + t.to; count[k] = (count[k] || 0) + 1; }); + (wfEdSpec(m).transitions || []).forEach(t => { const k = t.from + '>' + t.to; o[count[k] > 1 ? k + '@' + (t.on || '') : k] = strip(t, ['from', 'to']); }); + return o; + }; + const labelItems = m => { const o = {}; ((wfEdSpec(m).labels || {}).entries || []).forEach(l => { o[l.name] = strip(l, ['name']); }); return o; }; + const ruleItems = m => { const o = {}; ((wfEdSpec(m).derivation || {}).rules || []).forEach((r, i) => { o[r.id || 'rules[' + i + ']'] = strip(r, ['id']); }); return o; }; + const d = { + columns: diffItems(colItems(a), colItems(b)), + states: diffItems(stateItems(a), stateItems(b)), + transitions: diffItems(transItems(a), transItems(b)), + labels: diffItems(labelItems(a), labelItems(b)), + rules: diffItems(ruleItems(a), ruleItems(b)), + meta: [], + }; + const ma = wfEdSpec(a).meta || {}, mb = wfEdSpec(b).meta || {}; + const mkeys = {}; Object.keys(ma).concat(Object.keys(mb)).forEach(k => { mkeys[k] = true; }); + Object.keys(mkeys).sort().forEach(k => { if (flat(ma[k]) !== flat(mb[k])) d.meta.push({ field: k, from: flat(ma[k]), to: flat(mb[k]) }); }); + const parts = []; + let changed = d.meta.length; + ['columns', 'states', 'transitions', 'labels', 'rules'].forEach(k => { + const cs = d[k]; + if (cs.added.length) parts.push('+' + cs.added.length + ' ' + k); + if (cs.removed.length) parts.push('\u2212' + cs.removed.length + ' ' + k); + changed += cs.changed.length; + }); + if (changed) parts.push(changed + ' changed'); + d.empty = !parts.length; + d.summary = d.empty ? 'no changes' : parts.join(', '); + return d; + } + + // wfEdSvg renders the canvas. `state` carries selection, diagnostics by + // subject, a simulate hit, profile and the view transform. Pure. + function wfEdSvg(model, layout, state) { + const st = state || {}; + const D = WF_ED; + const spec = wfEdSpec(model); + const view = st.view || { panX: 0, panY: 0, zoom: 1 }; + const sel = st.selection || { type: '', ids: [] }; + const isSel = (type, id) => sel.type === type && sel.ids.indexOf(id) >= 0; + const diags = {}; + (st.diags || []).forEach(d => { const k = d.subject || ''; if (!diags[k] || d.severity === 'error') diags[k] = Object.assign({}, diags[k] || {}, { severity: diags[k] && diags[k].severity === 'error' ? 'error' : d.severity, text: ((diags[k] && diags[k].text) ? diags[k].text + '\n' : '') + d.code + ': ' + d.detail }); }); + const states = {}; wfEdStates(model).forEach(s => { states[s.id] = s; }); + const profile = st.profile || null; + const out = []; + const vw = st.viewportW || layout.width, vh = st.viewportH || layout.height; + out.push(`'); + return out.join(''); + } + + // wfEdMinimapSvg draws lanes and chips as small rectangles with the + // viewport outlined. Pure. + function wfEdMinimapSvg(layout, view, viewportW, viewportH) { + const W = 160, H = Math.max(40, Math.round(W * layout.height / Math.max(1, layout.width))); + const k = Math.min(W / Math.max(1, layout.width), H / Math.max(1, layout.height)); + const out = [`'); + return out.join(''); + } + + // wfEdFitView returns a view that fits the layout into a viewport. + function wfEdFitView(layout, viewportW, viewportH) { + const zoom = Math.max(0.2, Math.min(2, Math.min(viewportW / Math.max(1, layout.width), viewportH / Math.max(1, layout.height)))); + return { zoom: zoom, panX: Math.max(0, (viewportW - layout.width * zoom) / 2), panY: Math.max(0, (viewportH - layout.height * zoom) / 2) }; + } + + // wfEdCompileModel is the model as sent to compile/simulate: a draft + // version stands in for the empty one the editor saves with. + function wfEdCompileModel(model) { + const m = wfEdClone(model); + m.spec = m.spec || {}; + m.spec.meta = Object.assign({}, m.spec.meta); + if (!m.spec.meta.version) m.spec.meta.version = 'draft'; + return m; + } + + // wfEdSelectedProblem picks the compile status pill text from diagnostics. + function wfEdStatus(diags, busy, compiledFlag) { + const list = Array.isArray(diags) ? diags : []; + const errors = list.filter(d => d.severity === 'error').length; + const warnings = list.filter(d => d.severity !== 'error').length; + if (errors || compiledFlag === false) return { cls: 'error', text: 'does not compile' + (errors ? ' \u00b7 ' + errors + ' error' + (errors === 1 ? '' : 's') : ''), errors: errors, warnings: warnings, busy: !!busy }; + if (warnings) return { cls: 'warn', text: warnings + ' warning' + (warnings === 1 ? '' : 's'), errors: 0, warnings: warnings, busy: !!busy }; + return { cls: 'ok', text: 'compiles', errors: 0, warnings: 0, busy: !!busy }; + } + + // --- Runtime state -------------------------------------------------------- + + function wfEdDefaultState() { + return { + model: null, saved: null, source: null, readOnly: false, rev: 0, + history: [], future: [], selection: { type: '', ids: [] }, + view: { panX: 0, panY: 0, zoom: 1, laneWidths: {}, showLabels: false, fansOpen: {} }, + compile: { busy: false, rev: -1, profile: null, diags: [], compiled: null, error: '' }, + drawer: { tab: 'problems', open: true }, + yaml: { text: '', rev: -1, error: '', busy: false, focused: false }, + diff: { versions: [], against: '', remote: null, error: '', busy: false, loadedFor: '' }, + sim: { kind: 'pr', facts: wfSimDefaultFacts(), result: null, error: '', busy: false, hit: '' }, + palette: { hiveDefault: null, loading: false, section: 'states' }, + exportMenu: false, spaceHeld: false, viewport: { w: 900, h: 520 }, timers: {}, drag: null, marquee: null, pendingEdge: null, dropLane: '', + }; + } + const _wfEd = wfEdDefaultState(); + + function wfEdOwner() { return dashboardRoleAtLeast(window._hiveRole || 'read', 'owner'); } + function wfEdDirty() { return !!_wfEd.model && JSON.stringify(_wfEd.model) !== JSON.stringify(_wfEd.saved); } + function wfEdCanEdit() { return !!_wfEd.model && !_wfEd.readOnly && wfEdOwner(); } + + // wfEdDiags is what the canvas and Problems drawer show: the server's + // diagnostics when they are for the current revision, local ones until. + function wfEdDiags() { + if (!_wfEd.model) return []; + if (_wfEd.compile.rev === _wfEd.rev && !_wfEd.compile.error) return _wfEd.compile.diags || []; + return wfEdLocalProblems(_wfEd.model); + } + + function wfEdLoad(model, source, readOnly) { + const m = wfEdNormalize(model); + Object.assign(_wfEd, wfEdDefaultState(), { model: m, saved: wfEdClone(m), source: source || null, readOnly: !!readOnly, palette: _wfEd.palette }); + _wfEd.rev = 1; + _wfLib.view = 'editor'; + wfEdScheduleCompile(0); + wfLibRerender(); + } + + function wfEdCommit(next, opts) { + if (!_wfEd.model) return; + if (!wfEdCanEdit()) { showToast(_wfEd.readOnly ? 'This model is read-only. Use "Edit a copy".' : 'Owner role is required to edit.', 'error'); return; } + const o = opts || {}; + _wfEd.history.push(wfEdClone(_wfEd.model)); + _wfEd.history = _wfEd.history.slice(-WF_ED_HISTORY_CAP); + _wfEd.future = []; + _wfEd.model = wfEdNormalize(next); + _wfEd.rev++; + _wfEd.sim.hit = ''; + wfEdScheduleCompile(); + wfEdRefresh(o.parts || ['toolbar', 'canvas', 'inspector', 'drawer']); + } + + function wfEdUndo() { + if (!_wfEd.history.length) return; + _wfEd.future.push(wfEdClone(_wfEd.model)); + _wfEd.future = _wfEd.future.slice(-WF_ED_HISTORY_CAP); + _wfEd.model = _wfEd.history.pop(); + _wfEd.rev++; wfEdPruneSelection(); wfEdScheduleCompile(); wfEdRefresh(); + } + function wfEdRedo() { + if (!_wfEd.future.length) return; + _wfEd.history.push(wfEdClone(_wfEd.model)); + _wfEd.history = _wfEd.history.slice(-WF_ED_HISTORY_CAP); + _wfEd.model = _wfEd.future.pop(); + _wfEd.rev++; wfEdPruneSelection(); wfEdScheduleCompile(); wfEdRefresh(); + } + + function wfEdPruneSelection() { + const sel = _wfEd.selection; + if (sel.type === 'state') sel.ids = sel.ids.filter(id => wfEdFindState(_wfEd.model, id)); + else if (sel.type === 'column') sel.ids = sel.ids.filter(id => wfEdFindColumn(_wfEd.model, id)); + else if (sel.type === 'transition') sel.ids = sel.ids.filter(i => _wfEd.model.spec.transitions[parseInt(i, 10)]); + if (!sel.ids.length) { sel.type = ''; } + } + + function wfEdSelect(type, id, additive) { + const sel = _wfEd.selection; + if (!type) { sel.type = ''; sel.ids = []; } + else if (additive && sel.type === type) { const i = sel.ids.indexOf(id); if (i >= 0) sel.ids.splice(i, 1); else sel.ids.push(id); if (!sel.ids.length) sel.type = ''; } + else { sel.type = type; sel.ids = [id]; } + wfEdRefresh(['canvas', 'inspector']); + } + + // --- Live compile --------------------------------------------------------- + + function wfEdScheduleCompile(delay) { + clearTimeout(_wfEd.timers.compile); + _wfEd.timers.compile = setTimeout(wfEdCompileNow, delay === undefined ? WF_ED_COMPILE_DEBOUNCE_MS : delay); + } + + async function wfEdCompileNow() { + if (!_wfEd.model) return; + const rev = _wfEd.rev, c = _wfEd.compile; + c.busy = true; wfEdRefresh(['toolbar']); + try { + const res = await fetch('/api/workflows/compile', { method: 'POST', headers: _inceptionAuthHeaders(), body: JSON.stringify(wfEdCompileModel(_wfEd.model)) }); + if (!res.ok) throw new Error(await saveErrorMessage(res)); + const data = await res.json(); + if (rev !== _wfEd.rev) return; + c.profile = data.profile || null; c.diags = Array.isArray(data.diagnostics) ? data.diagnostics : []; c.compiled = !!data.compiled; c.error = ''; c.rev = rev; + } catch (err) { + if (rev !== _wfEd.rev) return; + c.error = err.message; c.rev = rev; + } finally { + if (rev === _wfEd.rev) { c.busy = false; wfEdRefresh(['toolbar', 'canvas', 'drawer']); } + } + } + + // --- Render --------------------------------------------------------------- + + function renderWorkflowEditor(owner) { + if (!_wfEd.model) return renderWorkflowEditorStart(owner); + return '
Design a lifecycle on a canvas: columns are lanes, states are chips, transitions are drawn by dragging from a chip\u2019s port. The model compiles live as you edit; the YAML, Diff and Simulate drawers work on the unsaved copy.
' + + (owner ? '' : 'Owner role is required to edit or save; you can still open models to look at them.
') + + 'No stored models yet.
') + + 'No numbered stages.
') : (st.palette.loading ? 'Loading\u2026
' : '')], + ]; + return '${sel.ids.map(id => `${esc(id)}`).join(', ')}
` + + ``; + } else if (sel.type === 'state') { + const s = wfEdFindState(m, sel.ids[0]); + if (!s) return 'Nothing selected.
'; + const lc = s.lifecycle || {}, base = 'spec.states[id=' + s.id + ']'; + const cols = [[WF_ED_UNASSIGNED, '\u2014 unassigned']].concat(spec.columns.map(c => [c.id, c.label || c.id])); + const dupNumber = lc.number && wfEdStates(m).some(o => o.id !== s.id && (o.lifecycle || {}).number === lc.number); + body = `Nothing selected.
'; + const base = 'spec.transitions[' + i + ']'; + body = `Nothing selected.
'; + const base = 'spec.columns[id=' + c.id + ']'; + const others = spec.columns.filter(o => o.id !== c.id); + body = `${(c.states || []).length} state${(c.states || []).length === 1 ? '' : 's'}
` + + 'Deleting asks where to move its states.
' : ''); + } else { + const meta = spec.meta || {}, lab = spec.labels || {}; + const states = wfEdStates(m); + body = '${spec.columns.length} column${spec.columns.length === 1 ? '' : 's'} \u00b7 ${states.length} state${states.length === 1 ? '' : 's'} \u00b7 ${spec.transitions.length} transition${spec.transitions.length === 1 ? '' : 's'}
`; + } + return body; + } + + function wfEdProblemsHtml(diags) { + const list = Array.isArray(diags) ? diags : []; + if (!list.length) return 'No problems: the model compiles clean.
'; + return '${esc(d.summary || '')}
` + + wfEdChangeSetHtml('Columns', d.columns) + wfEdChangeSetHtml('States', d.states) + wfEdChangeSetHtml('Transitions', d.transitions) + wfEdChangeSetHtml('Labels', d.labels) + wfEdChangeSetHtml('Rules', d.rules) + + ((d.meta || []).length ? 'Compile request failed: ${esc(st.compile.error)}
` : '') + + (st.compile.rev !== st.rev ? 'Showing local checks until the server answers\u2026
' : '') + wfEdProblemsHtml(wfEdDiags()); + } else if (tab === 'yaml') { + body = `` + + (st.yaml.error ? `${esc(st.yaml.error)}
` : '') + + ``; + } else if (tab === 'diff') { + const local = wfEdDiff(st.saved || {}, st.model); + const versions = st.diff.versions || []; + const opts = [['', '\u2014 saved version \u2014']].concat(versions.map(v => [v.version, v.version + (v.savedAt && v.savedAt !== '0001-01-01T00:00:00Z' ? ' \u00b7 ' + formatDashboardDateTime(v.savedAt) : '')])); + body = 'No unsaved changes.
' : wfEdDiffHtml(local)) + + (st.source ? 'Loading\u2026
' : '') + (st.diff.error ? `${esc(st.diff.error)}
` : '') + + (st.diff.remote ? wfEdDiffHtml(st.diff.remote) : '') : 'Save the model to compare stored versions.
'); + } else if (tab === 'simulate') { + const sim = st.sim; + const dis = sim.busy ? 'disabled' : ''; + const kinds = WF_ED_KINDS.map(k => ``).join(''); + body = `${esc(sim.error)}
` : '') + + (sim.result ? renderWorkflowSimulateResult(sim.result) : ''); + } + return '