---
title: "Workflow Studio"
description: "Application scaffold: an n8n- and ComfyUI-style workflow studio with six apps you can run - an AI agent crew with prompts and external data, a route planner that calls its traffic service twice, a three.js scene graph with shader and animation subworkflows, an order-to-cash process that hands schemaful objects from step to step, a hand-built neural network of 973 weights and biases that computes A + B, A - B, A × B and A ÷ B, and the complete form logic of the BDI-II questionnaire; built only from the shipped components."
slug: "scaffold-workflow-studio"
---

import { DocPage, PageHeader, DocText, DocLink } from "../../lib/components/index";

<DocPage meta={meta}>

<PageHeader slug="scaffold-workflow-studio" title="Workflow Studio" introStyle="max-width:44rem;">
  A workflow studio as a clickdummy - "Loom" for a team that wires its automations as graphs, the way n8n and ComfyUI do. Six apps are drawn as workflows you can change and run: an <strong>AI agent crew</strong> that answers a customer from prompts and two data sources, a <strong>route planner</strong> that asks its traffic service twice, a <strong>3D scene</strong> built in three.js from a scene graph with shader and animation subworkflows, an <strong>order-to-cash process</strong> that hands typed business objects from step to step, and a <strong>neural network</strong> whose 973 weights and biases were written by hand to compute A + B, A − B, A × B and A ÷ B for A and B from 0 to 100, and the <strong>BDI-II form logic</strong> - all 21 items with their options and every scoring rule. The tree on the left finds any node; Follow flies the editor to it. Part of the <DocLink href="application-scaffolds.html">Application Scaffolds</DocLink>.
</PageHeader>

<div class="flex flex-wrap items-center gap-2 mb-6">
  <a class="btn" href="app-workflow-studio.html" target="_blank" rel="noopener"><i data-lucide="maximize-2"></i> Open full screen</a>
  <a class="btn" data-variant="outline" href="#how-it-works">How it works</a>
</div>

```html example standalone label="Workflow studio" schema="none" mode="desktop" hint="Pick an app on the left, then Run (or press R in the editor; with Auto-run pressed every change runs it again): the dashes show the data moving, the connection labels say what went through, the Preview shows the result. Click a prompt, a script, the weights or the order to edit it in a window or a wizard. Type in the navigator's filter and pick a node: with Follow on, the editor flies to it; a click on a card opens its way in the tree. Every edit lands in History - click a row to step the workflow back to it - and every edit and run in Events. The language switch is in the toolbar." previewStyle="align-items:stretch;padding:0;"
<style>
  /* Loom: the scaffold's own glue. Every control is a shipped component (Border Layout, Panel, Resizer, Workflow,
     Data Tree, Window, Dialog, Steps, Button, Toggle, Badge, Table, Language Switcher) */
  .ws {
    position: relative;
    block-size: var(--scaffold-height, 50rem);
  }
  .ws-brand {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-weight: 650;
    white-space: nowrap;
  }
  .ws-brand-mark {
    display: grid;
    place-items: center;
    inline-size: 1.75rem;
    block-size: 1.75rem;
    border-radius: var(--radius-md);
    background: var(--primary);
    color: var(--primary-foreground);

    & svg {
      inline-size: 1rem;
      block-size: 1rem;
    }
  }
  .ws-brand-sub {
    color: var(--muted-foreground);
    font-weight: 450;
  }
  .ws-tools {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 0.375rem;
  }
  .ws-status {
    min-inline-size: 5rem;
    color: var(--muted-foreground);
    font-size: 0.8125rem;
  }
  .ws-apps {
    display: grid;
    gap: 0.25rem;
    margin: 0;
    padding: 0.375rem;
    list-style: none;
  }
  .ws-app {
    display: grid;
    grid-template-columns: auto minmax(0, 1fr);
    gap: 0.125rem 0.625rem;
    align-items: center;
    padding: 0.5rem 0.625rem;
    border-radius: var(--radius-md);
    color: inherit;
    text-decoration: none;

    & svg {
      grid-row: span 2;
      inline-size: 1.125rem;
      block-size: 1.125rem;
      color: var(--muted-foreground);
    }
    & b {
      font-size: 0.8125rem;
      font-weight: 600;
    }
    & small {
      color: var(--muted-foreground);
      font-size: 0.75rem;
      line-height: 1.3;
    }
    &:hover {
      background: var(--accent);
    }
    &[data-current] {
      background: var(--secondary);

      & svg {
        color: var(--primary);
      }
    }
  }
  .ws-nav {
    display: grid;
    grid-template-rows: auto minmax(0, 1fr);
    gap: 0.375rem;
    block-size: 100%;
    padding: 0.375rem;
    box-sizing: border-box;

    & .data-tree {
      block-size: 100%;
      min-block-size: 6rem;
    }
  }
  .ws-editor-head {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    min-inline-size: 0;
    flex: 1;
  }
  .ws-flow {
    --workflow-height: 100%;
    block-size: 100%;
    border: 0;
    border-radius: 0;
  }
  .ws-preview {
    display: grid;
    gap: 0.75rem;
    align-content: start;
    font-size: 0.8125rem;
  }
  .ws-empty {
    margin: 0;
    color: var(--muted-foreground);
  }
  .ws-log {
    margin: 0;
    padding: 0.25rem 0.75rem;
    list-style: none;
    font-family: var(--font-mono);
    font-size: 0.75rem;

    & li {
      display: grid;
      grid-template-columns: 4.5rem 11rem minmax(0, 1fr);
      gap: 0.5rem;
      padding-block: 0.125rem;
      border-block-end: 1px solid color-mix(in oklab, var(--border) 60%, transparent);
    }
    & time {
      color: var(--muted-foreground);
    }
    & b {
      font-weight: 600;
    }
    & span {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  .ws-code-text {
    border: 0;
    border-radius: 0;
    block-size: 100%;
    min-block-size: 14rem;
    font-family: var(--font-mono);
    font-size: 0.8125rem;
    resize: none;
  }
  /* what the cards draw */
  .ws-pre {
    margin: 0;
    font-family: var(--font-mono);
    font-size: 0.6875rem;
    line-height: 1.4;
    white-space: pre-wrap;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 4;
    -webkit-box-orient: vertical;
  }
  .ws-badges {
    display: flex;
    flex-wrap: wrap;
    gap: 0.25rem;
  }
  .ws-kv {
    display: grid;
    grid-template-columns: auto minmax(0, 1fr);
    gap: 0.125rem 0.5rem;
    margin: 0;
    font-size: 0.75rem;

    & dt {
      color: var(--muted-foreground);
    }
    & dd {
      margin: 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  .ws-heat {
    display: block;
    inline-size: 100%;
    block-size: 3.5rem;
    border-radius: var(--radius-sm);
    image-rendering: pixelated;
    background: var(--muted);
  }
  .ws-bars {
    display: flex;
    align-items: end;
    gap: 1px;
    block-size: 1.75rem;

    & i {
      flex: 1;
      min-inline-size: 1px;
      background: var(--chart-2);
      border-radius: 1px 1px 0 0;
    }
  }
  .ws-swatch {
    display: inline-block;
    inline-size: 0.75rem;
    block-size: 0.75rem;
    border-radius: 999px;
    border: 1px solid var(--border);
    vertical-align: -0.0625rem;
  }
  /* the readout matrix: one row per place, one column per digit */
  .ws-matrix {
    border-collapse: collapse;
    font-family: var(--font-mono);
    font-size: 0.6875rem;

    & th {
      padding: 0 0.25rem;
      color: var(--muted-foreground);
      font-weight: 500;
    }
    & td {
      inline-size: 1.125rem;
      block-size: 1.125rem;
      text-align: center;
      border: 1px solid var(--border);
      color: var(--muted-foreground);
    }
    & td[data-on] {
      background: var(--primary);
      color: var(--primary-foreground);
      font-weight: 700;
    }
  }
  .ws-result {
    font-size: 1.75rem;
    font-weight: 650;
    font-variant-numeric: tabular-nums;
    letter-spacing: -0.01em;
  }
  .ws-chat {
    display: grid;
    gap: 0.5rem;
    margin: 0;
    padding: 0;
    list-style: none;

    & li {
      padding: 0.5rem 0.75rem;
      border-radius: var(--radius-lg);
      background: var(--muted);
      white-space: pre-wrap;
    }
    & li[data-from='agent'] {
      background: color-mix(in oklab, var(--primary) 12%, var(--card));
    }
    & small {
      display: block;
      margin-block-end: 0.25rem;
      color: var(--muted-foreground);
      font-size: 0.6875rem;
      font-weight: 600;
      text-transform: uppercase;
      letter-spacing: 0.04em;
    }
  }
  .ws-map {
    inline-size: 100%;
    block-size: auto;
    border-radius: var(--radius-md);
    background: var(--muted);

    & .road {
      stroke: var(--border);
      stroke-width: 1.5;
    }
    & .road[data-busy] {
      stroke: var(--chart-5);
    }
    & .route {
      fill: none;
      stroke: var(--primary);
      stroke-width: 3.5;
      stroke-linecap: round;
      stroke-linejoin: round;
    }
    & circle {
      fill: var(--card);
      stroke: var(--foreground);
      stroke-width: 1.5;
    }
    & circle[data-end] {
      fill: var(--primary);
    }
    & text {
      fill: var(--foreground);
      font-size: 9px;
    }
  }
  .ws-stage {
    position: relative;
    aspect-ratio: 4 / 3;
    border-radius: var(--radius-md);
    overflow: hidden;
    background: var(--muted);

    & canvas {
      display: block;
      inline-size: 100%;
      block-size: 100%;
    }
  }
  .ws-steps-list {
    display: grid;
    gap: 0.375rem;
    margin: 0;
    padding: 0;
    list-style: none;

    & li {
      display: grid;
      grid-template-columns: auto minmax(0, 1fr);
      gap: 0.5rem;
      align-items: start;
    }
  }
  .ws-json {
    margin: 0;
    max-block-size: 14rem;
    overflow: auto;
    padding: 0.5rem;
    border-radius: var(--radius-md);
    background: var(--muted);
    font-family: var(--font-mono);
    font-size: 0.6875rem;
    white-space: pre;
  }
  /* the revision history: one row per change, the current one marked, the undone ones muted */
  .ws-history-steps {
    position: sticky;
    inset-block-start: 0;
    z-index: 1;
    display: flex;
    padding: 0.375rem;
    background: var(--card);

    & .btn {
      flex: 1;
    }
  }
  .ws-history {
    display: grid;
    gap: 1px;
    margin: 0;
    padding: 0 0.375rem 0.375rem;
    list-style: none;
    font-size: 0.75rem;

    & button {
      display: grid;
      grid-template-columns: 1.75rem minmax(0, 1fr);
      gap: 0.375rem;
      align-items: baseline;
      inline-size: 100%;
      padding: 0.25rem 0.5rem;
      border: 0;
      border-radius: var(--radius-sm);
      background: none;
      color: inherit;
      font: inherit;
      text-align: start;
      cursor: pointer;
    }
    & button:hover {
      background: var(--accent);
      color: var(--accent-foreground);
    }
    & button:focus-visible {
      outline: 2px solid var(--ring);
      outline-offset: -2px;
    }
    & small {
      color: var(--muted-foreground);
      font-variant-numeric: tabular-nums;
      text-align: end;
    }
    & span {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    & li[data-undone] span {
      color: var(--muted-foreground);
      text-decoration: line-through;
    }
    & li[aria-current] button {
      background: var(--secondary);
      color: var(--secondary-foreground);
      font-weight: 600;
    }
  }
  /* the BDI-II severity scale: four bands, a marker at the total */
  .ws-scale {
    display: grid;
    gap: 0.25rem;
    margin-block-end: 0.75rem;
    font-size: 0.6875rem;
  }
  .ws-scale-bar {
    position: relative;
    display: flex;
    gap: 2px;
    block-size: 0.625rem;

    & i {
      min-inline-size: 0;
      border-radius: var(--radius-sm);
      background: var(--muted);
    }
    & i[data-on] {
      background: var(--primary);
    }
    & b {
      position: absolute;
      inset-block: -0.25rem;
      inline-size: 2px;
      background: var(--foreground);
      translate: -1px 0;
    }
  }
  .ws-scale-ticks {
    position: relative;
    block-size: 1rem;
    color: var(--muted-foreground);
    font-variant-numeric: tabular-nums;

    & span {
      position: absolute;
      translate: -50% 0;
    }
    & span:first-child {
      translate: 0 0;
    }
    & span:last-child {
      translate: -100% 0;
    }
  }
  .ws [hidden] {
    display: none !important;
  }
  @media (prefers-reduced-motion: reduce) {
    .ws-bars i {
      transition: none;
    }
  }
</style>
<div class="ws" data-ws data-i18n-component>
  <div class="border-layout" id="ws-app" data-frame="none" data-center-min="420" style="block-size: 100%">
    <header class="border-layout-north flex flex-wrap items-center gap-3 px-3 py-2">
      <span class="ws-brand"
        ><span class="ws-brand-mark"><i data-lucide="workflow"></i></span><span>Loom</span
        ><span class="ws-brand-sub" data-i18n-target="ws-brand-sub">workflow studio</span></span
      >
      <div class="separator" data-orientation="vertical" role="separator"></div>
      <div
        class="ws-tools"
        role="toolbar"
        aria-label="Run and edit"
        data-i18n-aria-label-en="Run and edit"
        data-i18n-aria-label-de="Ausführen und bearbeiten"
      >
        <button class="btn" data-size="sm" type="button" data-workflow-for="ws-flow" data-workflow-action="run">
          <i data-lucide="play"></i> <span data-i18n-target="ws-run">Run</span>
        </button>
        <button
          class="btn"
          data-variant="outline"
          data-size="sm"
          type="button"
          data-workflow-for="ws-flow"
          data-workflow-action="cancel"
        >
          <i data-lucide="square"></i> <span data-i18n-target="ws-cancel">Cancel</span>
        </button>
        <output class="ws-status" data-workflow-for="ws-flow" data-workflow-output="status"></output>
        <button
          class="toggle"
          id="ws-auto"
          type="button"
          aria-pressed="false"
          data-size="sm"
          title="Auto-run: a changed value runs the workflow again, half a second after the last change"
          data-i18n-title-en="Auto-run: a changed value runs the workflow again, half a second after the last change"
          data-i18n-title-de="Automatisch ausführen: ein geänderter Wert führt den Workflow eine halbe Sekunde nach der letzten Änderung erneut aus"
        >
          <i data-lucide="refresh-cw"></i> <span data-i18n-target="ws-auto">Auto-run</span>
        </button>
        <div class="separator" data-orientation="vertical" role="separator"></div>
        <button
          class="btn"
          data-variant="ghost"
          data-size="icon-sm"
          type="button"
          aria-label="Undo"
          title="Undo (⌘Z)"
          data-i18n-aria-label-en="Undo"
          data-i18n-aria-label-de="Rückgängig"
          data-i18n-title-en="Undo (⌘Z)"
          data-i18n-title-de="Rückgängig (⌘Z)"
          data-workflow-for="ws-flow"
          data-workflow-action="undo"
        >
          <i data-lucide="undo-2"></i>
        </button>
        <button
          class="btn"
          data-variant="ghost"
          data-size="icon-sm"
          type="button"
          aria-label="Redo"
          title="Redo (⇧⌘Z)"
          data-i18n-aria-label-en="Redo"
          data-i18n-aria-label-de="Wiederholen"
          data-i18n-title-en="Redo (⇧⌘Z)"
          data-i18n-title-de="Wiederholen (⇧⌘Z)"
          data-workflow-for="ws-flow"
          data-workflow-action="redo"
        >
          <i data-lucide="redo-2"></i>
        </button>
        <button
          class="btn"
          data-variant="ghost"
          data-size="sm"
          type="button"
          data-workflow-for="ws-flow"
          data-workflow-action="fit"
        >
          <i data-lucide="scan"></i> <span data-i18n-target="ws-fit">Fit</span>
        </button>
        <button
          class="btn"
          data-variant="ghost"
          data-size="sm"
          type="button"
          data-workflow-for="ws-flow"
          data-workflow-action="arrange"
        >
          <i data-lucide="layout-grid"></i> <span data-i18n-target="ws-arrange">Arrange</span>
        </button>
        <button
          class="toggle"
          id="ws-follow"
          type="button"
          aria-pressed="true"
          data-size="sm"
          title="Follow: a pick in the navigator flies the editor to the node"
          data-i18n-title-en="Follow: a pick in the navigator flies the editor to the node"
          data-i18n-title-de="Folgen: eine Auswahl im Navigator fliegt den Editor zum Knoten"
        >
          <i data-lucide="crosshair"></i> <span data-i18n-target="ws-follow">Follow</span>
        </button>
      </div>
      <div class="flex-1"></div>
      <div
        class="language-switcher"
        data-app-locale
        role="group"
        aria-label="Language"
        data-i18n-aria-label-en="Language"
        data-i18n-aria-label-de="Sprache"
        data-languages="en de"
        data-value="en"
        data-size="sm"
        data-display="icon"
        data-flag-shape="circle"
        data-flag-style="ring"
        data-align="end"
      ></div>
      <button
        class="btn"
        data-variant="ghost"
        data-size="icon-sm"
        type="button"
        aria-pressed="false"
        aria-label="Dark mode"
        title="Dark mode"
        data-i18n-aria-label-en="Dark mode"
        data-i18n-aria-label-de="Dunkelmodus"
        data-i18n-title-en="Dark mode"
        data-i18n-title-de="Dunkelmodus"
        data-ws-theme
      >
        <i data-lucide="moon"></i>
      </button>
    </header>
    <div class="resizer border-layout-west" data-min="180" data-max="420">
      <div
        class="border-layout-stack"
        style="width: 16rem"
        aria-label="Apps and navigator"
        data-i18n-aria-label-en="Apps and navigator"
        data-i18n-aria-label-de="Apps und Navigator"
      >
        <section
          class="card panel"
          id="ws-apps-panel"
          style="--border-layout-share: 2"
          aria-labelledby="ws-apps-title"
          data-density="compact"
        >
          <header class="panel-header">
            <i data-lucide="layout-dashboard" class="panel-icon" aria-hidden="true"></i>
            <h3 class="panel-title" id="ws-apps-title"><span data-i18n-target="ws-t-apps">Apps</span></h3>
            <div class="panel-tools">
              <label class="swap panel-minimize">
                <input
                  type="checkbox"
                  aria-label="Minimize Apps"
                  data-i18n-aria-label-en="Minimize Apps"
                  data-i18n-aria-label-de="Apps einklappen"
                />
                <span class="swap-off"><i data-lucide="chevron-up"></i></span>
                <span class="swap-on"><i data-lucide="chevron-down"></i></span>
              </label>
            </div>
          </header>
          <nav
            class="panel-body"
            data-flush
            aria-label="Apps"
            data-i18n-aria-label-en="Apps"
            data-i18n-aria-label-de="Apps"
          >
            <ul class="ws-apps">
              <li>
                <a class="ws-app" href="#/agents" data-ws-app="agents"
                  ><i data-lucide="bot"></i><b data-i18n-target="ws-a-agents">AI agent crew</b
                  ><small data-i18n-target="ws-a-agents-d"
                    >Prompts, a knowledge base and an order API answer a customer</small
                  ></a
                >
              </li>
              <li>
                <a class="ws-app" href="#/algorithm" data-ws-app="algorithm"
                  ><i data-lucide="route"></i><b data-i18n-target="ws-a-algorithm">Route planner</b
                  ><small data-i18n-target="ws-a-algorithm-d">Dijkstra over live traffic - asked twice</small></a
                >
              </li>
              <li>
                <a class="ws-app" href="#/scene" data-ws-app="scene"
                  ><i data-lucide="box"></i><b data-i18n-target="ws-a-scene">3D scene</b
                  ><small data-i18n-target="ws-a-scene-d"
                    >A scene graph rendered by three.js, with shader and animation subworkflows</small
                  ></a
                >
              </li>
              <li>
                <a class="ws-app" href="#/process" data-ws-app="process"
                  ><i data-lucide="briefcase"></i><b data-i18n-target="ws-a-process">Order to cash</b
                  ><small data-i18n-target="ws-a-process-d">Typed business objects from step to step</small></a
                >
              </li>
              <li>
                <a class="ws-app" href="#/neural" data-ws-app="neural"
                  ><i data-lucide="brain-circuit"></i><b data-i18n-target="ws-a-neural">Neural calculator</b
                  ><small data-i18n-target="ws-a-neural-d"
                    >973 hand-written weights compute A + B, A − B, A × B, A ÷ B</small
                  ></a
                >
              </li>
              <li>
                <a class="ws-app" href="#/bdi" data-ws-app="bdi"
                  ><i data-lucide="clipboard-list"></i><b data-i18n-target="ws-a-bdi">BDI-II form logic</b
                  ><small data-i18n-target="ws-a-bdi-d">21 items, their options and every scoring rule</small></a
                >
              </li>
            </ul>
          </nav>
        </section>
        <section
          class="card panel"
          id="ws-nodes-panel"
          style="--border-layout-share: 2"
          aria-labelledby="ws-nodes-title"
          data-density="compact"
        >
          <header class="panel-header">
            <i data-lucide="shapes" class="panel-icon" aria-hidden="true"></i>
            <h3 class="panel-title" id="ws-nodes-title"><span data-i18n-target="ws-t-nodes">Nodes</span></h3>
            <div class="panel-tools">
              <label class="swap panel-minimize">
                <input
                  type="checkbox"
                  aria-label="Minimize Nodes"
                  data-i18n-aria-label-en="Minimize Nodes"
                  data-i18n-aria-label-de="Knoten einklappen"
                />
                <span class="swap-off"><i data-lucide="chevron-up"></i></span>
                <span class="swap-on"><i data-lucide="chevron-down"></i></span>
              </label>
            </div>
          </header>
          <div
            class="panel-body"
            data-workflow-for="ws-flow"
            data-workflow-outlet="palette"
            data-ws-palette
            title="Click a node type to add it, or drag it onto the canvas"
            data-i18n-title-en="Click a node type to add it, or drag it onto the canvas"
            data-i18n-title-de="Einen Knotentyp anklicken, um ihn hinzuzufügen, oder auf die Fläche ziehen"
          ></div>
        </section>
        <section
          class="card panel"
          id="ws-nav-panel"
          style="--border-layout-share: 3"
          aria-labelledby="ws-nav-title"
          data-density="compact"
        >
          <header class="panel-header">
            <i data-lucide="list-tree" class="panel-icon" aria-hidden="true"></i>
            <h3 class="panel-title" id="ws-nav-title"><span data-i18n-target="ws-t-nav">Navigator</span></h3>
            <div class="panel-tools">
              <label class="swap panel-minimize">
                <input
                  type="checkbox"
                  aria-label="Minimize Navigator"
                  data-i18n-aria-label-en="Minimize Navigator"
                  data-i18n-aria-label-de="Navigator einklappen"
                />
                <span class="swap-off"><i data-lucide="chevron-up"></i></span>
                <span class="swap-on"><i data-lucide="chevron-down"></i></span>
              </label>
            </div>
          </header>
          <div class="panel-body" data-flush>
            <div class="ws-nav">
              <input
                class="input"
                data-size="sm"
                type="search"
                data-tree-filter="ws-tree"
                placeholder="Find a node…"
                aria-label="Find a node"
                data-i18n-placeholder-en="Find a node…"
                data-i18n-placeholder-de="Knoten finden…"
                data-i18n-aria-label-en="Find a node"
                data-i18n-aria-label-de="Knoten finden"
              />
              <div
                class="data-tree"
                id="ws-tree"
                aria-label="The nodes of the workflow"
                data-i18n-aria-label-en="The nodes of the workflow"
                data-i18n-aria-label-de="Die Knoten des Workflows"
                data-label-field="title"
                data-exclusive
                data-persist="none"
                data-density="compact"
              ></div>
            </div>
          </div>
        </section>
      </div>
    </div>
    <div class="border-layout border-layout-center" id="ws-center" data-frame="none" data-center-min="320">
      <section
        class="card panel border-layout-center"
        id="ws-editor"
        aria-labelledby="ws-editor-title"
        data-density="compact"
        data-title-collapse="false"
      >
        <header class="panel-header">
          <div class="ws-editor-head">
            <button
              class="btn"
              data-variant="ghost"
              data-size="xs"
              type="button"
              data-workflow-for="ws-flow"
              data-workflow-action="parent"
              title="Out of the subworkflow"
              data-i18n-title-en="Out of the subworkflow"
              data-i18n-title-de="Aus dem Subworkflow"
            >
              <i data-lucide="arrow-up"></i> <span data-i18n-target="ws-up">Up</span>
            </button>
            <i data-lucide="workflow" class="panel-icon" aria-hidden="true"></i>
            <h3 class="panel-title" id="ws-editor-title"><span data-i18n-target="ws-t-editor">Workflow</span></h3>
            <div class="flex-1 min-w-0" data-workflow-for="ws-flow" data-workflow-outlet="breadcrumb"></div>
          </div>
          <div class="panel-tools">
            <span class="text-xs text-muted-foreground"
              ><span data-workflow-for="ws-flow" data-workflow-output="nodes"></span>
              <span data-i18n-target="ws-nodes">nodes</span> ·
              <span data-workflow-for="ws-flow" data-workflow-output="zoom"></span
            ></span>
            <label class="swap panel-maximize">
              <input
                type="checkbox"
                aria-label="Maximize the editor"
                data-i18n-aria-label-en="Maximize the editor"
                data-i18n-aria-label-de="Editor maximieren"
              />
              <span class="swap-off"><i data-lucide="maximize-2"></i></span>
              <span class="swap-on"><i data-lucide="minimize-2"></i></span>
            </label>
          </div>
        </header>
        <div class="panel-body" data-flush>
          <div
            class="workflow ws-flow"
            id="ws-flow"
            aria-label="The app's workflow"
            data-i18n-aria-label-en="The app's workflow"
            data-i18n-aria-label-de="Der Workflow der App"
          ></div>
        </div>
      </section>
      <!-- the revision history: every change of the shown level; a click steps the workflow to it -->
      <div class="resizer border-layout-east" data-min="180" data-max="420">
        <section
          class="card panel"
          id="ws-history-panel"
          style="width: 13rem"
          aria-labelledby="ws-history-title"
          data-density="compact"
        >
          <header class="panel-header">
            <i data-lucide="history" class="panel-icon" aria-hidden="true"></i>
            <h3 class="panel-title" id="ws-history-title"><span data-i18n-target="ws-t-history">History</span></h3>
            <div class="panel-tools">
              <span class="text-xs text-muted-foreground" data-ws-history-count></span>
              <label class="swap panel-minimize">
                <input
                  type="checkbox"
                  aria-label="Minimize History"
                  data-i18n-aria-label-en="Minimize History"
                  data-i18n-aria-label-de="Verlauf einklappen"
                />
                <span class="swap-off"><i data-lucide="chevron-right"></i></span>
                <span class="swap-on"><i data-lucide="chevron-left"></i></span>
              </label>
            </div>
          </header>
          <div class="panel-body" data-flush>
            <div
              class="ws-history-steps btn-group"
              role="group"
              aria-label="Step"
              data-i18n-aria-label-en="Step"
              data-i18n-aria-label-de="Schritt"
            >
              <button
                class="btn"
                data-variant="outline"
                data-size="xs"
                type="button"
                data-ws-history-step="-1"
                title="One change back"
                data-i18n-title-en="One change back"
                data-i18n-title-de="Eine Änderung zurück"
              >
                <i data-lucide="chevron-up"></i> <span data-i18n-target="ws-h-back">Back</span>
              </button>
              <button
                class="btn"
                data-variant="outline"
                data-size="xs"
                type="button"
                data-ws-history-step="1"
                title="One change forward"
                data-i18n-title-en="One change forward"
                data-i18n-title-de="Eine Änderung vor"
              >
                <i data-lucide="chevron-down"></i> <span data-i18n-target="ws-h-forward">Forward</span>
              </button>
            </div>
            <ol
              class="ws-history"
              data-ws-history
              aria-label="Changes, oldest first"
              data-i18n-aria-label-en="Changes, oldest first"
              data-i18n-aria-label-de="Änderungen, die älteste zuerst"
            ></ol>
          </div>
        </section>
      </div>
    </div>
    <div class="resizer border-layout-east" data-min="260" data-max="640">
      <div
        class="border-layout-stack"
        style="width: 20rem"
        aria-label="Preview and inspector"
        data-i18n-aria-label-en="Preview and inspector"
        data-i18n-aria-label-de="Vorschau und Inspektor"
      >
        <section
          class="card panel"
          id="ws-preview-panel"
          style="--border-layout-share: 3"
          aria-labelledby="ws-preview-title"
          data-density="compact"
        >
          <header class="panel-header">
            <i data-lucide="monitor-play" class="panel-icon" aria-hidden="true"></i>
            <h3 class="panel-title" id="ws-preview-title"><span data-i18n-target="ws-t-preview">Preview</span></h3>
            <div class="panel-tools">
              <label class="swap panel-maximize">
                <input
                  type="checkbox"
                  aria-label="Maximize Preview"
                  data-i18n-aria-label-en="Maximize Preview"
                  data-i18n-aria-label-de="Vorschau maximieren"
                />
                <span class="swap-off"><i data-lucide="maximize-2"></i></span>
                <span class="swap-on"><i data-lucide="minimize-2"></i></span>
              </label>
              <label class="swap panel-minimize">
                <input
                  type="checkbox"
                  aria-label="Minimize Preview"
                  data-i18n-aria-label-en="Minimize Preview"
                  data-i18n-aria-label-de="Vorschau einklappen"
                />
                <span class="swap-off"><i data-lucide="chevron-up"></i></span>
                <span class="swap-on"><i data-lucide="chevron-down"></i></span>
              </label>
            </div>
          </header>
          <div class="panel-body">
            <div class="ws-empty" data-ws-placeholder>
              <span data-i18n-target="ws-preview-empty">Run the workflow - its result shows here.</span>
            </div>
            <div class="ws-preview" data-ws-preview aria-live="polite"></div>
          </div>
        </section>
        <section
          class="card panel"
          id="ws-inspector-panel"
          style="--border-layout-share: 2"
          aria-labelledby="ws-inspector-title"
          data-density="compact"
        >
          <header class="panel-header">
            <i data-lucide="sliders-horizontal" class="panel-icon" aria-hidden="true"></i>
            <h3 class="panel-title" id="ws-inspector-title">
              <span data-i18n-target="ws-t-inspector">Inspector</span>
            </h3>
            <div class="panel-tools">
              <label class="swap panel-minimize">
                <input
                  type="checkbox"
                  aria-label="Minimize Inspector"
                  data-i18n-aria-label-en="Minimize Inspector"
                  data-i18n-aria-label-de="Inspektor einklappen"
                />
                <span class="swap-off"><i data-lucide="chevron-up"></i></span>
                <span class="swap-on"><i data-lucide="chevron-down"></i></span>
              </label>
            </div>
          </header>
          <div class="panel-body" data-workflow-for="ws-flow" data-workflow-outlet="inspector"></div>
        </section>
      </div>
    </div>
    <div class="resizer border-layout-south" data-min="80" data-max="420">
      <section
        class="card panel"
        id="ws-events-panel"
        style="height: 9rem"
        aria-labelledby="ws-events-title"
        data-density="compact"
      >
        <header class="panel-header">
          <i data-lucide="activity" class="panel-icon" aria-hidden="true"></i>
          <h3 class="panel-title" id="ws-events-title"><span data-i18n-target="ws-t-events">Events</span></h3>
          <div class="panel-tools">
            <button class="btn" data-variant="ghost" data-size="xs" type="button" data-ws-clear>
              <span data-i18n-target="ws-clear">Clear</span>
            </button>
            <label class="swap panel-minimize">
              <input
                type="checkbox"
                aria-label="Minimize Events"
                data-i18n-aria-label-en="Minimize Events"
                data-i18n-aria-label-de="Ereignisse einklappen"
              />
              <span class="swap-off"><i data-lucide="chevron-up"></i></span>
              <span class="swap-on"><i data-lucide="chevron-down"></i></span>
            </label>
          </div>
        </header>
        <div class="panel-body" data-flush>
          <ol class="ws-log" data-ws-log aria-live="off"></ol>
        </div>
      </section>
    </div>
  </div>

  <!-- the code editor: a Window over the studio - prompts, scripts, weights, JSON -->
  <dialog
    class="window"
    id="ws-code"
    data-resizable
    style="--window-x: 18rem; --window-y: 4rem; --window-w: 34rem; --window-h: 24rem; z-index: 20"
  >
    <header class="window-titlebar">
      <i data-lucide="file-code-2" class="window-icon"></i>
      <h2 class="window-title" id="ws-code-title">Editor</h2>
      <form method="dialog" class="window-controls">
        <button
          type="button"
          class="window-maximize"
          aria-label="Maximize"
          data-i18n-aria-label-en="Maximize"
          data-i18n-aria-label-de="Maximieren"
        ></button>
        <button
          class="window-close"
          aria-label="Close"
          data-i18n-aria-label-en="Close"
          data-i18n-aria-label-de="Schließen"
        ></button>
      </form>
    </header>
    <div class="window-body" data-flush>
      <textarea
        class="textarea ws-code-text"
        id="ws-code-text"
        aria-labelledby="ws-code-title"
        spellcheck="false"
      ></textarea>
    </div>
    <footer class="window-statusbar flex items-center gap-2">
      <span class="flex-1 text-xs text-muted-foreground" id="ws-code-hint"></span>
      <button class="btn" data-variant="outline" data-size="sm" type="button" id="ws-code-cancel">
        <span data-i18n-target="ws-cancel-2">Cancel</span>
      </button>
      <button class="btn" data-size="sm" type="button" id="ws-code-save">
        <span data-i18n-target="ws-save">Save</span>
      </button>
    </footer>
  </dialog>

  <!-- the order wizard: three steps fold into one Order object -->
  <dialog class="dialog" id="ws-wizard" aria-labelledby="ws-wizard-title">
    <form method="dialog" class="dialog-content" id="ws-wizard-form">
      <div class="dialog-header">
        <h2 class="dialog-title" id="ws-wizard-title"><span data-i18n-target="ws-w-title">Edit the order</span></h2>
        <p class="dialog-description">
          <span data-i18n-target="ws-w-lead">Three steps; Finish folds them into one Order object.</span>
        </p>
      </div>
      <ol class="steps" id="ws-wizard-steps">
        <li class="step" data-status="current" aria-current="step">
          <div class="step-indicator">1</div>
          <div class="step-content">
            <p class="step-title"><span data-i18n-target="ws-w-s1">Customer</span></p>
          </div>
        </li>
        <li class="step">
          <div class="step-indicator">2</div>
          <div class="step-content">
            <p class="step-title"><span data-i18n-target="ws-w-s2">Lines</span></p>
          </div>
        </li>
        <li class="step">
          <div class="step-indicator">3</div>
          <div class="step-content">
            <p class="step-title"><span data-i18n-target="ws-w-s3">Shipping</span></p>
          </div>
        </li>
      </ol>
      <div class="dialog-body">
        <fieldset class="grid gap-3 m-0 p-0" style="border: 0" data-step="0">
          <label class="label" for="ws-w-name"><span data-i18n-target="ws-w-name">Name</span></label>
          <input class="input" id="ws-w-name" name="name" required autocomplete="off" />
          <label class="label" for="ws-w-email"><span data-i18n-target="ws-w-email">Email</span></label>
          <input class="input" id="ws-w-email" name="email" type="email" autocomplete="off" />
          <label class="label" for="ws-w-country"><span data-i18n-target="ws-w-country">Country</span></label>
          <select class="select" id="ws-w-country" name="country">
            <option value="DE">Deutschland</option>
            <option value="AT">Österreich</option>
            <option value="NL">Nederland</option>
            <option value="FR">France</option>
          </select>
        </fieldset>
        <fieldset class="grid gap-3 m-0 p-0" style="border: 0" data-step="1" hidden>
          <legend class="label mb-2"><span data-i18n-target="ws-w-qty">Quantities</span></legend>
          <div class="grid gap-2" style="grid-template-columns: minmax(0, 1fr) 5rem; align-items: center">
            <label for="ws-w-q0">Espresso beans 1 kg · € 24.90</label>
            <input class="input" id="ws-w-q0" name="q0" type="number" min="0" max="20" />
            <label for="ws-w-q1">Hand grinder · € 59.00</label>
            <input class="input" id="ws-w-q1" name="q1" type="number" min="0" max="20" />
            <label for="ws-w-q2">Milk jug 600 ml · € 19.50</label>
            <input class="input" id="ws-w-q2" name="q2" type="number" min="0" max="20" />
          </div>
        </fieldset>
        <fieldset class="grid gap-3 m-0 p-0" style="border: 0" data-step="2" hidden>
          <label class="label" for="ws-w-carrier"><span data-i18n-target="ws-w-carrier">Carrier</span></label>
          <select class="select" id="ws-w-carrier" name="carrier">
            <option value="DHL">DHL</option>
            <option value="UPS">UPS</option>
            <option value="DPD">DPD</option>
          </select>
          <label class="flex items-center gap-2"
            ><input class="switch" type="checkbox" role="switch" name="express" />
            <span data-i18n-target="ws-w-express">Express delivery</span></label
          >
        </fieldset>
      </div>
      <div class="dialog-footer">
        <button class="btn" data-variant="outline" type="button" id="ws-w-back">
          <span data-i18n-target="ws-w-back">Back</span>
        </button>
        <button class="btn" data-variant="outline" value="cancel">
          <span data-i18n-target="ws-w-cancel">Cancel</span>
        </button>
        <button class="btn" type="button" id="ws-w-next"><span data-i18n-target="ws-w-next">Next</span></button>
        <button class="btn" value="finish" id="ws-w-finish" style="display: none">
          <span data-i18n-target="ws-w-finish">Finish</span>
        </button>
      </div>
    </form>
  </dialog>

  <!-- the catalog: every text the frame shows, in English and German -->
  <template data-i18n-for="ws-brand-sub" data-i18n-locale="en">workflow studio</template>
  <template data-i18n-for="ws-brand-sub" data-i18n-locale="de">Workflow-Studio</template>
  <template data-i18n-for="ws-run" data-i18n-locale="en">Run</template>
  <template data-i18n-for="ws-run" data-i18n-locale="de">Ausführen</template>
  <template data-i18n-for="ws-auto" data-i18n-locale="en">Auto-run</template>
  <template data-i18n-for="ws-auto" data-i18n-locale="de">Automatisch</template>
  <template data-i18n-for="ws-t-history" data-i18n-locale="en">History</template>
  <template data-i18n-for="ws-t-history" data-i18n-locale="de">Verlauf</template>
  <template data-i18n-for="ws-h-back" data-i18n-locale="en">Back</template>
  <template data-i18n-for="ws-h-back" data-i18n-locale="de">Zurück</template>
  <template data-i18n-for="ws-h-forward" data-i18n-locale="en">Forward</template>
  <template data-i18n-for="ws-h-forward" data-i18n-locale="de">Vor</template>
  <template data-i18n-for="ws-cancel" data-i18n-locale="en">Cancel</template>
  <template data-i18n-for="ws-cancel" data-i18n-locale="de">Abbrechen</template>
  <template data-i18n-for="ws-fit" data-i18n-locale="en">Fit</template>
  <template data-i18n-for="ws-fit" data-i18n-locale="de">Einpassen</template>
  <template data-i18n-for="ws-arrange" data-i18n-locale="en">Arrange</template>
  <template data-i18n-for="ws-arrange" data-i18n-locale="de">Anordnen</template>
  <template data-i18n-for="ws-follow" data-i18n-locale="en">Follow</template>
  <template data-i18n-for="ws-follow" data-i18n-locale="de">Folgen</template>
  <template data-i18n-for="ws-t-apps" data-i18n-locale="en">Apps</template>
  <template data-i18n-for="ws-t-apps" data-i18n-locale="de">Apps</template>
  <template data-i18n-for="ws-a-agents" data-i18n-locale="en">AI agent crew</template>
  <template data-i18n-for="ws-a-agents" data-i18n-locale="de">KI-Agenten-Team</template>
  <template data-i18n-for="ws-a-agents-d" data-i18n-locale="en"
    >Prompts, a knowledge base and an order API answer a customer</template
  >
  <template data-i18n-for="ws-a-agents-d" data-i18n-locale="de"
    >Prompts, eine Wissensdatenbank und eine Bestell-API beantworten eine Kundin</template
  >
  <template data-i18n-for="ws-a-algorithm" data-i18n-locale="en">Route planner</template>
  <template data-i18n-for="ws-a-algorithm" data-i18n-locale="de">Routenplaner</template>
  <template data-i18n-for="ws-a-algorithm-d" data-i18n-locale="en">Dijkstra over live traffic - asked twice</template>
  <template data-i18n-for="ws-a-algorithm-d" data-i18n-locale="de"
    >Dijkstra über den aktuellen Verkehr - zweimal gefragt</template
  >
  <template data-i18n-for="ws-a-scene" data-i18n-locale="en">3D scene</template>
  <template data-i18n-for="ws-a-scene" data-i18n-locale="de">3D-Szene</template>
  <template data-i18n-for="ws-a-scene-d" data-i18n-locale="en"
    >A scene graph rendered by three.js, with shader and animation subworkflows</template
  >
  <template data-i18n-for="ws-a-scene-d" data-i18n-locale="de"
    >Ein Szenengraph, gerendert von three.js, mit Shader- und Animations-Subworkflows</template
  >
  <template data-i18n-for="ws-a-process" data-i18n-locale="en">Order to cash</template>
  <template data-i18n-for="ws-a-process" data-i18n-locale="de">Bestellung bis Zahlung</template>
  <template data-i18n-for="ws-a-process-d" data-i18n-locale="en">Typed business objects from step to step</template>
  <template data-i18n-for="ws-a-process-d" data-i18n-locale="de"
    >Typisierte Geschäftsobjekte von Schritt zu Schritt</template
  >
  <template data-i18n-for="ws-a-neural" data-i18n-locale="en">Neural calculator</template>
  <template data-i18n-for="ws-a-neural" data-i18n-locale="de">Neuronaler Rechner</template>
  <template data-i18n-for="ws-a-neural-d" data-i18n-locale="en"
    >973 hand-written weights compute A + B, A − B, A × B, A ÷ B</template
  >
  <template data-i18n-for="ws-a-neural-d" data-i18n-locale="de"
    >973 von Hand geschriebene Gewichte rechnen A + B, A − B, A × B, A ÷ B</template
  >
  <template data-i18n-for="ws-a-bdi" data-i18n-locale="en">BDI-II form logic</template>
  <template data-i18n-for="ws-a-bdi" data-i18n-locale="de">BDI-II-Formularlogik</template>
  <template data-i18n-for="ws-a-bdi-d" data-i18n-locale="en">21 items, their options and every scoring rule</template>
  <template data-i18n-for="ws-a-bdi-d" data-i18n-locale="de">21 Items, ihre Optionen und jede Auswerteregel</template>
  <template data-i18n-for="ws-t-editor" data-i18n-locale="en">Workflow</template>
  <template data-i18n-for="ws-t-editor" data-i18n-locale="de">Workflow</template>
  <template data-i18n-for="ws-t-nodes" data-i18n-locale="en">Nodes</template>
  <template data-i18n-for="ws-t-nodes" data-i18n-locale="de">Knoten</template>
  <template data-i18n-for="ws-t-nav" data-i18n-locale="en">Navigator</template>
  <template data-i18n-for="ws-t-nav" data-i18n-locale="de">Navigator</template>
  <template data-i18n-for="ws-up" data-i18n-locale="en">Up</template>
  <template data-i18n-for="ws-up" data-i18n-locale="de">Hoch</template>
  <template data-i18n-for="ws-nodes" data-i18n-locale="en">nodes</template>
  <template data-i18n-for="ws-nodes" data-i18n-locale="de">Knoten</template>
  <template data-i18n-for="ws-t-preview" data-i18n-locale="en">Preview</template>
  <template data-i18n-for="ws-t-preview" data-i18n-locale="de">Vorschau</template>
  <template data-i18n-for="ws-preview-empty" data-i18n-locale="en">Run the workflow - its result shows here.</template>
  <template data-i18n-for="ws-preview-empty" data-i18n-locale="de"
    >Führe den Workflow aus - sein Ergebnis erscheint hier.</template
  >
  <template data-i18n-for="ws-t-inspector" data-i18n-locale="en">Inspector</template>
  <template data-i18n-for="ws-t-inspector" data-i18n-locale="de">Inspektor</template>
  <template data-i18n-for="ws-t-events" data-i18n-locale="en">Events</template>
  <template data-i18n-for="ws-t-events" data-i18n-locale="de">Ereignisse</template>
  <template data-i18n-for="ws-clear" data-i18n-locale="en">Clear</template>
  <template data-i18n-for="ws-clear" data-i18n-locale="de">Leeren</template>
  <template data-i18n-for="ws-cancel-2" data-i18n-locale="en">Cancel</template>
  <template data-i18n-for="ws-cancel-2" data-i18n-locale="de">Abbrechen</template>
  <template data-i18n-for="ws-save" data-i18n-locale="en">Save</template>
  <template data-i18n-for="ws-save" data-i18n-locale="de">Speichern</template>
  <template data-i18n-for="ws-w-title" data-i18n-locale="en">Edit the order</template>
  <template data-i18n-for="ws-w-title" data-i18n-locale="de">Bestellung bearbeiten</template>
  <template data-i18n-for="ws-w-lead" data-i18n-locale="en"
    >Three steps; Finish folds them into one Order object.</template
  >
  <template data-i18n-for="ws-w-lead" data-i18n-locale="de"
    >Drei Schritte; Fertig fasst sie zu einem Order-Objekt zusammen.</template
  >
  <template data-i18n-for="ws-w-s1" data-i18n-locale="en">Customer</template>
  <template data-i18n-for="ws-w-s1" data-i18n-locale="de">Kunde</template>
  <template data-i18n-for="ws-w-s2" data-i18n-locale="en">Lines</template>
  <template data-i18n-for="ws-w-s2" data-i18n-locale="de">Positionen</template>
  <template data-i18n-for="ws-w-s3" data-i18n-locale="en">Shipping</template>
  <template data-i18n-for="ws-w-s3" data-i18n-locale="de">Versand</template>
  <template data-i18n-for="ws-w-name" data-i18n-locale="en">Name</template>
  <template data-i18n-for="ws-w-name" data-i18n-locale="de">Name</template>
  <template data-i18n-for="ws-w-email" data-i18n-locale="en">Email</template>
  <template data-i18n-for="ws-w-email" data-i18n-locale="de">E-Mail</template>
  <template data-i18n-for="ws-w-country" data-i18n-locale="en">Country</template>
  <template data-i18n-for="ws-w-country" data-i18n-locale="de">Land</template>
  <template data-i18n-for="ws-w-qty" data-i18n-locale="en">Quantities</template>
  <template data-i18n-for="ws-w-qty" data-i18n-locale="de">Mengen</template>
  <template data-i18n-for="ws-w-carrier" data-i18n-locale="en">Carrier</template>
  <template data-i18n-for="ws-w-carrier" data-i18n-locale="de">Versanddienst</template>
  <template data-i18n-for="ws-w-express" data-i18n-locale="en">Express delivery</template>
  <template data-i18n-for="ws-w-express" data-i18n-locale="de">Expresszustellung</template>
  <template data-i18n-for="ws-w-back" data-i18n-locale="en">Back</template>
  <template data-i18n-for="ws-w-back" data-i18n-locale="de">Zurück</template>
  <template data-i18n-for="ws-w-cancel" data-i18n-locale="en">Cancel</template>
  <template data-i18n-for="ws-w-cancel" data-i18n-locale="de">Abbrechen</template>
  <template data-i18n-for="ws-w-next" data-i18n-locale="en">Next</template>
  <template data-i18n-for="ws-w-next" data-i18n-locale="de">Weiter</template>
  <template data-i18n-for="ws-w-finish" data-i18n-locale="en">Finish</template>
  <template data-i18n-for="ws-w-finish" data-i18n-locale="de">Fertig</template>
</div>
<script type="module">
  // Loom: routing (defuss-dom-router), translation (defuss-i18n) and the studio's own wiring - six apps, each a
  // workflow document plus the node types and connection types it uses, a navigator, a log and a preview
  import { createRouter } from 'https://cdn.jsdelivr.net/npm/defuss-dom-router@0.1.1/dist/index.js';
  import { createDomI18n, createI18n } from 'https://cdn.jsdelivr.net/npm/defuss-i18n@0.2.0/dist/core.js';

  // df$ comes with the component bundle - a full-screen page loads it after this module
  addEventListener('DOMContentLoaded', async () => {
    const W = df$.shadcn.workflow;
    const T = df$.shadcn.dataTree;
    const root = df$('[data-ws]').get(0);
    const flow = df$('#ws-flow').get(0);
    const tree = df$('#ws-tree').get(0);
    const follow = df$('#ws-follow').get(0);
    const previewEl = df$('[data-ws-preview]').get(0);
    const logEl = df$('[data-ws-log]').get(0);

    // -- translation: the markup is the catalog (the templates at the end of the app)
    const locale = createI18n({ locale: 'en' }); // the demos start in English; the switch offers German
    createDomI18n(df$).bind(root, locale);
    df$.shadcn.languageSwitcher.bind(df$('[data-app-locale]').get(0), locale);

    // -- light / dark: the class every token reads; the editor redraws its canvas from the tokens
    const theme = df$('[data-ws-theme]');
    const showTheme = () => theme.attr('aria-pressed', String(document.documentElement.classList.contains('dark')));
    showTheme();
    theme.on('click', () => {
      document.documentElement.classList.toggle('dark');
      showTheme();
      document.dispatchEvent(new CustomEvent('defuss-theme-change'));
    });

    // -- small helpers for what the cards and the preview draw
    const h = (tag, props = {}, ...kids) => {
      const el = document.createElement(tag);
      for (const [k, v] of Object.entries(props)) {
        if (v === undefined || v === null || v === false) continue;
        if (k === 'class') el.className = v;
        else if (k === 'style') el.style.cssText = v;
        else if (k === 'text') el.textContent = v;
        else el.setAttribute(k, v === true ? '' : v);
      }
      for (const kid of kids.flat()) if (kid !== null && kid !== undefined && kid !== false) el.append(kid);
      return el;
    };
    const badge = (text, variant = 'secondary') => h('span', { class: 'badge', 'data-variant': variant, text });
    const badges = (list, variant) =>
      h(
        'div',
        { class: 'ws-badges' },
        list.map((t) => badge(t, variant)),
      );
    const kv = (pairs) =>
      h(
        'dl',
        { class: 'ws-kv' },
        pairs.flatMap(([k, v]) => [h('dt', { text: k }), h('dd', { text: String(v) })]),
      );
    const pre = (text, lines = 4) => {
      const el = h('pre', { class: 'ws-pre', text: String(text ?? '') });
      el.style.webkitLineClamp = String(lines);
      return el;
    };
    const span = (text, color) => h('span', { text, style: color ? `color: ${color}` : null });
    const wait = (ms, signal) =>
      new Promise((resolve, reject) => {
        const t = setTimeout(resolve, ms);
        signal?.addEventListener('abort', () => (clearTimeout(t), reject(new Error('Cancelled'))), { once: true });
      });
    // a slow call that reports its progress - the stand-in for a network or model call
    const work = async (ms, signal, progress) => {
      for (let i = 1; i <= 5; i++) {
        await wait(ms / 5, signal);
        progress?.(i / 5);
      }
    };
    const first = (inputs, key) => inputs[key]?.[0];
    const money = (n) => '€ ' + Number(n).toFixed(2);
    const port = (id, direction, type, extra = {}) => ({ id, direction, type, ...extra });

    // -- the events log: every event the editor fires lands here, newest first
    const log = (name, text) => {
      const time = new Date().toLocaleTimeString('en-GB');
      logEl.prepend(h('li', {}, h('time', { text: time }), h('b', { text: name }), h('span', { text, title: text })));
      while (logEl.children.length > 400) logEl.lastElementChild.remove();
    };
    df$('[data-ws-clear]').on('click', () => df$(logEl).empty());
    const short = (v) => {
      const s = JSON.stringify(v);
      return s === undefined ? 'nothing' : s.length > 60 ? s.slice(0, 57) + '...' : s;
    };
    flow.addEventListener('workflow-change', (e) => log('workflow-change', e.detail.label));
    flow.addEventListener('workflow-field-change', (e) =>
      log(
        'workflow-field-change',
        `${e.detail.nodeId}.${e.detail.key}: ${short(e.detail.oldValue)} to ${short(e.detail.value)}`,
      ),
    );
    flow.addEventListener('workflow-field-edit', (e) =>
      log('workflow-field-edit', `${e.detail.nodeId}.${e.detail.key}`),
    );
    flow.addEventListener('workflow-select', (e) =>
      log('workflow-select', e.detail.edge ? 'connection ' + e.detail.edge : e.detail.selected.join(', ') || 'nothing'),
    );
    flow.addEventListener('workflow-run', (e) =>
      log('workflow-run', e.detail.status + (e.detail.message ? ': ' + e.detail.message : '')),
    );
    flow.addEventListener('workflow-node-state', (e) => {
      const s = e.detail.state.status;
      if (s === 'success' || s === 'error')
        log(
          'workflow-node-state',
          `${e.detail.nodeId} ${s}${e.detail.state.message ? ': ' + e.detail.state.message : ''}`,
        );
    });
    flow.addEventListener('workflow-navigate', (e) => log('workflow-navigate', e.detail.path.join(' / ')));

    // -- the code editor: a Window; resolves with the text on Save, undefined on Cancel or close. A check may refuse
    //    the text - the window stays open and says why
    const win = df$('#ws-code').get(0);
    const code = df$('#ws-code-text').get(0);
    const hint = df$('#ws-code-hint').get(0);
    const editText = (title, value, check) =>
      new Promise((resolve) => {
        if (win.open) df$.shadcn.win.close(win);
        df$('#ws-code-title').text(title);
        code.value = value ?? '';
        hint.textContent = '';
        const off = new AbortController();
        const finish = (result) => {
          off.abort();
          if (win.open) df$.shadcn.win.close(win);
          resolve(result);
        };
        df$('#ws-code-save')
          .get(0)
          .addEventListener(
            'click',
            () => {
              const problem = check?.(code.value);
              if (problem) return void (hint.textContent = problem);
              finish(code.value);
            },
            { signal: off.signal },
          );
        df$('#ws-code-cancel')
          .get(0)
          .addEventListener('click', () => finish(undefined), { signal: off.signal });
        win.addEventListener('close', () => finish(undefined), { signal: off.signal });
        df$.shadcn.win.open(win);
        code.focus();
      });
    // JSON in the same window: parsed on Save, refused while it does not parse or fails the check
    const editJson = (title, value, check) =>
      editText(title, JSON.stringify(value, null, 2), (text) => {
        let parsed;
        try {
          parsed = JSON.parse(text);
        } catch (err) {
          return 'Not valid JSON: ' + err.message;
        }
        return check?.(parsed) ?? null;
      }).then((text) => (text === undefined ? undefined : JSON.parse(text)));

    // -- the order wizard: three steps in a modal Dialog, folded into one Order object on Finish
    const wizard = df$('#ws-wizard').get(0);
    const wform = df$('#ws-wizard-form').get(0);
    const wsteps = df$('#ws-wizard-steps .step').toArray();
    const wpages = df$(wform).find('[data-step]').toArray();
    let wat = 0;
    const wshow = (i) => {
      wat = i;
      wpages.forEach((p, k) => (p.hidden = k !== i));
      wsteps.forEach((s, k) => {
        s.dataset.status = k < i ? 'complete' : k === i ? 'current' : '';
        if (k === i) s.setAttribute('aria-current', 'step');
        else s.removeAttribute('aria-current');
      });
      df$('#ws-w-back').get(0).disabled = i === 0;
      // a Button's display beats the hidden attribute: show and hide them by style
      df$('#ws-w-next').get(0).style.display = i === wpages.length - 1 ? 'none' : '';
      df$('#ws-w-finish').get(0).style.display = i === wpages.length - 1 ? '' : 'none';
    };
    df$('#ws-w-back').on('click', () => wshow(Math.max(0, wat - 1)));
    df$('#ws-w-next').on('click', () => {
      if (wat === 0 && !df$('#ws-w-name').get(0).reportValidity()) return;
      wshow(Math.min(wpages.length - 1, wat + 1));
    });
    const PRODUCTS = [
      { sku: 'BEAN-1KG', name: 'Espresso beans 1 kg', price: 24.9 },
      { sku: 'GRIND-H', name: 'Hand grinder', price: 59 },
      { sku: 'JUG-600', name: 'Milk jug 600 ml', price: 19.5 },
    ];
    const editOrder = (order) =>
      new Promise((resolve) => {
        const f = wform.elements;
        f.name.value = order.customer.name;
        f.email.value = order.customer.email;
        f.country.value = order.customer.country;
        PRODUCTS.forEach((p, i) => (f['q' + i].value = String(order.lines.find((l) => l.sku === p.sku)?.qty ?? 0)));
        f.carrier.value = order.shipping.carrier;
        f.express.checked = order.shipping.express;
        wshow(0);
        wizard.returnValue = '';
        wizard.addEventListener(
          'close',
          () => {
            if (wizard.returnValue !== 'finish') return resolve(undefined);
            resolve({
              id: order.id,
              customer: { name: f.name.value.trim(), email: f.email.value.trim(), country: f.country.value },
              lines: PRODUCTS.map((p, i) => ({
                ...p,
                qty: Math.max(0, Math.round(Number(f['q' + i].value) || 0)),
              })).filter((l) => l.qty > 0),
              shipping: { carrier: f.carrier.value, express: f.express.checked },
            });
          },
          { once: true },
        );
        wizard.showModal();
      });

    // -- the apps: each one registers its node types and connection types, builds its document and draws its preview
    const APPS = {};
    const node = (type, id, x, y, overrides = {}) => W.node(flow, type, { x, y }, { id, ...overrides });
    const edge = (id, from, to, extra = {}) => {
      const [sn, sp] = from.split('.');
      const [tn, tp] = to.split('.');
      return { id, source: { node: sn, port: sp }, target: { node: tn, port: tp }, ...extra };
    };
    // the layouts are drawn on a tight grid; spread sideways, so a connection has room for its label
    const SPREAD = 1.4;
    // each card as high as its content after the first run, plus 12px - measured per document and node (the
    // estimate W.node makes from the field kinds cannot know what a rendered value or a custom body needs)
    const FIT = {
      support: { classify: 277, guard: 316, kb: 195, orders: 195, send: 265, writer: 389 },
      routes: { graph: 135, recheck: 135, stops: 260, traffic: 135 },
      scene: { fill: 252, glow: 190, gold: 235, hero: 274, ico: 178, key: 252, knot: 222, satellite: 274, scene: 289 },
      glow: { noise: 178, fresnel: 135 },
      motion: { spin: 195, bob: 178, combine: 100 },
      o2c: { credit: 199, invoice: 338, ledger: 218, order: 201, reject: 100, validate: 322 },
      fulfil: { pack: 135, ship: 100 },
      neural: {
        a: 135,
        b: 135,
        bits: 388,
        decimals: 372,
        divide: 393,
        flags: 398,
        multiply: 372,
        p0: 393,
        p1: 393,
        p2: 393,
        p3: 393,
        p4: 393,
        p5: 393,
        p6: 393,
        select: 497,
      },
      bdi: { band: 211, direction: 145, report: 242, rules: 227, safety: 190 },
    };
    const doc = (id, title, nodes, edges, groups = [], spread = SPREAD) => ({
      schemaVersion: 1,
      id,
      title,
      nodes: nodes.map((n) => ({ ...n, x: Math.round(n.x * spread), height: FIT[id]?.[n.id] ?? n.height })),
      edges,
      groups: groups.map((g) => ({ ...g, x: Math.round(g.x * spread) - Math.round(30 * (spread - 1)) })),
    });
    const sub = (id, title, nodes, edges, inputs, outputs) => ({ ...doc(id, title, nodes, edges), inputs, outputs });

    // ---- a) AI agent crew: a customer message, a knowledge base and an order API (external data), agents with
    //      prompts; the agents are deterministic stand-ins for model calls, so the demo runs offline and the same way
    {
      const KB = [
        {
          id: 'kb-returns',
          title: 'Returns within 30 days',
          text: 'Unused items can be returned within 30 days for a full refund. Start the return in your account; the label is free.',
          tags: ['return', 'refund', 'money', 'back', 'cancel'],
        },
        {
          id: 'kb-damaged',
          title: 'Damaged on arrival',
          text: 'If an item arrives damaged, send a photo within 7 days and we replace it or refund it at once - no return needed.',
          tags: ['damaged', 'broken', 'crack', 'photo', 'refund'],
        },
        {
          id: 'kb-shipping',
          title: 'Delivery times',
          text: 'Standard delivery takes 2-4 working days, express 1 day. Tracking starts when the parcel leaves the warehouse.',
          tags: ['delivery', 'shipping', 'where', 'late', 'track', 'parcel'],
        },
        {
          id: 'kb-warranty',
          title: 'Two-year warranty',
          text: 'Grinders and machines carry a two-year warranty. Faults are repaired or the part is replaced free of charge.',
          tags: ['warranty', 'grinder', 'fault', 'repair', 'machine'],
        },
        {
          id: 'kb-beans',
          title: 'Freshness of the beans',
          text: 'Beans are roasted weekly and best within six weeks of the roast date printed on the bag.',
          tags: ['beans', 'fresh', 'roast', 'taste'],
        },
      ];
      const ORDERS = {
        48213: {
          id: '48213',
          status: 'delivered',
          carrier: 'DHL',
          eta: '2026-11-14',
          items: ['Hand grinder', 'Milk jug 600 ml'],
        },
        51877: { id: '51877', status: 'in transit', carrier: 'UPS', eta: '2026-11-19', items: ['Espresso beans 1 kg'] },
      };
      const words = (text) =>
        String(text)
          .toLowerCase()
          .match(/[a-zäöüß]+/g) ?? [];
      const tokens = (text) => Math.ceil(String(text).length / 4);
      const prompt = (key, label, height = 96) => ({
        key,
        label,
        kind: 'textarea',
        height,
        edit: (value) => editText(label, value),
        render: (value) => pre(value, 3),
      });
      const model = {
        key: 'model',
        label: 'Model',
        kind: 'select',
        options: ['claude-sonnet-5-5', 'claude-haiku-5-5', 'claude-opus-5-5'],
      };
      const temperature = {
        key: 'temperature',
        label: 'Temperature',
        kind: 'slider',
        min: 0,
        max: 1.5,
        step: 0.1,
        renderLabel: (v) =>
          v >= 1
            ? span('🔥 Temperature - creative', 'var(--destructive)')
            : v <= 0.2
              ? span('🧊 Temperature - exact')
              : null,
      };
      const types = [
        {
          type: 'ag-inbox',
          label: 'Customer message',
          category: 'Agents',
          color: 'chart-1',
          width: 280,
          ports: [port('message', 'output', 'message')],
          defaults: {
            from: 'Mara Lindqvist',
            text: 'Hi! My grinder from order #48213 arrived with a cracked hopper. Can I get my money back or a new one?',
          },
          fields: [
            { key: 'from', label: 'From', kind: 'text' },
            { key: 'text', label: 'Message', kind: 'textarea', rows: 4 },
          ],
          run: async (n, { signal, progress }) => (
            await work(250, signal, progress),
            { message: { from: n.data.from, text: n.data.text } }
          ),
        },
        {
          type: 'ag-kb',
          label: 'Knowledge base',
          description: 'External data: searches the help centre',
          category: 'Data sources',
          color: 'chart-3',
          width: 260,
          ports: [port('query', 'input', 'message'), port('docs', 'output', 'context')],
          defaults: { collection: 'help centre', topK: 2 },
          fields: [
            { key: 'collection', label: 'Collection', kind: 'select', options: ['help centre', 'internal notes'] },
            {
              key: 'topK',
              label: 'Results',
              kind: 'slider',
              min: 1,
              max: 5,
              step: 1,
              renderLabel: (v) => '📚 Top ' + v + ' results',
            },
          ],
          run: async (n, { inputs, signal, progress }) => {
            await work(700, signal, progress);
            const q = new Set(words(first(inputs, 'query')?.text ?? ''));
            const scored = KB.map((d) => ({
              ...d,
              score: d.tags.filter((t) => [...q].some((w) => w.startsWith(t))).length,
            })).filter((d) => d.score);
            scored.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
            return {
              docs: scored.slice(0, n.data.topK).map(({ id, title, text, score }) => ({ id, title, text, score })),
            };
          },
        },
        {
          type: 'ag-orders',
          label: 'Order API',
          description: 'External data: GET /orders/:id',
          category: 'Data sources',
          color: 'chart-4',
          width: 260,
          ports: [port('query', 'input', 'message'), port('order', 'output', 'record')],
          defaults: { endpoint: 'https://api.loom.example/orders/:id', timeout: 3 },
          fields: [
            { key: 'endpoint', label: 'Endpoint', kind: 'text' },
            { key: 'timeout', label: 'Timeout (s)', kind: 'slider', min: 1, max: 10, step: 1 },
          ],
          run: async (n, { inputs, signal, progress }) => {
            await work(600, signal, progress);
            const id = /#?(\d{5})/.exec(first(inputs, 'query')?.text ?? '')?.[1];
            return { order: (id && ORDERS[id]) || { id: id ?? null, status: 'not found' } };
          },
        },
        {
          type: 'ag-classify',
          label: 'Classifier agent',
          category: 'Agents',
          color: 'chart-2',
          width: 280,
          ports: [port('message', 'input', 'message'), port('intent', 'output', 'intent')],
          defaults: {
            model: 'claude-haiku-5-5',
            temperature: 0,
            prompt:
              'Classify the customer message as one of:\nrefund, replacement, where-is-my-order, warranty, other.\nAnswer with the label only.',
          },
          fields: [model, temperature, prompt('prompt', 'Prompt')],
          run: async (n, { inputs, signal, progress }) => {
            await work(500, signal, progress);
            const w = words(first(inputs, 'message')?.text ?? '').join(' ');
            const intent = /crack|broken|damaged/.test(w)
              ? 'replacement'
              : /refund|money|return/.test(w)
                ? 'refund'
                : /where|late|track|delivery/.test(w)
                  ? 'where-is-my-order'
                  : /warranty|fault|repair/.test(w)
                    ? 'warranty'
                    : 'other';
            return { intent };
          },
        },
        {
          type: 'ag-research',
          label: 'Researcher agent',
          category: 'Agents',
          color: 'chart-2',
          width: 280,
          ports: [
            port('intent', 'input', 'intent'),
            port('docs', 'input', 'context'),
            port('order', 'input', 'record', { optional: true }),
            port('notes', 'output', 'brief'),
          ],
          defaults: {
            model: 'claude-sonnet-5-5',
            prompt:
              'Using only the documents and the order record,\nlist the facts that answer a "{{intent}}" request.\nCite each document by its id.',
          },
          fields: [model, prompt('prompt', 'Prompt', 84)],
          run: async (n, { inputs, signal, progress }) => {
            await work(900, signal, progress);
            const docs = first(inputs, 'docs') ?? [];
            const order = first(inputs, 'order');
            const facts = docs.map((d) => `${d.text} [${d.id}]`);
            if (order?.status && order.status !== 'not found')
              facts.unshift(
                `Order ${order.id} (${order.items.join(', ')}) was ${order.status} by ${order.carrier} on ${order.eta}.`,
              );
            return {
              notes: {
                intent: first(inputs, 'intent'),
                facts,
                sources: docs.map((d) => d.id),
                order: order?.id ?? null,
              },
            };
          },
        },
        {
          type: 'ag-critic',
          label: 'Critic agent',
          category: 'Agents',
          color: 'chart-5',
          width: 260,
          ports: [port('notes', 'input', 'brief'), port('brief', 'output', 'brief')],
          defaults: { strictness: 'cite every fact' },
          fields: [
            {
              key: 'strictness',
              label: 'Strictness',
              kind: 'select',
              options: ['cite every fact', 'lenient'],
              renderLabel: (v) => (v === 'lenient' ? '🙂 Strictness' : '🧐 Strictness'),
            },
          ],
          run: async (n, { inputs, signal, progress }) => {
            await work(500, signal, progress);
            const notes = first(inputs, 'notes') ?? { facts: [] };
            const kept =
              n.data.strictness === 'lenient' ? notes.facts : notes.facts.filter((f) => /\[kb-|^Order /.test(f));
            return { brief: { ...notes, facts: kept, dropped: notes.facts.length - kept.length } };
          },
        },
        {
          type: 'ag-crew',
          label: 'Research crew',
          description: 'A subworkflow: a researcher and a critic',
          category: 'Agents',
          color: 'chart-2',
          width: 260,
          ports: [
            port('intent', 'input', 'intent'),
            port('docs', 'input', 'context'),
            port('order', 'input', 'record', { optional: true }),
            port('brief', 'output', 'brief'),
          ],
          fields: [
            {
              key: 'about',
              label: 'Inside',
              kind: 'value',
              render: () => 'A researcher, then a critic. Double-click to open.',
            },
          ],
        },
        {
          type: 'ag-writer',
          label: 'Writer agent',
          category: 'Agents',
          color: 'chart-2',
          width: 280,
          ports: [
            port('message', 'input', 'message'),
            port('intent', 'input', 'intent'),
            port('brief', 'input', 'brief'),
            port('reply', 'output', 'message'),
          ],
          defaults: {
            model: 'claude-sonnet-5-5',
            tone: 'warm',
            temperature: 0.6,
            prompt:
              'Write a {{tone}} reply to {{customer}} that resolves the\n"{{intent}}" request with the facts in the brief.\nNo promises the facts do not support.',
          },
          fields: [
            model,
            { key: 'tone', label: 'Tone', kind: 'select', options: ['warm', 'neutral', 'formal'] },
            temperature,
            prompt('prompt', 'Prompt', 84),
          ],
          run: async (n, { inputs, signal, progress }) => {
            const msg = first(inputs, 'message') ?? { from: 'there', text: '' };
            const intent = first(inputs, 'intent') ?? 'other';
            const brief = first(inputs, 'brief') ?? { facts: [] };
            const name = String(msg.from).split(' ')[0];
            const hello =
              {
                warm: `Hi ${name}, thank you for writing to us - and sorry about this!`,
                neutral: `Hello ${name},`,
                formal: `Dear ${msg.from},`,
              }[n.data.tone] ?? `Hello ${name},`;
            const action = {
              replacement: 'We are sending a replacement today, and you do not need to return the damaged one.',
              refund: 'We have started your refund; it reaches your account within 5 working days.',
              'where-is-my-order': 'Your parcel is on its way - the tracking link follows in a separate email.',
              warranty: 'Your grinder is covered by our two-year warranty, so the repair is free.',
              other: 'A colleague will look into this and get back to you today.',
            }[intent];
            const facts = brief.facts
              .slice(0, 2)
              .map((f) => '- ' + f.replace(/ \[kb-[a-z]+\]$/, ''))
              .join('\n');
            const text = `${hello}\n\n${action}\n\n${facts ? 'What we found:\n' + facts + '\n\n' : ''}If you need anything else, just reply to this email. Our address: help@loom.example, +49 30 1234567.\n\nKind regards,\nLoom support`;
            // the reply arrives in pieces, as a streamed model answer would
            for (let i = 1; i <= 5; i++) {
              await wait(220, signal);
              progress(i / 5);
            }
            return { reply: { from: 'Loom support', text } };
          },
        },
        {
          type: 'ag-guard',
          label: 'Guardrail',
          category: 'Agents',
          color: 'chart-5',
          width: 260,
          ports: [port('reply', 'input', 'message'), port('safe', 'output', 'message')],
          defaults: { policy: 'redact contact data', maxWords: 140, blocklist: 'guarantee\nlawsuit' },
          fields: [
            { key: 'policy', label: 'Policy', kind: 'select', options: ['redact contact data', 'pass through'] },
            {
              key: 'maxWords',
              label: 'Max words',
              kind: 'slider',
              min: 40,
              max: 200,
              step: 10,
              renderLabel: (v) => (v < 70 ? span('⚠️ Max words - tight', 'var(--destructive)') : '✍️ Max words'),
            },
            // edited by the page: a click asks with workflow-field-edit, the page answers with setField()
            { key: 'blocklist', label: 'Blocked words', kind: 'textarea', editor: 'external', rows: 2 },
            {
              key: 'verdict',
              label: 'Verdict',
              kind: 'output',
              render: (v) => (v ? badge(v, v.startsWith('passed') ? 'secondary' : 'destructive') : null),
            },
          ],
          run: async (n, { inputs, signal, progress }) => {
            await work(300, signal, progress);
            const reply = first(inputs, 'reply') ?? { text: '' };
            let text = reply.text;
            const notes = [];
            if (n.data.policy === 'redact contact data') {
              const before = text;
              text = text.replace(/[\w.]+@[\w.]+\w/g, '[email]').replace(/\+?\d[\d ]{7,}\d/g, '[phone]');
              if (text !== before) notes.push('contact data redacted');
            }
            const blocked = String(n.data.blocklist)
              .split('\n')
              .map((w) => w.trim())
              .filter(Boolean)
              .filter((w) => text.toLowerCase().includes(w.toLowerCase()));
            const count = words(text).length;
            const verdict = blocked.length
              ? 'blocked: ' + blocked.join(', ')
              : count > n.data.maxWords
                ? `too long: ${count} words`
                : 'passed' + (notes.length ? ' - ' + notes.join(', ') : '');
            return { safe: { ...reply, text }, verdict };
          },
        },
        {
          type: 'ag-send',
          label: 'Send reply',
          category: 'Outputs',
          color: 'chart-1',
          width: 280,
          ports: [port('reply', 'input', 'message')],
          defaults: { channel: 'email' },
          fields: [
            { key: 'channel', label: 'Channel', kind: 'select', options: ['email', 'chat', 'ticket comment'] },
            { key: 'sent', label: 'Sent', kind: 'output', render: (v) => (v ? pre(v.text, 5) : null) },
          ],
          run: async (n, { inputs, signal, progress }) => (
            await work(200, signal, progress),
            { sent: first(inputs, 'reply') ?? null }
          ),
        },
      ];
      APPS.agents = {
        types,
        edges: [
          {
            type: 'message',
            color: 'chart-1',
            width: 2.5,
            render: (e, { value }) => (value?.text ? `≈ ${tokens(value.text)} tokens` : 'message'),
          },
          {
            type: 'context',
            color: 'chart-3',
            dash: 'dashed',
            render: (e, { value }) => (Array.isArray(value) ? value.length + ' docs' : 'documents'),
          },
          {
            type: 'record',
            color: 'chart-4',
            dash: 'dashed',
            render: (e, { value }) => (value?.id ? 'order ' + value.id : 'order record'),
          },
          {
            type: 'intent',
            color: 'chart-5',
            dash: 'dotted',
            render: (e, { value }) => (value ? '“' + value + '”' : 'intent'),
          },
          {
            type: 'brief',
            color: 'chart-2',
            render: (e, { value }) => (value?.facts ? value.facts.length + ' facts' : 'brief'),
          },
        ],
        doc: () =>
          doc(
            'support',
            'Support triage crew',
            [
              node('ag-inbox', 'inbox', 0, 120),
              node('ag-kb', 'kb', 360, 0, { groupId: 'g-data' }),
              node('ag-orders', 'orders', 360, 260, { groupId: 'g-data' }),
              node('ag-classify', 'classify', 360, 560),
              {
                ...node('ag-crew', 'crew', 720, 160),
                subgraph: sub(
                  'crew',
                  'Research crew',
                  [node('ag-research', 'research', 0, 0), node('ag-critic', 'critic', 360, 40)],
                  [edge('c1', 'research.notes', 'critic.notes')],
                  [
                    { id: 'intent', type: 'intent', endpoint: { node: 'research', port: 'intent' } },
                    { id: 'docs', type: 'context', endpoint: { node: 'research', port: 'docs' } },
                    { id: 'order', type: 'record', endpoint: { node: 'research', port: 'order' } },
                  ],
                  [{ id: 'brief', type: 'brief', endpoint: { node: 'critic', port: 'brief' } }],
                ),
              },
              node('ag-writer', 'writer', 1060, 120),
              node('ag-guard', 'guard', 1420, 120),
              node('ag-send', 'send', 1760, 120),
            ],
            [
              edge('e1', 'inbox.message', 'kb.query'),
              edge('e2', 'inbox.message', 'orders.query'),
              edge('e3', 'inbox.message', 'classify.message'),
              edge('e4', 'kb.docs', 'crew.docs'),
              edge('e5', 'orders.order', 'crew.order'),
              edge('e6', 'classify.intent', 'crew.intent'),
              edge('e7', 'crew.brief', 'writer.brief'),
              edge('e8', 'classify.intent', 'writer.intent'),
              edge('e9', 'inbox.message', 'writer.message', { route: 'orthogonal' }),
              edge('e10', 'writer.reply', 'guard.reply'),
              edge('e11', 'guard.safe', 'send.reply', { label: 'approved reply' }),
            ],
            [{ id: 'g-data', title: 'External data', x: 330, y: -60, width: 320, height: 570, color: 'chart-3' }],
          ),
        preview: (el, out) => {
          const msg = out.inbox?.message;
          const sent = out.send?.sent;
          const docs = out.kb?.docs ?? [];
          const verdict = out.guard?.verdict;
          return [
            h(
              'ul',
              { class: 'ws-chat' },
              msg && h('li', { 'data-from': 'customer' }, h('small', { text: msg.from }), msg.text),
              sent &&
                h(
                  'li',
                  { 'data-from': 'agent' },
                  h('small', { text: sent.from + ' · ' + (out.classify?.intent ?? '') }),
                  sent.text,
                ),
            ),
            verdict &&
              kv([
                ['Guardrail', verdict],
                ['Order', out.orders?.order?.status ?? '-'],
                ['Sources', docs.map((d) => d.id).join(', ') || '-'],
              ]),
          ];
        },
      };
      // the blocklist is edited by the page itself: cancel the editor's own handling and answer with setField()
      flow.addEventListener('workflow-field-edit', async (e) => {
        if (e.detail.key !== 'blocklist') return;
        e.preventDefault();
        const next = await editText('Blocked words - one per line', e.detail.value);
        if (next !== undefined) W.setField(flow, e.detail.nodeId, 'blocklist', next);
      });
    }

    // ---- b) route planner: stops become a road graph, a traffic service weighs the roads, Dijkstra finds the
    //      route, and the traffic service is asked again for the roads on that route before the ETA is final
    {
      const STOPS = [
        { name: 'Depot', x: 30, y: 160 },
        { name: 'Harbour', x: 70, y: 60 },
        { name: 'Old Town', x: 120, y: 110 },
        { name: 'Market', x: 150, y: 40 },
        { name: 'Station', x: 170, y: 150 },
        { name: 'Museum', x: 210, y: 90 },
        { name: 'Park', x: 250, y: 170 },
        { name: 'Bridge', x: 270, y: 50 },
        { name: 'Clinic', x: 310, y: 120 },
        { name: 'Campus', x: 350, y: 60 },
        { name: 'Stadium', x: 370, y: 170 },
        { name: 'Airport', x: 410, y: 110 },
      ];
      const DIJKSTRA = [
        '// graph: { stops, roads: [{ id, a, b, minutes }] } - returns the cheapest path from -> to',
        'const n = graph.stops.length, dist = Array(n).fill(Infinity), prev = Array(n).fill(-1), done = new Set();',
        'const from = graph.stops.findIndex((s) => s.name === fromName);',
        'const to = graph.stops.findIndex((s) => s.name === toName);',
        'dist[from] = 0;',
        'while (done.size < n) {',
        '  let u = -1;',
        '  for (let i = 0; i < n; i++) if (!done.has(i) && (u < 0 || dist[i] < dist[u])) u = i;',
        '  if (dist[u] === Infinity) break;',
        '  done.add(u);',
        '  for (const r of graph.roads) {',
        '    const v = r.a === u ? r.b : r.b === u ? r.a : -1;',
        '    if (v >= 0 && dist[u] + r.minutes < dist[v]) { dist[v] = dist[u] + r.minutes; prev[v] = u; }',
        '  }',
        '}',
        'const stops = [];',
        'for (let v = to; v >= 0 && stops.length <= n; v = prev[v]) stops.unshift(v);',
        'return { stops, minutes: dist[to] };',
      ].join('\n');
      // the traffic service: a slowdown factor per road for an hour - the same answer for the same question
      const factor = (road, hour) => {
        let x = (road * 2654435761 + hour * 40503) >>> 0;
        x = (x ^ (x >>> 13)) >>> 0;
        const rush = hour >= 7 && hour <= 9 ? 0.9 : hour >= 16 && hour <= 18 ? 0.7 : 0.1;
        return 1 + rush * ((x % 1000) / 1000) * 2;
      };
      const names = STOPS.map((s) => s.name);
      const types = [
        {
          type: 'al-stops',
          label: 'Stops',
          category: 'Inputs',
          color: 'chart-1',
          width: 280,
          ports: [port('stops', 'output', 'stops')],
          defaults: { stops: STOPS },
          fields: [
            {
              key: 'stops',
              label: 'Stops',
              kind: 'value',
              height: 88,
              edit: (v) =>
                editJson('Stops - name, x, y', v, (list) =>
                  Array.isArray(list) &&
                  list.length >= 2 &&
                  list.every((s) => s && typeof s.name === 'string' && Number.isFinite(s.x) && Number.isFinite(s.y))
                    ? null
                    : 'A list of at least two stops, each { "name", "x", "y" }',
                ),
              render: (v) =>
                badges(
                  (v ?? []).map((s) => s.name),
                  'outline',
                ),
              renderLabel: (v) => '📍 ' + (v?.length ?? 0) + ' stops',
            },
          ],
          run: (n) => ({ stops: n.data.stops }),
        },
        {
          type: 'al-graph',
          label: 'Road graph',
          category: 'Algorithm',
          color: 'chart-2',
          width: 260,
          ports: [port('stops', 'input', 'stops'), port('graph', 'output', 'graph')],
          defaults: { k: 3 },
          fields: [
            {
              key: 'k',
              label: 'Neighbours',
              kind: 'slider',
              min: 2,
              max: 5,
              step: 1,
              renderLabel: (v) => '🔗 Each stop to its ' + v + ' nearest',
            },
          ],
          run: async (n, { inputs, signal, progress }) => {
            await work(250, signal, progress);
            const stops = first(inputs, 'stops') ?? [];
            const seen = new Set();
            const roads = [];
            stops.forEach((s, a) => {
              const near = stops
                .map((t, b) => [b, Math.hypot(t.x - s.x, t.y - s.y)])
                .filter(([b]) => b !== a)
                .sort((p, q) => p[1] - q[1])
                .slice(0, n.data.k);
              for (const [b, d] of near) {
                const key = Math.min(a, b) + '-' + Math.max(a, b);
                if (seen.has(key)) continue;
                seen.add(key);
                roads.push({
                  id: roads.length,
                  a: Math.min(a, b),
                  b: Math.max(a, b),
                  km: Math.round((d / 10) * 10) / 10,
                });
              }
            });
            return { graph: { stops, roads } };
          },
        },
        {
          type: 'al-traffic',
          label: 'Traffic API',
          description: 'External data: GET /traffic?hour=',
          category: 'Data sources',
          color: 'chart-4',
          width: 260,
          ports: [port('graph', 'input', 'graph'), port('traffic', 'output', 'traffic')],
          defaults: { hour: 8 },
          fields: [
            {
              key: 'hour',
              label: 'Hour',
              kind: 'slider',
              min: 0,
              max: 23,
              step: 1,
              renderLabel: (v) =>
                (v >= 7 && v <= 9) || (v >= 16 && v <= 18)
                  ? span('🚦 ' + String(v).padStart(2, '0') + ':00 - rush hour', 'var(--destructive)')
                  : '🕗 ' + String(v).padStart(2, '0') + ':00',
            },
          ],
          run: async (n, { inputs, signal, progress }) => {
            await work(700, signal, progress);
            const g = first(inputs, 'graph') ?? { roads: [] };
            return {
              traffic: {
                hour: n.data.hour,
                factors: Object.fromEntries(
                  g.roads.map((r) => [r.id, Math.round(factor(r.id, n.data.hour) * 100) / 100]),
                ),
              },
            };
          },
        },
        {
          type: 'al-weigh',
          label: 'Apply traffic',
          category: 'Algorithm',
          color: 'chart-2',
          width: 240,
          ports: [
            port('graph', 'input', 'graph'),
            port('traffic', 'input', 'traffic'),
            port('weighted', 'output', 'graph'),
          ],
          defaults: { speed: 50 },
          fields: [{ key: 'speed', label: 'Free-flow speed (km/h)', kind: 'number', min: 10, max: 120 }],
          run: (n, { inputs }) => {
            const g = first(inputs, 'graph') ?? { stops: [], roads: [] };
            const t = first(inputs, 'traffic') ?? { factors: {} };
            return {
              weighted: {
                ...g,
                hour: t.hour,
                roads: g.roads.map((r) => ({
                  ...r,
                  factor: t.factors[r.id] ?? 1,
                  minutes: Math.round((r.km / n.data.speed) * 60 * (t.factors[r.id] ?? 1) * 10) / 10,
                })),
              },
            };
          },
        },
        {
          type: 'al-dijkstra',
          label: 'Dijkstra',
          category: 'Algorithm',
          color: 'chart-2',
          width: 300,
          ports: [port('graph', 'input', 'graph'), port('path', 'output', 'path')],
          defaults: { from: 'Depot', to: 'Airport', code: DIJKSTRA },
          fields: [
            { key: 'from', label: 'From', kind: 'select', options: names },
            { key: 'to', label: 'To', kind: 'select', options: names },
            {
              key: 'code',
              label: 'Algorithm',
              kind: 'textarea',
              height: 92,
              edit: (v) => editText('Dijkstra - JavaScript', v),
              render: (v) => pre(v, 4),
            },
          ],
          run: async (n, { inputs, signal, progress }) => {
            await work(300, signal, progress);
            const graph = first(inputs, 'graph');
            const found = new Function('graph', 'fromName', 'toName', n.data.code)(graph, n.data.from, n.data.to);
            if (!found || !Array.isArray(found.stops)) throw new Error('The algorithm must return { stops, minutes }');
            const roads = [];
            for (let i = 1; i < found.stops.length; i++) {
              const [a, b] = [found.stops[i - 1], found.stops[i]].sort((p, q) => p - q);
              roads.push(graph.roads.find((r) => r.a === a && r.b === b).id);
            }
            return { path: { ...found, roads, names: found.stops.map((i) => graph.stops[i].name) } };
          },
        },
        {
          type: 'al-recheck',
          label: 'Traffic API (again)',
          description: 'External data, called again for the route only',
          category: 'Data sources',
          color: 'chart-4',
          width: 260,
          ports: [port('path', 'input', 'path'), port('traffic', 'output', 'traffic')],
          defaults: { later: 1 },
          fields: [
            {
              key: 'later',
              label: 'Leave in (hours)',
              kind: 'slider',
              min: 0,
              max: 3,
              step: 1,
              renderLabel: (v) => '⏱️ Asked again for ' + (v ? '+' + v + ' h' : 'now'),
            },
          ],
          run: async (n, { inputs, signal, progress }) => {
            await work(600, signal, progress);
            const path = first(inputs, 'path') ?? { roads: [] };
            return {
              traffic: {
                later: n.data.later,
                factors: Object.fromEntries(
                  path.roads.map((id) => [id, Math.round(factor(id, (8 + n.data.later) % 24) * 100) / 100]),
                ),
              },
            };
          },
        },
        {
          type: 'al-eta',
          label: 'Final ETA',
          category: 'Algorithm',
          color: 'chart-3',
          width: 260,
          ports: [
            port('graph', 'input', 'graph'),
            port('path', 'input', 'path'),
            port('traffic', 'input', 'traffic'),
            port('eta', 'output', 'eta'),
          ],
          defaults: { budget: 120 },
          fields: [
            { key: 'budget', label: 'Budget (min)', kind: 'slider', min: 30, max: 180, step: 10 },
            {
              key: 'eta',
              label: 'ETA',
              kind: 'output',
              render: (v) =>
                v
                  ? kv([
                      ['Minutes', v.minutes],
                      ['Was', v.planned],
                      ['Within budget', v.ok ? 'yes ✅' : 'no ❌'],
                    ])
                  : null,
            },
          ],
          run: (n, { inputs }) => {
            const g = first(inputs, 'graph') ?? { roads: [], hour: 8 };
            const path = first(inputs, 'path') ?? { roads: [], minutes: 0 };
            const t = first(inputs, 'traffic') ?? { factors: {} };
            const minutes =
              Math.round(
                path.roads.reduce((sum, id) => {
                  const r = g.roads.find((x) => x.id === id);
                  return sum + (r.minutes / r.factor) * (t.factors[id] ?? r.factor);
                }, 0) * 10,
              ) / 10;
            return {
              eta: {
                minutes,
                planned: path.minutes,
                ok: minutes <= n.data.budget,
                names: path.names,
                roads: path.roads,
              },
            };
          },
        },
      ];
      APPS.algorithm = {
        types,
        edges: [
          {
            type: 'stops',
            color: 'chart-1',
            render: (e, { value }) => (Array.isArray(value) ? value.length + ' stops' : 'stops'),
          },
          {
            type: 'graph',
            color: 'chart-2',
            width: 3,
            render: (e, { value }) => (value?.roads ? value.roads.length + ' roads' : 'graph'),
          },
          {
            type: 'traffic',
            color: 'chart-4',
            dash: 'dashed',
            animated: true,
            render: (e, { value }) =>
              value?.factors ? Object.keys(value.factors).length + ' factors' : 'live traffic',
          },
          {
            type: 'path',
            color: 'chart-5',
            width: 3,
            render: (e, { value }) =>
              value?.names ? value.names.length + ' stops · ' + value.minutes + ' min' : 'path',
          },
          { type: 'eta', color: 'chart-3' },
        ],
        doc: () =>
          doc(
            'routes',
            'Delivery route planner',
            [
              node('al-stops', 'stops', 0, 80),
              node('al-graph', 'graph', 340, 80),
              node('al-traffic', 'traffic', 660, 0, { groupId: 'g-ext' }),
              node('al-weigh', 'weigh', 980, 80),
              node('al-dijkstra', 'dijkstra', 1280, 40),
              node('al-recheck', 'recheck', 1640, 0, { groupId: 'g-ext2' }),
              node('al-eta', 'eta', 1960, 80),
            ],
            [
              edge('e1', 'stops.stops', 'graph.stops'),
              edge('e2', 'graph.graph', 'traffic.graph'),
              edge('e3', 'graph.graph', 'weigh.graph', { route: 'orthogonal' }),
              edge('e4', 'traffic.traffic', 'weigh.traffic'),
              edge('e5', 'weigh.weighted', 'dijkstra.graph'),
              edge('e6', 'dijkstra.path', 'recheck.path'),
              edge('e7', 'weigh.weighted', 'eta.graph', { route: 'orthogonal' }),
              edge('e8', 'dijkstra.path', 'eta.path'),
              edge('e9', 'recheck.traffic', 'eta.traffic'),
            ],
            [
              { id: 'g-ext', title: 'Traffic service', x: 630, y: -60, width: 320, height: 300, color: 'chart-4' },
              {
                id: 'g-ext2',
                title: 'Traffic service, again',
                x: 1610,
                y: -60,
                width: 320,
                height: 300,
                color: 'chart-4',
              },
            ],
          ),
        preview: (el, out) => {
          const g = out.weigh?.weighted;
          const eta = out.eta?.eta;
          if (!g) return null;
          const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
          svg.setAttribute('viewBox', '0 0 470 210');
          svg.setAttribute('class', 'ws-map');
          svg.setAttribute('role', 'img');
          svg.setAttribute('aria-label', 'The road graph and the route');
          const add = (tag, attrs, text) => {
            const n = document.createElementNS('http://www.w3.org/2000/svg', tag);
            for (const [k, v] of Object.entries(attrs)) n.setAttribute(k, v);
            if (text) n.textContent = text;
            svg.append(n);
            return n;
          };
          for (const r of g.roads) {
            const a = g.stops[r.a];
            const b = g.stops[r.b];
            const line = add('line', { class: 'road', x1: a.x, y1: a.y, x2: b.x, y2: b.y });
            if (r.factor > 1.8) line.setAttribute('data-busy', '');
          }
          const route = out.dijkstra?.path?.stops ?? [];
          if (route.length)
            add('polyline', { class: 'route', points: route.map((i) => g.stops[i].x + ',' + g.stops[i].y).join(' ') });
          g.stops.forEach((s, i) => {
            const c = add('circle', { cx: s.x, cy: s.y, r: 4 });
            if (i === route[0] || i === route.at(-1)) c.setAttribute('data-end', '');
            add('text', { x: s.x + 6, y: s.y - 6 }, s.name);
          });
          return [
            svg,
            eta &&
              kv([
                ['Route', eta.names.join(' - ')],
                ['Planned', eta.planned + ' min'],
                ['Asked again', eta.minutes + ' min'],
                ['Within budget', eta.ok ? 'yes' : 'no'],
              ]),
          ];
        },
      };
    }

    // ---- c) 3D scene: geometry, material and motion flow into meshes, meshes and lights into a scene; three.js
    //      renders it. The shader material and the motion are subworkflows of their own
    {
      let THREE = null;
      const three = async () =>
        (THREE ??= await import('https://cdn.jsdelivr.net/npm/three@0.180.0/build/three.module.min.js'));
      const VERTEX = `varying vec3 vNormal; varying vec3 vView; varying vec3 vPos;
void main() {
  vec4 world = modelMatrix * vec4(position, 1.0);
  vPos = position;
  vNormal = normalize(normalMatrix * normal);
  vView = normalize(-(modelViewMatrix * vec4(position, 1.0)).xyz);
  gl_Position = projectionMatrix * viewMatrix * world;
}`;
      const FRAGMENT = `uniform vec3 base; uniform vec3 rim; uniform float scale; uniform float speed; uniform float power; uniform float time;
varying vec3 vNormal; varying vec3 vView; varying vec3 vPos;
float hash(vec3 p) { return fract(sin(dot(p, vec3(12.9898, 78.233, 37.719))) * 43758.5453); }
float noise(vec3 p) {
  vec3 i = floor(p), f = fract(p);
  f = f * f * (3.0 - 2.0 * f);
  return mix(mix(mix(hash(i), hash(i + vec3(1,0,0)), f.x), mix(hash(i + vec3(0,1,0)), hash(i + vec3(1,1,0)), f.x), f.y),
             mix(mix(hash(i + vec3(0,0,1)), hash(i + vec3(1,0,1)), f.x), mix(hash(i + vec3(0,1,1)), hash(i + vec3(1,1,1)), f.x), f.y), f.z);
}
void main() {
  float n = noise(vPos * scale + vec3(0.0, time * speed, 0.0));
  float fresnel = pow(1.0 - max(dot(normalize(vNormal), normalize(vView)), 0.0), power);
  gl_FragColor = vec4(mix(base * (0.55 + 0.45 * n), rim, clamp(fresnel, 0.0, 1.0)), 1.0);
}`;
      const slider = (key, label, min, max, step) => ({ key, label, kind: 'slider', min, max, step });
      const color = (key, label) => ({
        key,
        label,
        kind: 'color',
        renderLabel: (v) =>
          h('span', {}, h('span', { class: 'ws-swatch', style: 'background:' + v }), ' ' + label + ' ' + v),
      });
      const types = [
        {
          type: 'sc-knot',
          label: 'Torus knot',
          category: 'Geometry',
          color: 'chart-1',
          width: 240,
          ports: [port('geometry', 'output', 'geometry')],
          defaults: { radius: 1, tube: 0.32, p: 2, q: 3 },
          fields: [
            slider('radius', 'Radius', 0.4, 1.6, 0.1),
            slider('tube', 'Tube', 0.1, 0.6, 0.02),
            slider('q', 'Turns', 2, 7, 1),
          ],
          run: (n) => ({
            geometry: { kind: 'torusKnot', radius: n.data.radius, tube: n.data.tube, p: n.data.p, q: n.data.q },
          }),
        },
        {
          type: 'sc-box',
          label: 'Rounded box',
          category: 'Geometry',
          color: 'chart-1',
          width: 220,
          ports: [port('geometry', 'output', 'geometry')],
          defaults: { size: 1.1 },
          fields: [slider('size', 'Size', 0.4, 2, 0.1)],
          run: (n) => ({ geometry: { kind: 'box', size: n.data.size } }),
        },
        {
          type: 'sc-ico',
          label: 'Icosahedron',
          category: 'Geometry',
          color: 'chart-1',
          width: 220,
          ports: [port('geometry', 'output', 'geometry')],
          defaults: { radius: 0.8, detail: 0 },
          fields: [slider('radius', 'Radius', 0.3, 1.5, 0.1), slider('detail', 'Detail', 0, 3, 1)],
          run: (n) => ({ geometry: { kind: 'icosahedron', radius: n.data.radius, detail: n.data.detail } }),
        },
        // the shader subworkflow's parts
        {
          type: 'sc-color',
          label: 'Color',
          category: 'Shader',
          color: 'chart-4',
          width: 220,
          ports: [port('color', 'output', 'color')],
          defaults: { color: '#7c3aed' },
          fields: [color('color', 'Color')],
          run: (n) => ({ color: n.data.color }),
        },
        {
          type: 'sc-noise',
          label: 'Noise',
          category: 'Shader',
          color: 'chart-4',
          width: 220,
          ports: [port('noise', 'output', 'noise')],
          defaults: { scale: 2.5, speed: 0.6 },
          fields: [slider('scale', 'Scale', 0.5, 8, 0.5), slider('speed', 'Speed', 0, 2, 0.1)],
          run: (n) => ({ noise: { scale: n.data.scale, speed: n.data.speed } }),
        },
        {
          type: 'sc-fresnel',
          label: 'Fresnel rim',
          category: 'Shader',
          color: 'chart-4',
          width: 220,
          ports: [port('fresnel', 'output', 'fresnel')],
          defaults: { power: 2.5 },
          fields: [slider('power', 'Power', 0.5, 6, 0.5)],
          run: (n) => ({ fresnel: n.data.power }),
        },
        {
          type: 'sc-shader',
          label: 'Shader',
          category: 'Shader',
          color: 'chart-4',
          width: 240,
          ports: [
            port('base', 'input', 'color'),
            port('rim', 'input', 'color'),
            port('noise', 'input', 'noise'),
            port('fresnel', 'input', 'fresnel'),
            port('material', 'output', 'material'),
          ],
          fields: [
            {
              key: 'glsl',
              label: 'Fragment shader',
              kind: 'value',
              height: 72,
              render: () => pre(FRAGMENT.split('\n').slice(9).join('\n'), 3),
            },
          ],
          run: (n, { inputs }) => ({
            material: {
              kind: 'shader',
              base: first(inputs, 'base') ?? '#888888',
              rim: first(inputs, 'rim') ?? '#ffffff',
              noise: first(inputs, 'noise') ?? { scale: 2, speed: 0.5 },
              fresnel: first(inputs, 'fresnel') ?? 2,
            },
          }),
        },
        {
          type: 'sc-standard',
          label: 'Standard material',
          category: 'Materials',
          color: 'chart-4',
          width: 240,
          ports: [port('material', 'output', 'material')],
          defaults: { color: '#f59e0b', metalness: 0.6, roughness: 0.3 },
          fields: [
            color('color', 'Color'),
            slider('metalness', 'Metalness', 0, 1, 0.05),
            slider('roughness', 'Roughness', 0, 1, 0.05),
          ],
          run: (n) => ({
            material: {
              kind: 'standard',
              color: n.data.color,
              metalness: n.data.metalness,
              roughness: n.data.roughness,
            },
          }),
        },
        {
          type: 'sc-material',
          label: 'Glow shader',
          description: 'A subworkflow: colors, noise and a fresnel rim',
          category: 'Materials',
          color: 'chart-4',
          width: 240,
          ports: [port('material', 'output', 'material')],
          fields: [
            {
              key: 'about',
              label: 'Inside',
              kind: 'value',
              render: () => 'Two colors, noise and a rim feed the shader. Double-click to open.',
            },
          ],
        },
        // the motion subworkflow's parts
        {
          type: 'sc-spin',
          label: 'Spin',
          category: 'Motion',
          color: 'chart-5',
          width: 220,
          ports: [port('motion', 'output', 'motion')],
          defaults: { axis: 'y', speed: 0.8 },
          fields: [
            { key: 'axis', label: 'Axis', kind: 'select', options: ['x', 'y', 'z'] },
            slider('speed', 'Turns per 10 s', 0, 4, 0.2),
          ],
          run: (n) => ({ motion: { spin: { axis: n.data.axis, speed: n.data.speed } } }),
        },
        {
          type: 'sc-bob',
          label: 'Bob',
          category: 'Motion',
          color: 'chart-5',
          width: 220,
          ports: [port('motion', 'output', 'motion')],
          defaults: { height: 0.25, speed: 1.2 },
          fields: [slider('height', 'Height', 0, 1, 0.05), slider('speed', 'Speed', 0, 3, 0.1)],
          run: (n) => ({ motion: { bob: { height: n.data.height, speed: n.data.speed } } }),
        },
        {
          type: 'sc-combine',
          label: 'Combine motion',
          category: 'Motion',
          color: 'chart-5',
          width: 220,
          ports: [port('parts', 'input', 'motion', { maxConnections: 0 }), port('motion', 'output', 'motion')],
          run: (n, { inputs }) => ({ motion: Object.assign({}, ...(inputs.parts ?? [])) }),
        },
        {
          type: 'sc-motion',
          label: 'Spin and bob',
          description: 'A subworkflow: an animation',
          category: 'Motion',
          color: 'chart-5',
          width: 220,
          ports: [port('motion', 'output', 'motion')],
          fields: [
            {
              key: 'about',
              label: 'Inside',
              kind: 'value',
              render: () => 'A spin and a bob, combined. Double-click to open.',
            },
          ],
        },
        {
          type: 'sc-mesh',
          label: 'Mesh',
          category: 'Scene',
          color: 'chart-2',
          width: 240,
          ports: [
            port('geometry', 'input', 'geometry'),
            port('material', 'input', 'material'),
            port('motion', 'input', 'motion', { optional: true }),
            port('object', 'output', 'object'),
          ],
          defaults: { x: 0, y: 0, z: 0 },
          fields: [slider('x', 'X', -3, 3, 0.1), slider('y', 'Y', -2, 2, 0.1), slider('z', 'Z', -3, 3, 0.1)],
          run: (n, { inputs }) => {
            const geometry = first(inputs, 'geometry');
            const material = first(inputs, 'material');
            if (!geometry || !material) throw new Error('A mesh needs a geometry and a material');
            return {
              object: {
                name: n.title,
                geometry,
                material,
                motion: first(inputs, 'motion') ?? null,
                position: [n.data.x, n.data.y, n.data.z],
              },
            };
          },
        },
        {
          type: 'sc-light',
          label: 'Light',
          category: 'Scene',
          color: 'chart-3',
          width: 240,
          ports: [port('light', 'output', 'light')],
          defaults: { kind: 'directional', color: '#ffffff', intensity: 2.5 },
          fields: [
            { key: 'kind', label: 'Kind', kind: 'select', options: ['directional', 'point', 'ambient'] },
            color('color', 'Color'),
            slider('intensity', 'Intensity', 0, 6, 0.1),
          ],
          run: (n) => ({ light: { kind: n.data.kind, color: n.data.color, intensity: n.data.intensity } }),
        },
        {
          type: 'sc-scene',
          label: 'Scene',
          category: 'Scene',
          color: 'chart-2',
          width: 260,
          ports: [
            port('objects', 'input', 'object', { maxConnections: 0 }),
            port('lights', 'input', 'light', { maxConnections: 0 }),
            port('scene', 'output', 'scene'),
          ],
          defaults: { background: '#0f172a', fov: 45, distance: 7.5, orbit: true },
          fields: [
            color('background', 'Background'),
            slider('fov', 'Field of view', 20, 90, 1),
            slider('distance', 'Camera distance', 3, 12, 0.5),
            { key: 'orbit', label: 'Orbit the camera', kind: 'switch' },
          ],
          run: (n, { inputs }) => ({
            scene: {
              background: n.data.background,
              camera: { fov: n.data.fov, distance: n.data.distance, orbit: n.data.orbit },
              objects: inputs.objects ?? [],
              lights: inputs.lights ?? [],
            },
          }),
        },
        {
          type: 'sc-render',
          label: 'Render',
          category: 'Outputs',
          color: 'chart-2',
          width: 260,
          ports: [port('scene', 'input', 'scene')],
          defaults: { quality: 'high' },
          fields: [
            { key: 'quality', label: 'Quality', kind: 'select', options: ['high', 'low'] },
            { key: 'frame', label: 'Frame', kind: 'image', height: 150 },
          ],
          run: async (n, { inputs }) => {
            const scene = first(inputs, 'scene');
            if (!scene) throw new Error('Nothing to render - connect a scene');
            // one still frame for the card; the Preview plays the scene live
            let frame = null;
            try {
              const canvas = document.createElement('canvas');
              canvas.width = 320;
              canvas.height = 200;
              const stage = await build(scene, canvas, n.data.quality);
              stage.frame(1.2);
              frame = canvas.toDataURL('image/png');
              stage.dispose();
            } catch (err) {
              console.warn('Render: no WebGL frame', err);
            }
            return { frame, scene };
          },
        },
      ];
      // a scene description becomes a three.js scene; frame(t) draws it at time t
      const build = async (desc, canvas, quality = 'high') => {
        const T3 = await three();
        const renderer = new T3.WebGLRenderer({ canvas, antialias: quality === 'high', preserveDrawingBuffer: true });
        renderer.setPixelRatio(quality === 'high' ? Math.min(2, globalThis.devicePixelRatio || 1) : 1);
        renderer.setSize(canvas.width, canvas.height, false);
        const scene = new T3.Scene();
        scene.background = new T3.Color(desc.background);
        const camera = new T3.PerspectiveCamera(desc.camera.fov, canvas.width / canvas.height, 0.1, 100);
        const shaders = [];
        const geometryOf = (g) =>
          g.kind === 'torusKnot'
            ? new T3.TorusKnotGeometry(g.radius, g.tube, 160, 24, g.p, g.q)
            : g.kind === 'box'
              ? new T3.BoxGeometry(g.size, g.size, g.size, 4, 4, 4)
              : new T3.IcosahedronGeometry(g.radius, g.detail);
        const materialOf = (m) => {
          if (m.kind === 'standard')
            return new T3.MeshStandardMaterial({
              color: m.color,
              metalness: m.metalness,
              roughness: m.roughness,
              flatShading: false,
            });
          const mat = new T3.ShaderMaterial({
            vertexShader: VERTEX,
            fragmentShader: FRAGMENT,
            uniforms: {
              base: { value: new T3.Color(m.base) },
              rim: { value: new T3.Color(m.rim) },
              scale: { value: m.noise.scale },
              speed: { value: m.noise.speed },
              power: { value: m.fresnel },
              time: { value: 0 },
            },
          });
          shaders.push(mat);
          return mat;
        };
        const meshes = desc.objects.map((o) => {
          const mesh = new T3.Mesh(geometryOf(o.geometry), materialOf(o.material));
          mesh.position.set(...o.position);
          mesh.userData = { origin: o.position, motion: o.motion };
          scene.add(mesh);
          return mesh;
        });
        desc.lights.forEach((l, i) => {
          const light =
            l.kind === 'ambient'
              ? new T3.AmbientLight(l.color, l.intensity)
              : l.kind === 'point'
                ? new T3.PointLight(l.color, l.intensity * 8, 20)
                : new T3.DirectionalLight(l.color, l.intensity);
          if (l.kind !== 'ambient') light.position.set(i % 2 ? -4 : 4, 3 + i, i % 2 ? -2 : 4);
          scene.add(light);
        });
        const frame = (t) => {
          for (const mesh of meshes) {
            const m = mesh.userData.motion;
            if (m?.spin) mesh.rotation[m.spin.axis] = t * m.spin.speed * (Math.PI / 5);
            if (m?.bob) mesh.position.y = mesh.userData.origin[1] + Math.sin(t * m.bob.speed * Math.PI) * m.bob.height;
          }
          for (const s of shaders) s.uniforms.time.value = t;
          const a = desc.camera.orbit ? t * 0.15 : 0.6;
          camera.position.set(
            Math.sin(a) * desc.camera.distance,
            desc.camera.distance * 0.35,
            Math.cos(a) * desc.camera.distance,
          );
          camera.lookAt(0, 0, 0);
          renderer.render(scene, camera);
        };
        const dispose = () => {
          for (const mesh of meshes) {
            mesh.geometry.dispose();
            mesh.material.dispose();
          }
          renderer.dispose();
          // a context is a scarce thing: give it back now, not when the collector comes
          renderer.forceContextLoss();
        };
        return { frame, dispose, renderer, camera };
      };
      // the live stage in the Preview: one renderer at a time, released when the app changes or the scene does
      let live = null;
      const stop = () => {
        if (!live) return;
        cancelAnimationFrame(live.raf);
        live.stage?.dispose();
        live = null;
      };
      APPS.scene = {
        types,
        stop,
        edges: [
          { type: 'geometry', color: 'chart-1', render: (e, { value }) => (value?.kind ? value.kind : 'geometry') },
          {
            type: 'material',
            color: 'chart-4',
            width: 2.5,
            render: (e, { value }) => (value?.kind ? value.kind + ' material' : 'material'),
          },
          {
            type: 'motion',
            color: 'chart-5',
            dash: 'dotted',
            animated: true,
            render: (e, { value }) => (value ? Object.keys(value).join(' + ') : 'motion'),
          },
          {
            type: 'object',
            color: 'chart-2',
            width: 3,
            render: (e, { value }) => (value?.name ? value.name : 'object'),
          },
          { type: 'light', color: 'chart-3', dash: 'dashed' },
          {
            type: 'scene',
            color: 'chart-2',
            width: 4,
            render: (e, { value }) =>
              value?.objects ? value.objects.length + ' objects · ' + value.lights.length + ' lights' : 'scene',
          },
        ],
        doc: () =>
          doc(
            'scene',
            'Showcase scene',
            [
              node('sc-knot', 'knot', 0, 0),
              {
                ...node('sc-material', 'glow', 0, 320),
                subgraph: sub(
                  'glow',
                  'Glow shader',
                  [
                    node('sc-color', 'base', 0, 0, { title: 'Base color', data: { color: '#7c3aed' } }),
                    node('sc-color', 'rim', 0, 200, { title: 'Rim color', data: { color: '#22d3ee' } }),
                    node('sc-noise', 'noise', 0, 400),
                    node('sc-fresnel', 'fresnel', 0, 620),
                    node('sc-shader', 'shader', 340, 220),
                  ],
                  [
                    edge('s1', 'base.color', 'shader.base'),
                    edge('s2', 'rim.color', 'shader.rim'),
                    edge('s3', 'noise.noise', 'shader.noise'),
                    edge('s4', 'fresnel.fresnel', 'shader.fresnel'),
                  ],
                  [],
                  [{ id: 'material', type: 'material', endpoint: { node: 'shader', port: 'material' } }],
                ),
              },
              {
                ...node('sc-motion', 'motion', 0, 560),
                subgraph: sub(
                  'motion',
                  'Spin and bob',
                  [
                    node('sc-spin', 'spin', 0, 0),
                    node('sc-bob', 'bob', 0, 240),
                    node('sc-combine', 'combine', 320, 120),
                  ],
                  [edge('m1', 'spin.motion', 'combine.parts'), edge('m2', 'bob.motion', 'combine.parts')],
                  [],
                  [{ id: 'motion', type: 'motion', endpoint: { node: 'combine', port: 'motion' } }],
                ),
              },
              node('sc-mesh', 'hero', 340, 160, { title: 'Hero knot' }),
              node('sc-ico', 'ico', 0, 800),
              node('sc-standard', 'gold', 0, 1020, { title: 'Gold' }),
              node('sc-mesh', 'satellite', 340, 760, { title: 'Satellite', data: { x: 2.4, y: 0.6, z: -1 } }),
              node('sc-light', 'key', 340, 1100, { title: 'Key light' }),
              node('sc-light', 'fill', 340, 1380, {
                title: 'Fill light',
                data: { kind: 'point', color: '#38bdf8', intensity: 1.5 },
              }),
              node('sc-scene', 'scene', 700, 480),
              node('sc-render', 'render', 1060, 480),
            ],
            [
              edge('e1', 'knot.geometry', 'hero.geometry'),
              edge('e2', 'glow.material', 'hero.material'),
              edge('e3', 'motion.motion', 'hero.motion'),
              edge('e4', 'ico.geometry', 'satellite.geometry'),
              edge('e5', 'gold.material', 'satellite.material'),
              edge('e6', 'motion.motion', 'satellite.motion'),
              edge('e7', 'hero.object', 'scene.objects'),
              edge('e8', 'satellite.object', 'scene.objects'),
              edge('e9', 'key.light', 'scene.lights'),
              edge('e10', 'fill.light', 'scene.lights'),
              edge('e11', 'scene.scene', 'render.scene'),
            ],
          ),
        preview: (el, out) => {
          stop();
          const scene = out.render?.scene;
          if (!scene) return null;
          const canvas = h('canvas', { width: 640, height: 480, 'aria-label': 'The rendered scene', role: 'img' });
          const box = h('div', { class: 'ws-stage' }, canvas);
          const still = matchMedia('(prefers-reduced-motion: reduce)').matches;
          const mine = (live = { raf: 0, stage: null });
          build(scene, canvas)
            .then((stage) => {
              if (live !== mine) return stage.dispose();
              mine.stage = stage;
              root.dataset.wsScene = 'ready';
              const t0 = performance.now();
              const tick = () => {
                stage.frame(still ? 1.2 : (performance.now() - t0) / 1000);
                if (!still && live === mine) mine.raf = requestAnimationFrame(tick);
              };
              tick();
            })
            .catch((err) => box.replaceChildren(h('p', { class: 'ws-empty', text: 'No WebGL here: ' + err.message })));
          return [
            box,
            kv([
              ['Objects', scene.objects.map((o) => o.name).join(', ')],
              ['Lights', scene.lights.map((l) => l.kind).join(', ')],
              ['Camera', scene.camera.fov + '° at ' + scene.camera.distance],
            ]),
          ];
        },
      };
    }

    // ---- d) order to cash: one Order object goes from step to step; each step checks or extends it and hands on
    //      an object of a declared schema - Order, Decision, Shipment, Invoice, Notice
    {
      const SCHEMAS = {
        Order: [
          'id',
          'customer.name',
          'customer.email',
          'customer.country',
          'lines[].sku',
          'lines[].qty',
          'lines[].price',
          'shipping.carrier',
          'shipping.express',
          'total',
        ],
        Decision: ['approved', 'score', 'reason'],
        Shipment: ['tracking', 'carrier', 'parcels', 'weightKg', 'eta'],
        Invoice: ['number', 'net', 'tax', 'gross', 'due'],
        Notice: ['to', 'subject', 'body'],
      };
      const total = (o) =>
        Math.round(o.lines.reduce((s, l) => s + l.qty * l.price, 0) * 100) / 100 + (o.shipping.express ? 9.9 : 0);
      const ORDER = {
        id: 'SO-10427',
        customer: { name: 'Jonas Weber', email: 'jonas@example.com', country: 'DE' },
        lines: [
          { sku: 'BEAN-1KG', name: 'Espresso beans 1 kg', price: 24.9, qty: 2 },
          { sku: 'GRIND-H', name: 'Hand grinder', price: 59, qty: 1 },
        ],
        shipping: { carrier: 'DHL', express: false },
      };
      const orderTable = (o) =>
        h(
          'table',
          { class: 'table', 'data-size': 'sm' },
          h(
            'tbody',
            {},
            o.lines.map((l) =>
              h(
                'tr',
                {},
                h('td', { text: l.qty + ' ×' }),
                h('td', { text: l.name }),
                h('td', { text: money(l.qty * l.price), style: 'text-align: end' }),
              ),
            ),
            h(
              'tr',
              {},
              h('td', {}),
              h('th', { text: 'Total' + (o.shipping.express ? ' (express)' : '') }),
              h('th', { text: money(total(o)), style: 'text-align: end' }),
            ),
          ),
        );
      const schemaField = (name) => ({
        key: 'schema',
        label: name + ' schema',
        kind: 'value',
        height: 64,
        render: () => badges(SCHEMAS[name], 'outline'),
      });
      const types = [
        {
          type: 'bp-order',
          label: 'Order received',
          category: 'Triggers',
          color: 'chart-1',
          width: 300,
          ports: [port('order', 'output', 'Order')],
          defaults: { order: ORDER },
          fields: [
            {
              key: 'order',
              label: 'Order',
              kind: 'value',
              height: 140,
              edit: (v) => editOrder(v),
              render: (v) => (v ? orderTable(v) : null),
              renderLabel: (v) =>
                '🧾 ' + (v?.id ?? 'Order') + ' · ' + (v?.lines.length ?? 0) + ' lines · ' + v?.customer.name,
            },
          ],
          run: async (n, { signal, progress }) => (
            await work(200, signal, progress),
            { order: { ...n.data.order, total: total(n.data.order) } }
          ),
        },
        {
          type: 'bp-validate',
          label: 'Validate',
          category: 'Checks',
          color: 'chart-2',
          width: 280,
          ports: [port('order', 'input', 'Order'), port('valid', 'output', 'Order')],
          defaults: { strict: true },
          fields: [schemaField('Order'), { key: 'strict', label: 'Refuse an order without an email', kind: 'switch' }],
          run: async (n, { inputs, signal, progress }) => {
            await work(250, signal, progress);
            const o = first(inputs, 'order');
            const problems = [];
            if (!o?.lines?.length) problems.push('no lines');
            if (n.data.strict && !/^\S+@\S+\.\S+$/.test(o?.customer?.email ?? '')) problems.push('no valid email');
            if (problems.length) throw new Error('Order ' + (o?.id ?? '') + ': ' + problems.join(', '));
            return { valid: o };
          },
        },
        {
          type: 'bp-credit',
          label: 'Credit check',
          description: 'External: the credit bureau',
          category: 'Checks',
          color: 'chart-4',
          width: 260,
          ports: [port('order', 'input', 'Order'), port('decision', 'output', 'Decision')],
          defaults: { limit: 300 },
          fields: [
            {
              key: 'limit',
              label: 'Credit limit',
              kind: 'slider',
              min: 50,
              max: 1000,
              step: 50,
              renderLabel: (v) =>
                v < 150 ? span('💶 Limit ' + money(v) + ' - tight', 'var(--destructive)') : '💶 Limit ' + money(v),
            },
            {
              key: 'decision',
              label: 'Decision',
              kind: 'output',
              render: (v) =>
                v
                  ? badge(
                      v.approved ? 'approved · score ' + v.score : 'rejected: ' + v.reason,
                      v.approved ? 'secondary' : 'destructive',
                    )
                  : null,
            },
          ],
          run: async (n, { inputs, signal, progress }) => {
            await work(800, signal, progress);
            const o = first(inputs, 'order');
            const score = 620 + ((o.customer.name.length * 37) % 180);
            const approved = o.total <= n.data.limit && score >= 600;
            return {
              decision: {
                approved,
                score,
                reason: approved ? 'within limit' : o.total > n.data.limit ? 'over the limit' : 'low score',
              },
            };
          },
        },
        {
          type: 'bp-gateway',
          label: 'Approval',
          description: 'Routes the order by the decision',
          category: 'Flow',
          color: 'chart-5',
          width: 240,
          ports: [
            port('order', 'input', 'Order'),
            port('decision', 'input', 'Decision'),
            port('approved', 'output', 'Order'),
            port('rejected', 'output', 'Order'),
          ],
          fields: [
            {
              key: 'route',
              label: 'Route taken',
              kind: 'output',
              render: (v) =>
                v
                  ? badge(
                      v === 'approved' ? '✅ approved' : '⛔ rejected',
                      v === 'approved' ? 'secondary' : 'destructive',
                    )
                  : null,
            },
          ],
          run: (n, { inputs }) => {
            const o = first(inputs, 'order');
            const d = first(inputs, 'decision');
            return d?.approved ? { approved: o, route: 'approved' } : { rejected: o, route: 'rejected' };
          },
        },
        {
          type: 'bp-pick',
          label: 'Pick',
          category: 'Fulfilment',
          color: 'chart-3',
          width: 220,
          ports: [port('order', 'input', 'Order'), port('picked', 'output', 'Order')],
          defaults: { warehouse: 'Leipzig' },
          fields: [{ key: 'warehouse', label: 'Warehouse', kind: 'select', options: ['Leipzig', 'Rotterdam'] }],
          run: async (n, { inputs, signal }) => {
            const o = first(inputs, 'order');
            if (!o) return {};
            await wait(300, signal);
            return { picked: { ...o, warehouse: n.data.warehouse } };
          },
        },
        {
          type: 'bp-pack',
          label: 'Pack',
          category: 'Fulfilment',
          color: 'chart-3',
          width: 220,
          ports: [port('order', 'input', 'Order'), port('packed', 'output', 'Order')],
          defaults: { perParcel: 3 },
          fields: [{ key: 'perParcel', label: 'Items per parcel', kind: 'slider', min: 1, max: 6, step: 1 }],
          run: async (n, { inputs, signal }) => {
            const o = first(inputs, 'order');
            if (!o) return {};
            await wait(300, signal);
            const items = o.lines.reduce((s, l) => s + l.qty, 0);
            return {
              packed: {
                ...o,
                parcels: Math.ceil(items / n.data.perParcel),
                weightKg: Math.round(items * 0.9 * 10) / 10,
              },
            };
          },
        },
        {
          type: 'bp-ship',
          label: 'Ship',
          category: 'Fulfilment',
          color: 'chart-3',
          width: 220,
          ports: [port('order', 'input', 'Order'), port('shipment', 'output', 'Shipment')],
          run: async (n, { inputs, signal }) => {
            const o = first(inputs, 'order');
            if (!o) return {};
            await wait(300, signal);
            return {
              shipment: {
                tracking: o.shipping.carrier.slice(0, 2) + '-' + o.id.replace(/\D/g, '') + '-' + (o.parcels ?? 1),
                carrier: o.shipping.carrier,
                parcels: o.parcels ?? 1,
                weightKg: o.weightKg ?? 1,
                eta: o.shipping.express ? '2026-11-19' : '2026-11-21',
              },
            };
          },
        },
        {
          type: 'bp-fulfil',
          label: 'Fulfilment',
          description: 'A subworkflow: pick, pack, ship',
          category: 'Fulfilment',
          color: 'chart-3',
          width: 240,
          ports: [port('order', 'input', 'Order'), port('shipment', 'output', 'Shipment')],
          fields: [
            { key: 'about', label: 'Inside', kind: 'value', render: () => 'Pick, pack, ship. Double-click to open.' },
          ],
        },
        {
          type: 'bp-invoice',
          label: 'Invoice',
          category: 'Finance',
          color: 'chart-4',
          width: 260,
          ports: [
            port('order', 'input', 'Order'),
            port('shipment', 'input', 'Shipment'),
            port('invoice', 'output', 'Invoice'),
          ],
          defaults: { tax: '19 %', terms: '14 days' },
          fields: [
            { key: 'tax', label: 'VAT', kind: 'select', options: ['19 %', '7 %', '0 %'] },
            { key: 'terms', label: 'Terms', kind: 'select', options: ['14 days', '30 days'] },
            schemaField('Invoice'),
          ],
          run: async (n, { inputs, signal, progress }) => {
            const o = first(inputs, 'order');
            if (!o) return {};
            await work(300, signal, progress);
            const rate = parseFloat(n.data.tax) / 100;
            const net = Math.round((o.total / (1 + rate)) * 100) / 100;
            return {
              invoice: {
                number: 'INV-' + o.id.slice(3),
                net,
                tax: Math.round((o.total - net) * 100) / 100,
                gross: o.total,
                due: n.data.terms,
                order: o.id,
                tracking: first(inputs, 'shipment')?.tracking ?? null,
              },
            };
          },
        },
        {
          type: 'bp-notify',
          label: 'Notify customer',
          category: 'Messages',
          color: 'chart-1',
          width: 280,
          ports: [
            port('invoice', 'input', 'Invoice', { optional: true }),
            port('order', 'input', 'Order', { optional: true }),
            port('notice', 'output', 'Notice'),
          ],
          defaults: {
            template:
              'Hello {{name}},\nyour order {{order}} is on its way ({{tracking}}).\nInvoice {{invoice}}: {{gross}}, due in {{terms}}.',
          },
          fields: [
            {
              key: 'template',
              label: 'Template',
              kind: 'textarea',
              height: 84,
              edit: (v) => editText('Notification template', v),
              render: (v) => pre(v, 3),
            },
          ],
          run: async (n, { inputs, signal }) => {
            const inv = first(inputs, 'invoice');
            const o = first(inputs, 'order');
            if (!inv && !o) return {};
            await wait(200, signal);
            const vars = {
              name: o?.customer.name ?? '',
              order: inv?.order ?? o?.id,
              tracking: inv?.tracking ?? '-',
              invoice: inv?.number ?? '-',
              gross: inv ? money(inv.gross) : '-',
              terms: inv?.due ?? '-',
            };
            return {
              notice: {
                to: o?.customer.email ?? '',
                subject: inv ? 'Your order ' + vars.order + ' is on its way' : 'About your order ' + vars.order,
                body: n.data.template.replace(/\{\{(\w+)\}\}/g, (_, k) => vars[k] ?? ''),
              },
            };
          },
        },
        {
          type: 'bp-reject',
          label: 'Rejection notice',
          category: 'Messages',
          color: 'chart-5',
          width: 260,
          ports: [port('order', 'input', 'Order'), port('notice', 'output', 'Notice')],
          run: (n, { inputs }) => {
            const o = first(inputs, 'order');
            return o
              ? {
                  notice: {
                    to: o.customer.email,
                    subject: 'About your order ' + o.id,
                    body:
                      'We are sorry - we cannot ship order ' +
                      o.id +
                      ' on account. Pay in advance and it leaves today.',
                  },
                }
              : {};
          },
        },
        {
          type: 'bp-ledger',
          label: 'Ledger',
          category: 'Outputs',
          color: 'chart-2',
          width: 280,
          ports: [
            port('notices', 'input', 'Notice', { maxConnections: 0 }),
            port('invoice', 'input', 'Invoice', { optional: true }),
          ],
          fields: [
            { key: 'entries', label: 'Booked', kind: 'output', render: (v) => (v ? badges(v, 'outline') : null) },
          ],
          run: (n, { inputs }) => {
            const inv = first(inputs, 'invoice');
            const sent = (inputs.notices ?? []).filter(Boolean);
            return {
              entries: [
                ...(inv ? [inv.number + ' ' + money(inv.gross)] : []),
                ...sent.map((x) => 'mail: ' + x.subject),
              ],
              invoice: inv ?? null,
              notices: sent,
            };
          },
        },
      ];
      APPS.process = {
        types,
        edges: [
          {
            type: 'Order',
            color: 'chart-1',
            width: 2.5,
            render: (e, { value }) =>
              value?.id ? 'Order ' + value.id + (value.total ? ' · ' + money(value.total) : '') : 'Order',
          },
          {
            type: 'Decision',
            color: 'chart-5',
            dash: 'dotted',
            render: (e, { value }) =>
              value ? (value.approved ? 'Decision: approved' : 'Decision: ' + value.reason) : 'Decision',
          },
          {
            type: 'Shipment',
            color: 'chart-3',
            width: 2.5,
            render: (e, { value }) => (value?.tracking ? 'Shipment ' + value.tracking : 'Shipment'),
          },
          {
            type: 'Invoice',
            color: 'chart-4',
            width: 2.5,
            render: (e, { value }) => (value?.number ? value.number + ' · ' + money(value.gross) : 'Invoice'),
          },
          {
            type: 'Notice',
            color: 'chart-2',
            dash: 'dashed',
            render: (e, { value }) => (value?.subject ? '✉ ' + value.to : 'Notice'),
          },
        ],
        doc: () =>
          doc(
            'o2c',
            'Order to cash',
            [
              node('bp-order', 'order', 0, 80),
              node('bp-validate', 'validate', 380, 80),
              node('bp-credit', 'credit', 720, 0),
              node('bp-gateway', 'gateway', 1060, 120),
              {
                ...node('bp-fulfil', 'fulfil', 1380, 0),
                subgraph: sub(
                  'fulfil',
                  'Fulfilment',
                  [node('bp-pick', 'pick', 0, 0), node('bp-pack', 'pack', 300, 0), node('bp-ship', 'ship', 600, 0)],
                  [edge('f1', 'pick.picked', 'pack.order'), edge('f2', 'pack.packed', 'ship.order')],
                  [{ id: 'order', type: 'Order', endpoint: { node: 'pick', port: 'order' } }],
                  [{ id: 'shipment', type: 'Shipment', endpoint: { node: 'ship', port: 'shipment' } }],
                ),
              },
              node('bp-invoice', 'invoice', 1700, 0),
              node('bp-notify', 'notify', 2040, 0),
              node('bp-reject', 'reject', 1380, 380),
              node('bp-ledger', 'ledger', 2380, 160),
            ],
            [
              edge('e1', 'order.order', 'validate.order'),
              edge('e2', 'validate.valid', 'credit.order'),
              edge('e3', 'validate.valid', 'gateway.order', { route: 'orthogonal' }),
              edge('e4', 'credit.decision', 'gateway.decision'),
              edge('e5', 'gateway.approved', 'fulfil.order', { label: 'approved' }),
              edge('e6', 'gateway.approved', 'invoice.order', { route: 'orthogonal' }),
              edge('e7', 'fulfil.shipment', 'invoice.shipment'),
              edge('e8', 'invoice.invoice', 'notify.invoice'),
              edge('e9', 'gateway.approved', 'notify.order', { route: 'orthogonal' }),
              edge('e10', 'gateway.rejected', 'reject.order', {
                label: 'rejected',
                dash: 'dashed',
                color: 'var(--destructive)',
              }),
              edge('e11', 'notify.notice', 'ledger.notices'),
              edge('e12', 'reject.notice', 'ledger.notices'),
              edge('e13', 'invoice.invoice', 'ledger.invoice', { route: 'orthogonal' }),
            ],
          ),
        preview: (el, out) => {
          const route = out.gateway?.route;
          if (!out.order) return null;
          const step = (label, ok, text) =>
            h(
              'li',
              {},
              badge(ok ? '✓' : '·', ok ? 'secondary' : 'outline'),
              h('span', {}, h('b', { text: label }), text ? ' - ' + text : ''),
            );
          const ledger = out.ledger;
          return [
            h(
              'ol',
              { class: 'ws-steps-list' },
              step(
                'Order received',
                !!out.order,
                out.order?.order && out.order.order.id + ', ' + money(out.order.order.total),
              ),
              step('Validated', !!out.validate),
              step(
                'Credit check',
                !!out.credit,
                out.credit?.decision &&
                  (out.credit.decision.approved
                    ? 'approved, score ' + out.credit.decision.score
                    : 'rejected: ' + out.credit.decision.reason),
              ),
              step('Route', !!route, route),
              route === 'approved' && step('Shipped', !!out.fulfil?.shipment, out.fulfil?.shipment?.tracking),
              route === 'approved' &&
                step(
                  'Invoiced',
                  !!out.invoice?.invoice,
                  out.invoice?.invoice && out.invoice.invoice.number + ', ' + money(out.invoice.invoice.gross),
                ),
              step('Customer told', !!ledger?.notices?.length, ledger?.notices?.[0]?.subject),
            ),
            ledger?.invoice && h('pre', { class: 'ws-json', text: JSON.stringify(ledger.invoice, null, 2) }),
          ];
        },
      };
    }

    // ---- e) neural calculator: a ReLU network whose 973 weights and biases are written, not trained. A small
    //      weight-space program below lays them out; every node of the workflow is one block of units with its
    //      weights, every connection carries a block's activations, and the readout heads are matrices
    {
      // units: [id, block, bias, [[source id, weight], ...]] in the order they are evaluated; 0-5 are the inputs
      // A, B and the op as one-hot (+, −, ×, ÷)
      const program = () => {
        const units = [];
        let block = 'in';
        const lin = (terms = [], b = 0) => ({ t: new Map(terms), b });
        const add = (...xs) => {
          const t = new Map();
          let b = 0;
          for (const x of xs) {
            b += x.b;
            for (const [k, w] of x.t) t.set(k, (t.get(k) ?? 0) + w);
          }
          for (const [k, w] of t) if (w === 0) t.delete(k);
          return { t, b };
        };
        const mul = (x, s) => ({ t: new Map([...x.t].map(([k, w]) => [k, w * s])), b: x.b * s });
        const c = (v) => lin([], v);
        const input = () => (units.push([units.length, 'in', 0, []]), lin([[units.length - 1, 1]]));
        const relu = (x) => (units.push([units.length, block, x.b, [...x.t]]), lin([[units.length - 1, 1]]));
        // H(x >= k) for whole numbers: relu(x - k + 1) - relu(x - k) is 1 or 0 - the network's only "if"
        const step = (x, k) => add(relu(add(x, c(1 - k))), mul(relu(add(x, c(-k))), -1));
        // x (0 <= x < M) when the gate g is 1, else 0
        const gate = (x, g, M) => relu(add(x, mul(g, M), c(-M)));
        const A = input();
        const B = input();
        const OP = [input(), input(), input(), input()];
        // the bits of A, highest first
        block = 'bits';
        let rest = A;
        const bits = [];
        for (let k = 6; k >= 0; k--) {
          bits[k] = step(rest, 2 ** k);
          rest = relu(add(rest, mul(bits[k], -(2 ** k))));
        }
        // A × B = Σ 2^k · (B when bit k of A)
        block = 'multiply';
        const product = add(...bits.map((bit, k) => mul(gate(B, bit, 128), 2 ** k)));
        // floor(A / B): restoring long division over the bits of A
        block = 'divide';
        let R = c(0);
        let q = c(0);
        for (let k = 6; k >= 0; k--) {
          R = relu(add(mul(R, 2), bits[k]));
          const t = step(add(R, mul(B, -1)), 0);
          q = add(q, mul(t, 2 ** k));
          R = add(R, mul(gate(B, t, 128), -1));
        }
        // two decimals: ten times the remainder against 1B ... 9B
        block = 'decimals';
        const dec = [];
        for (let d = 0; d < 2; d++) {
          R = relu(mul(R, 10));
          const hs = [];
          for (let j = 1; j <= 9; j++) hs.push(step(add(R, mul(B, -j)), 0));
          dec.push(add(...hs));
          R = add(R, mul(add(...hs.map((x) => gate(B, x, 128))), -1));
        }
        // the op picks one result (times 100: two decimals), subtraction keeps its sign in two halves
        block = 'select';
        const M = 1000001;
        const pos = add(
          gate(mul(add(A, B), 100), OP[0], M),
          gate(mul(add(A, mul(B, -1)), 100), OP[1], M),
          gate(mul(product, 100), OP[2], M),
          gate(add(mul(q, 100), mul(dec[0], 10), dec[1]), OP[3], M),
        );
        const neg = gate(mul(add(B, mul(A, -1)), 100), OP[1], M);
        block = 'flags';
        const sign = step(neg, 1);
        const err = relu(add(OP[3], mul(step(B, 1), -1)));
        // the decimal digits of |result|, highest first: each place's steps make its one-hot readout
        const heads = {};
        block = 'p6';
        let mag = relu(add(pos, neg));
        for (let p = 6; p >= 0; p--) {
          block = 'p' + p;
          const hs = [];
          for (let j = 1; j <= (p === 6 ? 1 : 9); j++) hs.push(step(mag, j * 10 ** p));
          heads['p' + p] = Array.from({ length: 10 }, (_, j) =>
            add(j === 0 ? c(1) : (hs[j - 1] ?? c(0)), mul(hs[j] ?? c(0), -1)),
          );
          if (p > 0) mag = relu(add(mag, mul(add(...hs), -(10 ** p))));
        }
        heads.flags = [sign, err];
        const row = (x) => [x.b, [...x.t]];
        return { units, heads: Object.fromEntries(Object.entries(heads).map(([k, rows]) => [k, rows.map(row)])) };
      };
      const BLOCKS = {
        bits: [
          'Bits of A',
          'Peels the bits of A off, highest first. A step H(x ≥ 2^k) is two ReLUs - relu(x − 2^k + 1) − relu(x − 2^k) - and exact on whole numbers; what is left goes on.',
        ],
        multiply: [
          'Multiply',
          'A × B = Σ 2^k · (B when bit k of A is 1). A gate relu(B + 128·bit − 128) lets B through only when its bit is set.',
        ],
        divide: [
          'Divide',
          'Restoring long division over the bits of A: double the remainder, add the next bit, compare it with B (a step) and take B away through a gate.',
        ],
        decimals: [
          'Two decimals',
          'Ten times the remainder against 1·B ... 9·B: nine steps add up to the next digit, twice.',
        ],
        select: [
          'Select the op',
          'Every result is gated by its one-hot op with a large M; subtraction keeps its sign in two halves. All results are times 100.',
        ],
        flags: ['Sign and ÷ 0', 'The sign of the result; with ÷ and B = 0 the error unit fires (B ≥ 1 is a step).'],
      };
      for (let p = 6; p >= 0; p--)
        BLOCKS['p' + p] = [
          'Digit 10^' + p,
          'Nine steps of the magnitude against 1·10^' +
            p +
            ' ... 9·10^' +
            p +
            '; their differences are the one-hot readout matrix of this place.',
        ];
      const net = program();
      // how deep it is: a unit sits one layer above the deepest unit it reads
      const layer = new Map([0, 1, 2, 3, 4, 5].map((k) => [k, 0]));
      for (const [id, , , ws] of net.units) if (id > 5) layer.set(id, 1 + Math.max(...ws.map(([k]) => layer.get(k))));
      const DEPTH = Math.max(...layer.values());
      const params = (units, heads = []) =>
        units.reduce((s, u) => s + u[3].length + (u[2] !== 0 ? 1 : 0), 0) +
        heads.reduce((s, r) => s + r[1].length + (r[0] !== 0 ? 1 : 0), 0);
      // one forward pass over a block: its units in order, from the activations that arrived
      const forward = (units, act) => {
        const ids = [];
        const v = [];
        for (const [id, , b, ws] of units) {
          let s = b;
          for (const [k, w] of ws) s += w * (act.get(k) ?? 0);
          const y = s > 0 ? s : 0;
          act.set(id, y);
          ids.push(id);
          v.push(y);
        }
        return { ids, v };
      };
      const readout = (rows, act) => rows.map(([b, ws]) => ws.reduce((s, [k, w]) => s + w * (act.get(k) ?? 0), b));
      const merge = (inputs) => {
        const act = new Map();
        for (const list of Object.values(inputs))
          for (const t of list) if (t?.ids) t.ids.forEach((id, i) => act.set(id, t.v[i]));
        return act;
      };
      // a block's weights as a heat map: a row per unit, a column per source it reads; blue +, red −
      const heat = (units) => {
        const cols = [...new Set(units.flatMap((u) => u[3].map(([k]) => k)))].sort((a, b) => a - b);
        const col = new Map(cols.map((k, i) => [k, i]));
        const canvas = h('canvas', {
          class: 'ws-heat',
          width: Math.max(1, cols.length),
          height: Math.max(1, units.length),
          'aria-hidden': 'true',
        });
        const ctx = canvas.getContext('2d');
        units.forEach((u, r) =>
          u[3].forEach(([k, w]) => {
            const a = Math.min(1, 0.25 + Math.log10(1 + Math.abs(w)) / 4);
            ctx.fillStyle = w > 0 ? `rgba(37, 99, 235, ${a})` : `rgba(220, 38, 38, ${a})`;
            ctx.fillRect(col.get(k), r, 1, 1);
          }),
        );
        return canvas;
      };
      const bars = (t) => {
        const top = Math.max(1, ...t.v);
        return h(
          'div',
          { class: 'ws-bars', 'aria-hidden': 'true' },
          t.v
            .slice(0, 80)
            .map((v) => h('i', { style: `height: ${Math.max(4, (v / top) * 100)}%; opacity: ${v > 0 ? 1 : 0.2}` })),
        );
      };
      const checkUnits = (list) =>
        Array.isArray(list) &&
        list.every(
          (u) =>
            Array.isArray(u) &&
            u.length === 4 &&
            Number.isFinite(u[0]) &&
            Number.isFinite(u[2]) &&
            Array.isArray(u[3]) &&
            u[3].every((p) => Array.isArray(p) && p.length === 2 && p.every(Number.isFinite)),
        )
          ? null
          : 'A list of units [id, block, bias, [[source, weight], ...]]';
      const unitsField = {
        key: 'units',
        label: 'Weights',
        kind: 'value',
        height: 64,
        edit: (v, ctx) => editJson(ctx.node.title + ' - units [id, block, bias, [[source, weight]]]', v, checkUnits),
        render: (v) => (Array.isArray(v) ? heat(v) : null),
        renderLabel: (v, ctx) =>
          '🧠 ' + (v?.length ?? 0) + ' units · ' + params(v ?? [], ctx.node.data.head ?? []) + ' parameters',
      };
      const aboutField = {
        key: 'about',
        label: 'Computes',
        kind: 'value',
        height: 76,
        render: (v) => h('span', { class: 'text-xs', text: v }),
      };
      const actField = {
        key: 'out',
        label: 'Activations',
        kind: 'output',
        height: 40,
        render: (v) => (v?.v ? bars(v) : null),
      };
      const digitText = (d) => (Array.isArray(d) ? String(d.indexOf(1)) : '');
      // the readout: one row of the matrix per place, the lit cell is the digit
      const matrix = (digits, flags) => {
        // ÷ 0: the digits carry no number - the error head says so, the matrix stays dark
        if (flags?.[1] === 1) digits = null;
        const places = [6, 5, 4, 3, 2, 1, 0];
        return h(
          'table',
          { class: 'ws-matrix', 'aria-label': 'Readout matrix' },
          h(
            'thead',
            {},
            h(
              'tr',
              {},
              h('th', {}),
              Array.from({ length: 10 }, (_, j) => h('th', { text: String(j) })),
            ),
          ),
          h(
            'tbody',
            {},
            places.map((p) =>
              h(
                'tr',
                {},
                h('th', { text: '10^' + (p - 2) }),
                Array.from({ length: 10 }, (_, j) =>
                  h('td', {
                    'data-on': digits?.['d' + p]?.[j] === 1,
                    text: digits?.['d' + p]?.[j] === 1 ? String(j) : '',
                  }),
                ),
              ),
            ),
          ),
        );
      };
      const decode = (digits, flags) => {
        if (flags?.[1] === 1) return 'undefined (÷ 0)';
        const n = [6, 5, 4, 3, 2, 1, 0].map((p) => digits['d' + p].indexOf(1)).join('');
        const whole = n.slice(0, 5).replace(/^0+(?=\d)/, '');
        return (flags?.[0] === 1 ? '−' : '') + whole + '.' + n.slice(5);
      };
      const OPS = ['+', '−', '×', '÷'];
      const types = [
        {
          type: 'nn-number',
          label: 'Number',
          category: 'Inputs',
          color: 'chart-1',
          width: 220,
          ports: [port('out', 'output', 'tensor')],
          defaults: { unit: 0, value: 42 },
          fields: [{ key: 'value', label: '🔢 Value', kind: 'slider', min: 0, max: 100, step: 1 }],
          run: (n) => ({ out: { ids: [n.data.unit], v: [n.data.value] } }),
        },
        {
          type: 'nn-op',
          label: 'Operation',
          category: 'Inputs',
          color: 'chart-1',
          width: 220,
          ports: [port('out', 'output', 'tensor')],
          defaults: { op: '÷' },
          fields: [
            {
              key: 'op',
              label: 'Operation',
              kind: 'select',
              options: OPS,
              renderLabel: (v) => 'One-hot ' + OPS.map((o) => (o === v ? '1' : '0')).join(' '),
            },
          ],
          run: (n) => ({ out: { ids: [2, 3, 4, 5], v: OPS.map((o) => (o === n.data.op ? 1 : 0)) } }),
        },
        {
          type: 'nn-block',
          label: 'Block',
          category: 'Layers',
          color: 'chart-2',
          width: 260,
          ports: [port('out', 'output', 'tensor')],
          fields: [aboutField, unitsField, actField],
          run: (n, { inputs }) => {
            const act = merge(inputs);
            const out = forward(n.data.units, act);
            return n.data.head ? { out, [n.data.headPort]: readout(n.data.head, act) } : { out };
          },
        },
        {
          type: 'nn-readout',
          label: 'Readout',
          category: 'Outputs',
          color: 'chart-5',
          width: 300,
          ports: [6, 5, 4, 3, 2, 1, 0]
            .map((p) => port('d' + p, 'input', 'onehot'))
            .concat([port('flags', 'input', 'onehot')]),
          fields: [
            {
              key: 'matrix',
              label: 'Readout matrices',
              kind: 'output',
              height: 200,
              render: (v) => (v ? matrix(v.digits, v.flags) : matrix(null)),
            },
            {
              key: 'result',
              label: 'Result',
              kind: 'output',
              render: (v) => (v ? h('span', { class: 'ws-result', text: v }) : null),
            },
          ],
          run: (n, { inputs }) => {
            const digits = Object.fromEntries(
              [6, 5, 4, 3, 2, 1, 0].map((p) => ['d' + p, first(inputs, 'd' + p) ?? Array(10).fill(0)]),
            );
            const flags = first(inputs, 'flags') ?? [0, 0];
            return { matrix: { digits, flags }, result: decode(digits, flags) };
          },
        },
      ];
      // the document: a node per block, a connection from every block a block reads; columns by depth
      const network = () => {
        const owner = new Map(net.units.map((u) => [u[0], u[1]]));
        owner.set(0, 'a');
        owner.set(1, 'b');
        for (const k of [2, 3, 4, 5]) owner.set(k, 'op');
        const order = [
          'bits',
          'multiply',
          'divide',
          'decimals',
          'select',
          'flags',
          'p6',
          'p5',
          'p4',
          'p3',
          'p2',
          'p1',
          'p0',
        ];
        const reads = new Map(order.map((b) => [b, new Set()]));
        for (const [, b, , ws] of net.units)
          if (b !== 'in') for (const [k] of ws) if (owner.get(k) !== b) reads.get(b).add(owner.get(k));
        for (const [k, rows] of Object.entries(net.heads))
          for (const [, ws] of rows)
            for (const [src] of ws) if (owner.get(src) !== k && k !== 'flags') reads.get(k).add(owner.get(src));
        const depth = new Map([
          ['a', 0],
          ['b', 0],
          ['op', 0],
        ]);
        for (const b of order) depth.set(b, 1 + Math.max(...[...reads.get(b)].map((s) => depth.get(s))));
        const rows = new Map();
        const at = (id) => {
          const d = depth.get(id);
          const r = rows.get(d) ?? 0;
          rows.set(d, r + 1);
          return [d * 340, r * 470];
        };
        const nodes = [
          node('nn-number', 'a', ...at('a'), { title: 'A', data: { unit: 0, value: 42 } }),
          node('nn-number', 'b', ...at('b'), { title: 'B', data: { unit: 1, value: 8 } }),
          node('nn-op', 'op', ...at('op'), { title: 'Operation' }),
        ];
        const edges = [];
        for (const b of order) {
          const sources = [...reads.get(b)];
          const units = net.units.filter((u) => u[1] === b);
          const head = net.heads[b === 'flags' ? 'flags' : b];
          const headPort = b === 'flags' ? 'flags' : b.startsWith('p') ? 'digit' : undefined;
          nodes.push(
            node('nn-block', b, ...at(b), {
              title: BLOCKS[b][0],
              ports: [
                ...sources.map((s) => port('in-' + s, 'input', 'tensor')),
                port('out', 'output', 'tensor'),
                ...(headPort ? [port(headPort, 'output', 'onehot')] : []),
              ],
              data: { about: BLOCKS[b][1], units, ...(head && headPort ? { head, headPort } : {}) },
            }),
          );
          for (const s of sources) edges.push(edge(`e-${s}-${b}`, s + '.out', b + '.in-' + s));
        }
        nodes.push(node('nn-readout', 'readout', (Math.max(...depth.values()) + 1) * 340, 0, { title: 'Readout' }));
        for (let p = 6; p >= 0; p--) edges.push(edge('e-r' + p, 'p' + p + '.digit', 'readout.d' + p));
        edges.push(edge('e-rf', 'flags.flags', 'readout.flags'));
        return doc('neural', 'Neural calculator', nodes, edges, [], 1.25);
      };
      // every A, B and op through the network as it stands in the editor - the proof it computes, not guesses
      const checkAll = async (report) => {
        const d = W.export(flow);
        const all = d.nodes.filter((n) => n.type === 'nn-block');
        const units = all.flatMap((n) => n.data.units).sort((a, b) => a[0] - b[0]);
        const heads = Object.fromEntries(all.filter((n) => n.data.head).map((n) => [n.id, n.data.head]));
        let exact = 0;
        let first;
        let done = 0;
        for (let op = 0; op < 4; op++)
          for (let a = 0; a <= 100; a++) {
            for (let b = 0; b <= 100; b++) {
              const act = new Map([
                [0, a],
                [1, b],
                [2, op === 0 ? 1 : 0],
                [3, op === 1 ? 1 : 0],
                [4, op === 2 ? 1 : 0],
                [5, op === 3 ? 1 : 0],
              ]);
              forward(units, act);
              const digits = Object.fromEntries(
                [6, 5, 4, 3, 2, 1, 0].map((p) => ['d' + p, readout(heads['p' + p] ?? [], act)]),
              );
              const flags = readout(heads.flags ?? [], act);
              const want =
                op === 3 && b === 0
                  ? 'undefined (÷ 0)'
                  : (() => {
                      const v =
                        op === 0
                          ? 100 * (a + b)
                          : op === 1
                            ? 100 * (a - b)
                            : op === 2
                              ? 100 * a * b
                              : Math.floor((100 * a) / b);
                      return (
                        (v < 0 ? '−' : '') +
                        String(Math.floor(Math.abs(v) / 100)) +
                        '.' +
                        String(Math.abs(v) % 100).padStart(2, '0')
                      );
                    })();
              let got;
              try {
                got = decode(digits, flags);
              } catch {
                got = '?';
              }
              if (got === want) exact++;
              else first ??= `${a} ${OPS[op]} ${b} gave ${got}, wants ${want}`;
              done++;
            }
            if (a % 20 === 0) {
              report(done);
              await wait(0);
            }
          }
        return { exact, total: done, first };
      };
      APPS.neural = {
        types,
        edges: [
          {
            type: 'tensor',
            color: 'chart-2',
            width: 2.5,
            render: (e, { value }) =>
              value?.v ? '[' + value.v.length + '] · ' + value.v.filter((x) => x > 0).length + ' on' : 'tensor',
          },
          {
            type: 'onehot',
            color: 'chart-5',
            dash: 'dashed',
            render: (e, { value }) =>
              Array.isArray(value)
                ? value.length === 2
                  ? 'sign ' + value[0] + ' · ÷0 ' + value[1]
                  : 'digit ' + digitText(value)
                : 'one-hot',
          },
        ],
        doc: network,
        preview: (el, out) => {
          const r = out.readout;
          const total = params(net.units, Object.values(net.heads).flat());
          const a = out.a?.out?.v[0];
          const b = out.b?.out?.v[0];
          const op = out.op?.out?.v.indexOf(1);
          const said = h('p', { class: 'ws-empty', 'data-ws-check': '' });
          const check = h(
            'button',
            { class: 'btn', 'data-variant': 'outline', 'data-size': 'sm', type: 'button' },
            'Check all 40,804 inputs',
          );
          check.addEventListener('click', async () => {
            check.disabled = true;
            const res = await checkAll((n) => (said.textContent = n.toLocaleString('en-US') + ' of 40,804 ...'));
            said.textContent =
              `${res.exact.toLocaleString('en-US')} of ${res.total.toLocaleString('en-US')} exact` +
              (res.first ? ' - first miss: ' + res.first : '');
            check.disabled = false;
          });
          return [
            r &&
              h(
                'div',
                {},
                h('div', {
                  class: 'text-xs text-muted-foreground',
                  text: a !== undefined ? `${a} ${OPS[op]} ${b} =` : '',
                }),
                h('div', { class: 'ws-result', 'data-ws-result': '', text: r.result }),
              ),
            r && matrix(r.matrix.digits, r.matrix.flags),
            kv([
              ['Weights and biases', total.toLocaleString('en-US')],
              ['Units', String(net.units.length - 6)],
              ['Layers deep', String(DEPTH)],
              ['Readout heads', '7 matrices 10 × n, and sign and ÷ 0'],
            ]),
            h('div', { class: 'flex flex-wrap items-center gap-2' }, check),
            said,
          ];
        },
      };
    }

    // ---- f) BDI-II form logic: the 21 items of the Beck Depression Inventory as nodes - each its options and its
    //      score - and every rule as a node after them: the highest statement counts, items 16 and 18 carry a
    //      direction (sleep: a = more, b = less; appetite: a = less, b = more), item 9 raises a safety flag, missing answers are prorated or stop the
    //      score, and the total falls into a band. The item statements are the publisher's (Pearson) - the nodes
    //      carry the item names and short anchors of our own; a licensed form pastes its wording in
    {
      const ITEMS = [
        'Sadness',
        'Pessimism',
        'Past failure',
        'Loss of pleasure',
        'Guilty feelings',
        'Punishment feelings',
        'Self-dislike',
        'Self-criticalness',
        'Suicidal thoughts or wishes',
        'Crying',
        'Agitation',
        'Loss of interest',
        'Indecisiveness',
        'Worthlessness',
        'Loss of energy',
        'Changes in sleeping pattern',
        'Irritability',
        'Changes in appetite',
        'Concentration difficulty',
        'Tiredness or fatigue',
        'Loss of interest in sex',
      ];
      // sleep and appetite answer 1a / 1b ... 3a / 3b: which letter means more
      const MORE = { 16: 'a', 18: 'b' };
      const ANCHOR = ['not at all', 'mild', 'moderate', 'severe'];
      const BANDS = [
        { from: 0, to: 13, band: 'minimal' },
        { from: 14, to: 19, band: 'mild' },
        { from: 20, to: 28, band: 'moderate' },
        { from: 29, to: 63, band: 'severe' },
      ];
      const scoreOf = (answer) => (answer === '–' || answer == null ? null : Number(String(answer)[0]));
      const directionOf = (n, answer) =>
        /[ab]$/.test(String(answer)) ? (String(answer).endsWith(MORE[n]) ? 'more' : 'less') : null;
      const answerLabel = (v, ctx) => {
        const n = ctx.node.data.n;
        const s = scoreOf(v);
        const d = directionOf(n, v);
        const dir = d ? ', ' + d : '';
        const text = s === null ? 'Item ' + n + ' - not answered' : 'Item ' + n + ' - ' + s + ' = ' + ANCHOR[s] + dir;
        return n === 9 && s ? span('⚠ ' + text, 'var(--destructive)') : text;
      };
      const item = (type, label, options) => ({
        type,
        label,
        category: 'BDI-II items',
        color: 'chart-1',
        width: 230,
        ports: [port('score', 'output', 'score')],
        defaults: { n: 1, answer: '–' },
        fields: [{ key: 'answer', label: 'Answer', kind: 'select', options, renderLabel: answerLabel }],
        run: (n) => ({
          score: { n: n.data.n, score: scoreOf(n.data.answer), dir: directionOf(n.data.n, n.data.answer) },
        }),
      });
      const types = [
        item('bdi-item', 'BDI item', ['–', '0', '1', '2', '3']),
        item('bdi-item-dir', 'BDI item with a direction', ['–', '0', '1a', '1b', '2a', '2b', '3a', '3b']),
        {
          type: 'bdi-rules',
          label: 'Instructions',
          category: 'BDI-II rules',
          color: 'chart-3',
          width: 280,
          ports: [],
          run: () => ({}),
          fields: [
            {
              key: 'about',
              label: 'How it is answered',
              kind: 'value',
              height: 110,
              render: () =>
                h('span', {
                  class: 'text-xs',
                  text: 'Past two weeks, including today. One answer per item; where two statements fit, the higher one counts. Items 16 and 18 also say the direction: a = more, b = less. Not a diagnosis - a clinician reads every result.',
                }),
            },
          ],
        },
        {
          type: 'bdi-sum',
          label: 'Sum',
          category: 'BDI-II rules',
          color: 'chart-2',
          width: 240,
          ports: [port('items', 'input', 'score', { maxConnections: 0 }), port('sum', 'output', 'sum')],
          fields: [
            {
              key: 'sum',
              label: 'Raw sum',
              kind: 'output',
              render: (v) =>
                v
                  ? kv([
                      ['Sum', v.raw],
                      ['Answered', v.answered + ' of 21'],
                    ])
                  : null,
            },
          ],
          run: (n, { inputs }) => {
            const items = inputs.items ?? [];
            const answered = items.filter((i) => i.score !== null);
            return {
              sum: {
                raw: answered.reduce((s, i) => s + i.score, 0),
                answered: answered.length,
                missing: items
                  .filter((i) => i.score === null)
                  .map((i) => i.n)
                  .sort((a, b) => a - b),
              },
            };
          },
        },
        {
          type: 'bdi-missing',
          label: 'Missing answers',
          category: 'BDI-II rules',
          color: 'chart-4',
          width: 260,
          ports: [port('sum', 'input', 'sum'), port('total', 'output', 'total')],
          defaults: { prorate: 2 },
          fields: [
            {
              key: 'prorate',
              label: 'Prorate up to',
              kind: 'slider',
              min: 0,
              max: 4,
              step: 1,
              renderLabel: (v) =>
                v ? 'Prorate up to ' + v + ' missing (this form’s rule)' : 'No missing answer allowed',
            },
          ],
          run: (n, { inputs }) => {
            const s = first(inputs, 'sum') ?? { raw: 0, answered: 0, missing: [] };
            if (!s.missing.length) return { total: { score: s.raw, missing: [], prorated: false } };
            if (s.missing.length > n.data.prorate)
              return { total: { score: null, missing: s.missing, prorated: false } };
            return { total: { score: Math.round((s.raw * 21) / s.answered), missing: s.missing, prorated: true } };
          },
        },
        {
          type: 'bdi-band',
          label: 'Severity band',
          category: 'BDI-II rules',
          color: 'chart-5',
          width: 260,
          ports: [port('total', 'input', 'total'), port('result', 'output', 'result')],
          defaults: { bands: BANDS },
          fields: [
            {
              key: 'bands',
              label: 'Cut-offs',
              kind: 'value',
              height: 96,
              edit: (v) =>
                editJson('Severity bands - from, to, band', v, (list) =>
                  Array.isArray(list) &&
                  list.length &&
                  list.every(
                    (b) =>
                      Number.isInteger(b.from) &&
                      Number.isInteger(b.to) &&
                      b.from <= b.to &&
                      typeof b.band === 'string',
                  )
                    ? null
                    : 'A list of { "from", "to", "band" } with whole numbers',
                ),
              render: (v) => kv((v ?? []).map((b) => [b.from + ' - ' + b.to, b.band])),
            },
          ],
          run: (n, { inputs }) => {
            const t = first(inputs, 'total') ?? { score: null };
            const band =
              t.score === null
                ? 'incomplete'
                : (n.data.bands.find((b) => t.score >= b.from && t.score <= b.to)?.band ?? 'out of range');
            return { result: { ...t, band, bands: n.data.bands } };
          },
        },
        {
          type: 'bdi-safety',
          label: 'Item 9 check',
          category: 'BDI-II rules',
          color: 'chart-5',
          width: 240,
          ports: [port('item9', 'input', 'score'), port('flag', 'output', 'flag')],
          fields: [
            {
              key: 'rule',
              label: 'Rule',
              kind: 'value',
              height: 52,
              render: () =>
                h('span', {
                  class: 'text-xs',
                  text: 'Any answer above 0 flags the form for a clinician today; 2 or 3 at once.',
                }),
            },
          ],
          run: (n, { inputs }) => {
            const s = first(inputs, 'item9')?.score;
            return {
              flag:
                s === null || s === undefined
                  ? 'item 9 not answered - ask'
                  : s === 0
                    ? 'none'
                    : s === 1
                      ? 'review today'
                      : 'urgent - contact now',
            };
          },
        },
        {
          type: 'bdi-direction',
          label: 'Sleep and appetite',
          category: 'BDI-II rules',
          color: 'chart-4',
          width: 240,
          ports: [
            port('sleep', 'input', 'score'),
            port('appetite', 'input', 'score'),
            port('notes', 'output', 'notes'),
          ],
          run: (n, { inputs }) => {
            const say = (what, i) =>
              i?.score
                ? what + ' ' + i.dir + ' (' + i.score + ')'
                : i?.score === 0
                  ? what + ' as usual'
                  : what + ': not answered';
            return { notes: [say('sleeps', first(inputs, 'sleep')), say('eats', first(inputs, 'appetite'))] };
          },
        },
        {
          type: 'bdi-report',
          label: 'Report',
          category: 'Outputs',
          color: 'chart-2',
          width: 280,
          ports: [port('result', 'input', 'result'), port('flag', 'input', 'flag'), port('notes', 'input', 'notes')],
          fields: [
            {
              key: 'report',
              label: 'Result',
              kind: 'output',
              render: (v) =>
                v
                  ? kv([
                      ['Total', v.total ?? '-'],
                      ['Band', v.band],
                      ['Item 9', v.flag],
                    ])
                  : null,
            },
          ],
          run: (n, { inputs }) => {
            const r = first(inputs, 'result') ?? { score: null, band: 'incomplete', missing: [] };
            return {
              report: {
                total: r.score,
                band: r.band,
                prorated: r.prorated,
                missing: r.missing,
                flag: first(inputs, 'flag') ?? 'none',
                notes: first(inputs, 'notes') ?? [],
              },
            };
          },
        },
      ];
      // an example form: a moderate pattern, item 9 at 0, sleeps less, eats less
      const ANSWERS = [
        '2',
        '1',
        '1',
        '2',
        '1',
        '0',
        '1',
        '1',
        '0',
        '1',
        '1',
        '2',
        '1',
        '1',
        '2',
        '2b',
        '1',
        '1a',
        '2',
        '2',
        '0',
      ];
      APPS.bdi = {
        types,
        edges: [
          // the 21 lines into the sum stay unlabelled (each card says its answer); the three into a rule say it
          {
            type: 'score',
            color: 'chart-1',
            render: (e, { value }) =>
              e.target.node === 'sum' || !value
                ? null
                : value.score === null
                  ? '–'
                  : String(value.score) + (value.dir ? ' ' + value.dir : ''),
          },
          {
            type: 'sum',
            color: 'chart-2',
            width: 3,
            render: (e, { value }) => (value ? value.raw + ' from ' + value.answered + ' items' : 'sum'),
          },
          {
            type: 'total',
            color: 'chart-4',
            width: 3,
            render: (e, { value }) =>
              value
                ? value.score === null
                  ? 'incomplete'
                  : value.score + (value.prorated ? ' prorated' : '')
                : 'total',
          },
          { type: 'result', color: 'chart-5', width: 3, render: (e, { value }) => (value ? value.band : 'band') },
          {
            type: 'flag',
            color: 'var(--destructive)',
            dash: 'dotted',
            render: (e, { value }) => (value ? 'item 9: ' + value : 'safety'),
          },
          {
            type: 'notes',
            color: 'chart-4',
            dash: 'dashed',
            render: (e, { value }) => (value ? value.join(' · ') : 'sleep, appetite'),
          },
        ],
        doc: () => {
          const nodes = [node('bdi-rules', 'rules', -330, 0)];
          const edges = [];
          const groups = [];
          ITEMS.forEach((name, i) => {
            const n = i + 1;
            const col = Math.floor(i / 7);
            nodes.push(
              node(MORE[n] ? 'bdi-item-dir' : 'bdi-item', 'q' + n, col * 300, (i % 7) * 168, {
                title: n + ' · ' + name,
                groupId: 'g' + col,
                data: { n, answer: ANSWERS[i] },
              }),
            );
            edges.push(edge('s' + n, 'q' + n + '.score', 'sum.items'));
          });
          ['Items 1 - 7', 'Items 8 - 14', 'Items 15 - 21'].forEach((title, col) =>
            groups.push({
              id: 'g' + col,
              title,
              x: col * 300 - 15,
              y: -55,
              width: 260,
              height: 1250,
              color: 'chart-1',
            }),
          );
          nodes.push(
            node('bdi-sum', 'sum', 980, 330),
            node('bdi-missing', 'missing', 1320, 330),
            node('bdi-band', 'band', 1680, 290),
            node('bdi-safety', 'safety', 1320, 0),
            node('bdi-direction', 'direction', 1320, 720),
            node('bdi-report', 'report', 2040, 330),
          );
          edges.push(
            edge('x9', 'q9.score', 'safety.item9', { route: 'orthogonal' }),
            edge('x16', 'q16.score', 'direction.sleep', { route: 'orthogonal' }),
            edge('x18', 'q18.score', 'direction.appetite', { route: 'orthogonal' }),
            edge('t1', 'sum.sum', 'missing.sum'),
            edge('t2', 'missing.total', 'band.total'),
            edge('t3', 'band.result', 'report.result'),
            edge('t4', 'safety.flag', 'report.flag'),
            edge('t5', 'direction.notes', 'report.notes'),
          );
          return doc('bdi', 'BDI-II form logic', nodes, edges, groups, 1);
        },
        preview: (el, out) => {
          const r = out.report?.report;
          if (!r) return null;
          const at = r.total === null ? null : Math.min(63, r.total);
          const bands = out.band?.result?.bands ?? BANDS;
          // the bands by their share of 0 - 63, the cut-offs as ticks below (a band's name does not fit its share)
          const scale = h(
            'div',
            { class: 'ws-scale', 'aria-hidden': 'true' },
            h(
              'div',
              { class: 'ws-scale-bar' },
              bands.map((b) =>
                h('i', {
                  style: `flex: ${b.to - b.from + 1}`,
                  'data-on': r.band === b.band,
                  title: `${b.band}: ${b.from} - ${b.to}`,
                }),
              ),
              at !== null && h('b', { style: `inset-inline-start: ${(at / 63) * 100}%` }),
            ),
            h(
              'div',
              { class: 'ws-scale-ticks' },
              [...bands.map((b) => b.from), 63].map((v) =>
                h('span', { style: `inset-inline-start: ${(v / 63) * 100}%`, text: String(v) }),
              ),
            ),
          );
          return [
            h(
              'div',
              {},
              h('div', { class: 'text-xs text-muted-foreground', text: 'BDI-II total (0 - 63)' }),
              h('div', {
                class: 'ws-result',
                'data-ws-bdi': '',
                text: r.total === null ? 'incomplete' : String(r.total),
              }),
              h('div', { text: r.band + (r.prorated ? ' · prorated for item ' + r.missing.join(', ') : '') }),
            ),
            scale,
            r.flag !== 'none' &&
              h(
                'div',
                { class: 'alert', 'data-variant': 'destructive', role: 'alert' },
                h('div', { class: 'alert-title', text: 'Item 9: ' + r.flag }),
                h('div', {
                  class: 'alert-description',
                  text: 'Suicidal thoughts or wishes were reported. A clinician follows up before anything else.',
                }),
              ),
            kv([
              ['Missing', r.missing.length ? r.missing.join(', ') : 'none'],
              ['Sleep and appetite', r.notes.join('; ')],
            ]),
            h('p', { class: 'ws-empty', text: 'A screening score, not a diagnosis.' }),
          ];
        },
      };
    }

    // -- every app's node types and connection types, registered once for the whole page
    for (const app of Object.values(APPS)) {
      for (const t of app.types) W.register('global', t);
      for (const e of app.edges) W.registerEdge('global', e);
    }

    // -- one app at a time in the editor: its document is kept while another is open, its outputs feed the preview
    const docs = {};
    const outputs = {};
    let current = null;
    const placeholder = df$('[data-ws-placeholder]').get(0);
    const palette = df$('[data-ws-palette]').get(0);
    const showPreview = () => {
      const app = APPS[current];
      const drawn = app?.preview(previewEl, outputs[current] ?? {});
      const kids = (Array.isArray(drawn) ? drawn : [drawn]).filter(Boolean);
      if (!kids.length) return;
      df$(previewEl).empty();
      previewEl.append(...kids);
      placeholder.hidden = true;
    };
    const resetPreview = () => {
      APPS.scene.stop();
      df$(previewEl).empty();
      placeholder.hidden = false;
    };
    flow.addEventListener('workflow-node-state', (e) => {
      if (e.detail.state.status === 'success' && current)
        (outputs[current] ??= {})[e.detail.nodeId] = e.detail.state.output ?? {};
    });
    flow.addEventListener('workflow-run', (e) => {
      if (e.detail.status === 'running' && current) outputs[current] = {};
      if (e.detail.status === 'done') showPreview();
    });
    const open = async (id) => {
      if (!APPS[id] || id === current) return;
      clearTimeout(autoTimer);
      // a run still going ends first: run() starts nothing until a cancelled run has settled
      let settled = null;
      if (current) {
        if (flow.hasAttribute('data-running')) settled = ended();
        W.cancel(flow);
        docs[current] = W.export(flow);
      }
      current = id;
      resetPreview();
      // the Nodes panel lists this app's node types (every app registers its types for the whole page)
      palette.dataset.workflowTypes = APPS[id].types.map((t) => t.type).join(' ');
      W.load(flow, docs[id] ?? APPS[id].doc());
      df$('[data-ws-app]').each((_i, a) => {
        a.toggleAttribute('data-current', a.dataset.wsApp === id);
        if (a.dataset.wsApp === id) a.setAttribute('aria-current', 'page');
        else a.removeAttribute('aria-current');
      });
      root.dataset.wsOpen = id;
      loadTree();
      drawHistory();
      ran = runnable();
      // the first visit runs the app once, so its preview and its connection labels show at once
      if (!outputs[id]) {
        await settled;
        if (current === id) await W.run(flow);
      } else showPreview();
    };

    // -- the navigator: the document as a Data Tree (groups, nodes, the nodes inside subworkflows); a pick reveals
    //    the node - with Follow pressed the editor flies to it, released only the selection moves; a click on a card
    //    opens the one way to it in the tree (data-exclusive)
    const loadTree = () =>
      T.setSource(tree, W.tree(flow), {
        render: (label, row) => {
          label.append(h('span', { text: row.title }));
          if (row.kind !== 'node')
            label.append(h('span', { class: 'data-tree-meta', text: row.kind === 'group' ? 'group' : 'subworkflow' }));
        },
      });
    let timer = 0;
    flow.addEventListener('workflow-change', () => {
      clearTimeout(timer);
      timer = setTimeout(loadTree, 200);
    });
    let syncing = false;
    tree.addEventListener('data-tree-select', (e) => {
      const row = e.detail.record;
      if (row.kind === 'group') return;
      syncing = true;
      W.reveal(flow, row.path, { camera: follow.getAttribute('aria-pressed') === 'true' });
      syncing = false;
    });
    flow.addEventListener('workflow-select', (e) => {
      if (syncing || e.detail.selected.length !== 1) return;
      T.reveal(tree, [...e.detail.path, e.detail.selected[0]].join('/'));
    });

    // -- Auto-run: with the toggle pressed, a change to what runs - a node's value, a node, a connection, also an undo
    //    or a step in the history - runs the workflow again 500 ms after the last one; a move or a label does not. A run
    //    still going is cancelled first, so the result always reflects the newest values
    const auto = df$('#ws-auto').get(0);
    const AUTO_DELAY = 500;
    let autoTimer = 0;
    const autoOn = () => auto.getAttribute('aria-pressed') === 'true';
    const runnable = () => {
      const d = W.export(flow);
      return JSON.stringify([
        d.nodes.map((n) => [n.id, n.type, n.data, n.subgraph]),
        d.edges.map((e) => [e.source, e.target]),
      ]);
    };
    let ran = '';
    const ended = () =>
      new Promise((resolve) => {
        const done = (e) => {
          if (e.detail.status === 'running') return;
          flow.removeEventListener('workflow-run', done);
          resolve();
        };
        flow.addEventListener('workflow-run', done);
      });
    const rerun = async () => {
      if (flow.hasAttribute('data-running')) {
        const end = ended();
        W.cancel(flow);
        await end;
      }
      await W.run(flow);
    };
    flow.addEventListener('workflow-change', () => {
      if (!autoOn()) return;
      const now = runnable();
      if (now === ran) return;
      ran = now;
      clearTimeout(autoTimer);
      autoTimer = setTimeout(rerun, AUTO_DELAY);
    });
    // pressed, it starts from the document as it is; released, a run waiting for its delay is dropped
    // (read after the Toggle's own click handler, whichever was bound first)
    auto.addEventListener('click', () =>
      setTimeout(() => {
        if (autoOn()) ran = runnable();
        else clearTimeout(autoTimer);
      }),
    );

    // -- the revision history: every change of the level the editor shows, oldest first; a row steps the workflow to
    //    that change (undo / redo one at a time - W.travel), Back and Forward move one change
    const historyEl = df$('[data-ws-history]').get(0);
    const historyCount = df$('[data-ws-history-count]').get(0);
    const [stepBack, stepForward] = df$('[data-ws-history-step]').toArray();
    let historyQueued = 0;
    const drawHistory = () => {
      historyQueued = 0;
      const { changes, at } = W.history(flow);
      const rows = ['Loaded', ...changes].map((label, i) =>
        h(
          'li',
          { 'aria-current': i === at ? 'step' : null, 'data-undone': i > at, 'data-step': String(i) },
          h('button', { type: 'button', title: label }, h('small', { text: String(i) }), h('span', { text: label })),
        ),
      );
      df$(historyEl).empty();
      historyEl.append(...rows);
      historyCount.textContent = `${at} / ${changes.length}`;
      stepBack.disabled = at === 0;
      stepForward.disabled = at === changes.length;
      // the current row in view - by the panel's own scroll (scrollIntoView would also move a docs page around its card)
      const row = df$(historyEl).find('[aria-current]').get(0);
      const box = df$(historyEl).closest('.panel-body').get(0);
      if (row && box) {
        const r = row.getBoundingClientRect();
        const b = box.getBoundingClientRect();
        if (r.top < b.top) box.scrollTop -= b.top - r.top;
        else if (r.bottom > b.bottom) box.scrollTop += r.bottom - b.bottom;
      }
    };
    // a step through the history is one change per undo - draw once, after the last
    const queueHistory = () => (historyQueued ||= setTimeout(drawHistory));
    flow.addEventListener('workflow-change', queueHistory);
    flow.addEventListener('workflow-navigate', queueHistory);
    df$(historyEl).on('click', (e) => {
      const li = df$(e.target).closest('li[data-step]').get(0);
      if (li) W.travel(flow, Number(li.dataset.step));
    });
    df$('[data-ws-history-step]').on('click', (e) => {
      W.travel(flow, W.history(flow).at + Number(e.currentTarget.dataset.wsHistoryStep));
    });

    // -- room for the editor: below 1600px of width the History starts minimized to its tab (a click opens it)
    if (root.clientWidth < 1600) df$('#ws-history-panel').get(0)?.api?.setState('minimized');

    // -- routing: an app is a route (#/agents, #/algorithm, #/scene, #/process, #/neural, #/bdi)
    const routes = [
      { id: 'home', path: '/' },
      { id: 'app', path: '/:app' },
    ];
    const show = (to) => void open(to.routeId === 'app' && APPS[to.params.app] ? to.params.app : 'agents');
    const router = createRouter({ mode: 'hash', routes, prepare: ({ to }) => ({ commit: () => show(to) }) });
    if ((await router.start()).status === 'rejected') {
      // no address the router may own - a docs preview is an about:srcdoc frame: the same routes match its hash
      const preview = createRouter({ mode: 'hash', routes, baseUrl: 'https://preview.invalid/' });
      const followHash = () => show(preview.resolve(location.hash.startsWith('#/') ? location.hash : '#/'));
      addEventListener('hashchange', followHash);
      followHash();
    }
    root.dataset.wsReady = '';
  });
</script>
```

<h2 id="how-it-works" class="h2-display">How it works</h2>

<DocText>A page, not a component: it composes the library and keeps its own glue in one script - the six apps' node types, connection types, documents and previews.</DocText>

<ul class="text-sm" style="display:grid;gap:0.5rem;max-width:46rem;padding-inline-start:1.25rem">
  <li><strong>One editor, six documents.</strong> Each app registers its node types with <code>df$.shadcn.workflow.register('global', ...)</code> and its connection types with <code>registerEdge()</code>; a route (<code>#/agents</code>, <code>#/algorithm</code>, <code>#/scene</code>, <code>#/process</code>, <code>#/neural</code>, <code>#/bdi</code>) loads its document. An edited document is kept while another app is open.</li>
  <li><strong>Custom editing.</strong> Prompts, the Dijkstra code, the stops and the network's weights open in a Window (<code>edit()</code> resolves the new value; JSON that does not parse keeps the window open). The order opens a three-step Dialog wizard that folds the answers into one Order object. The guardrail's blocked words are edited by the page itself: <code>editor: 'external'</code> fires <code>workflow-field-edit</code>, the page cancels it and writes with <code>setField()</code>.</li>
  <li><strong>Custom labels and values.</strong> <code>renderLabel</code> puts a flame or an ice cube on the temperature, turns the traffic hour red in a rush hour, a credit limit red when it is tight; <code>render</code> draws an order as a table, the stops as badges, a block's weights as a heat map and the readout as a matrix.</li>
  <li><strong>Custom connections.</strong> Every port type has a connection type: a message counts its tokens, a batch of documents its size, an Order its id and total, a tensor its shape and how many units fired. Motion and live traffic connections move; a run moves dashes into the node that is working.</li>
  <li><strong>The Nodes panel.</strong> The palette outlet lists the open app's node types by category - <code>data-workflow-types</code> on the outlet names them, since every app registers its types for the whole page. A click adds a node in the middle of the view, a drag drops it where you let go.</li>
  <li><strong>Room on the canvas.</strong> A connection label sits halfway along its line, else further along it or just beside it, where it covers neither a card nor another label, and hides while there is no such place; far off, each card keeps its title readable. Each card is as high as its content after the first run. Below 1600 px of width the History starts folded to its tab, so the editor keeps its room.</li>
  <li><strong>The navigator.</strong> <code>tree()</code> feeds a Data Tree with every group, node and subworkflow node; a pick calls <code>reveal()</code> - with Follow pressed the editor flies there - and a click on a card opens the one way to it in the tree (<code>data-exclusive</code>, <code>reveal()</code>).</li>
  <li><strong>Auto-run.</strong> With Auto-run pressed in the toolbar, a change to what runs - a value, a node, a connection, an undo or a step in the history - runs the workflow again half a second after the last change; a run still going is cancelled first. Moving a card or changing a label runs nothing.</li>
  <li><strong>The history.</strong> The sidebar right of the editor lists every change of the level on screen, oldest first, from <code>history()</code>: the current one marked, the undone ones struck through. A row, Back or Forward calls <code>travel()</code>, which undoes or redoes one change at a time until the workflow stands at that change; a new edit drops the changes after it, as undo does. Each subworkflow level keeps its own history.</li>
  <li><strong>Events.</strong> <code>workflow-change</code>, <code>workflow-field-change</code>, <code>workflow-field-edit</code>, <code>workflow-select</code>, <code>workflow-run</code>, <code>workflow-node-state</code> and <code>workflow-navigate</code> all land in the Events panel; <code>workflow-node-state</code> also collects the outputs the Preview draws.</li>
  <li><strong>The 3D scene.</strong> three.js 0.180.0 loads from jsDelivr when the scene app first runs. The Render node draws one still frame for its card; the Preview plays the scene - the motion subworkflow spins and bobs the meshes, the shader subworkflow becomes a <code>ShaderMaterial</code> (noise and a fresnel rim). Reduced motion shows one still frame.</li>
  <li><strong>The neural calculator.</strong> A ReLU network whose 973 weights and biases are written by a small program, not trained. A step - is x at least k? - is two ReLUs and exact on whole numbers; with it the network takes A apart into bits, multiplies by gating B with each bit, divides by restoring long division (plus two decimals), picks the op's result with a gate, and turns the magnitude into decimal digits. The digits leave through seven readout matrices of 10 rows each, plus sign and ÷ 0. <strong>Check all</strong> runs every A, B and op - 40,804 inputs - through the weights as they stand in the editor: change one and see what breaks.</li>
  <li><strong>The BDI-II form logic.</strong> Each of the 21 items is a node with its options - 0 to 3, and for sleep (item 16) and appetite (item 18) also the letter that says more or less. Every rule is a node of its own after them: the sum, missing answers (prorated up to a limit you set, else the score stops as incomplete), the severity band (0 - 13 minimal, 14 - 19 mild, 20 - 28 moderate, 29 - 63 severe; the cut-offs open as JSON), the item 9 check that flags any thought of suicide for a clinician, and the direction notes. The nodes carry the item names and short anchors of our own: the statements themselves are copyrighted by Pearson, and a licensed form pastes them in. A screening score, never a diagnosis.</li>
  <li><strong>The agents are stand-ins.</strong> The classifier, researcher, critic and writer are deterministic functions shaped like model calls (a prompt, a model, a temperature, streamed progress), and the knowledge base, the order API, the traffic service and the credit bureau answer from data in the page - so the demo runs offline and the same way every time.</li>
</ul>

</DocPage>
