Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(workbench): add the /workbench page, a node-graph editor that runs a photo through real GPU workflow steps
nirholasdaf1b527bb86
diff --git a/docs/workbench.md b/docs/workbench.mdnew file mode 100644index 000000000..ec30fc1eb--- /dev/null+++ b/docs/workbench.md@@ -0,0 +1,120 @@+# Workbench: image to 3D in a visual workflow++Workbench is a desktop-style 3D workspace that runs in the browser. You drop a photo into the Image node, press **Generate 3D Model**, and the photo runs through a chain of real platform steps (background removal, mesh generation, remeshing, auto-rigging, AI material restyle) before landing in a viewport where you can smooth, decimate, inspect and export it. The chain is a workflow you can edit in a node graph, save, and reuse.++Page: [/workbench](https://three.ws/workbench)++## Why it exists++[Forge](./forge.md) is built for one thing: type or drop something in, get a model out. That is the right shape for most people, but it hides the pipeline. Creators who make game props, printable figures or rigged characters want to choose the steps: cut the background first, retopologize to quads, keep a face budget, rig the result, and export to the format their tool expects. Workbench exposes that pipeline as a layout people already know from desktop 3D apps: an icon rail, a workflow panel of node cards, a large viewport with a tool strip, and an Export menu. Every step calls the same production endpoints Forge uses, so nothing here is a simulation.++## The layout++- **Top bar.** Brand, a live RAM meter (the JavaScript heap this tab is using, shown in Chromium browsers that expose it), links to Forge and these docs, and the theme toggle.+- **Icon rail.** Generate, Workflows, Extensions, Settings. Each view has its own URL hash (`#workflows`, `#extensions`, `#settings`), so you can link straight to one.+- **Generate panel.** A Workflow picker with an edit button, then one card per node in run order. Each card shows its input and output type (`image → mesh`), an on/off switch for optional nodes, a collapse chevron, and its settings. The purple **Generate 3D Model** button runs the workflow and turns into **Cancel** while it runs; underneath it a run log ticks through each step.+- **Viewport.** A toolbar with Undo, Redo, Import, Export, Smooth, Decimate and Free memory; a floating vertical strip with view modes and toggles; a triangle and vertex count in the corner; and a History drawer of everything you have generated in this browser.++## Running a workflow++1. Open [/workbench](https://three.ws/workbench).+2. Drop a PNG, JPG or WebP (up to 8 MB) onto the Image node, click it to browse, or paste an image from the clipboard. The upload starts immediately so the run does not wait for it. No photo? Type a description in the prompt box instead; the server turns it into a reference image first.+3. Adjust the Generate Mesh settings if you want to: **Engine** (Auto routes to the healthiest lane, or pin a specific one), **Quality** (Draft, Standard, or High for $THREE holders), **Resolution**, **Face budget**, **Texture** size, **Compression** (none, Meshopt or Draco) and **Seed**.+4. Press **Generate 3D Model** or <kbd>Ctrl</kbd>+<kbd>Enter</kbd>. The overlay shows the current step and elapsed time; the bar under the button fills as nodes finish.+5. When the model lands it appears in the viewport, joins History with a thumbnail, and a toast offers a one-click GLB download.++If a step fails, the toast says why and offers the fix that fits: switch the quality tier, retry on the lane the server suggests, add background removal for a photo it could not use, or try again after a rate limit.++## Nodes++| Node | Takes | Gives | Runs on | What it does |+|---|---|---|---|---|+| Image | | image | Your browser | The photo, or a text prompt. Always first. |+| Remove Background | image | image | GPU worker (`/api/forge-rembg`) | Cuts the subject out with BiRefNet, ISNet or U2-Net before reconstruction. Skipped automatically for a text prompt. |+| Generate Mesh | image | mesh | Forge GPU lanes (`/api/forge`) | Reconstructs a textured GLB. Always present. |+| Restyle Materials | mesh | mesh | `/api/material-studio` | Rewrites the PBR materials from a plain-language look such as "polished gold". |+| Remesh | mesh | mesh | GPU worker (`/api/forge-remesh`) | Server-side retopology to triangles, quads or low poly at a target face count. |+| Decimate | mesh | mesh | Your browser | Edge-collapse simplification that keeps UV seams and borders. |+| Smooth | mesh | mesh | Your browser | Taubin smoothing, which does not shrink the mesh. |+| Auto-Rig | mesh | mesh | `/api/forge?action=rig` | Adds a skeleton and skin weights so the model can animate. |+| Add to Scene | mesh | | Your browser | Loads the result into the viewport and History. Always last. |++When an in-browser step (Decimate, Smooth) is followed by a server step, the edited model is saved to durable storage first so the server works on exactly what you see. The same happens at the end of a run, so the History entry and the GLB link always match the viewport.++## Building workflows++Open **Workflows** from the rail, or press the pencil next to the Workflow picker.++- **Five starting points ship with it:** Image to 3D, Game-ready prop (draft quality, Meshopt, decimate, smooth), Rigged character (background removal, generate, rig), Clean quad retopo, and Restyled prop.+- **Add a node** from the palette under the graph. It is spliced into the chain at the first point where its types fit, so a new Smooth lands after the mesh exists.+- **Wire nodes** by dragging from an output dot to an input dot, or click an output dot and then an input dot (Enter on a focused output dot starts a wire from the keyboard). Click a wired input dot to unplug it. A wire between mismatched types (an image into a mesh input) is refused with a message.+- **Move** a node by its header, **pan** by dragging empty canvas, **delete** the selected node with Delete or Backspace. Image, Generate Mesh and Add to Scene are fixed.+- **Tidy** lays the chain out left to right. **Duplicate**, **New** and **Delete** (with Undo) manage the list.+- The status line validates continuously: one source, one output, one Generate Mesh, a single unbroken chain, matching types. **Use in Generate** is enabled only when the workflow can run.++Workflows are saved in this browser (`localStorage` key `wb:workflows`). Settings → **Restore default workflows** brings back the originals, with Undo.++## Editing in the viewport++- **Import** opens a GLB, glTF, OBJ, STL, PLY or FBX from disk, or a reference image for the Image node. Dropping either kind of file onto the viewport does the same.+- **Smooth** and **Decimate** open a small panel with a slider and Apply. Decimate shows the triangle count you will end up with before you apply it. Both are undoable (up to six steps).+- **Export** writes GLB (textures kept), OBJ, STL or PLY, named after your source. **Copy GLB link** copies the hosted URL of a generated or reopened model as long as it has no unsaved edits.+- **Free memory** unloads the model and releases its GPU buffers.+- The tool strip switches between **Shaded**, **Wireframe**, **Normals** and **Clay** views, toggles the grid, environment lighting and turntable, opens History, frames the model and saves a PNG screenshot.++### Keyboard shortcuts++| Keys | Action |+|---|---|+| <kbd>Ctrl</kbd>+<kbd>Enter</kbd> | Generate (or cancel a running generation) |+| <kbd>Ctrl</kbd>+<kbd>Z</kbd> / <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd> or <kbd>Ctrl</kbd>+<kbd>Y</kbd> | Undo / redo a mesh edit |+| <kbd>1</kbd> <kbd>2</kbd> <kbd>3</kbd> <kbd>4</kbd> | Shaded, wireframe, normals, clay |+| <kbd>F</kbd> | Frame the model |+| <kbd>G</kbd> / <kbd>E</kbd> / <kbd>T</kbd> | Grid, environment light, turntable |+| <kbd>H</kbd> | History drawer |+| <kbd>P</kbd> | Screenshot |+| <kbd>Esc</kbd> | Close menus and the History drawer |++## Extensions++The Extensions view reads the live engine catalog (`GET /api/forge?catalog=1`) and lane health (`GET /api/forge?health=1`) and shows one card per engine with its status, whether it is free, what inputs it accepts, and its typical time at Standard quality. Engines that accept your own photos and need no key have a switch that adds or removes them from the Engine picker. Engines that need your own API key link to [Forge](./forge.md), where keys are managed. Below the engines, each mesh tool has a card and an **Add to current workflow** button.++## Settings++Viewport defaults (grid, environment light, turntable after a generation), the site theme, your anonymous browser id (the same one Forge uses, so models made here also show in your Forge gallery), Clear history, Restore default workflows, and a copyable set of `curl` commands that reproduce the current workflow's Generate step.++## Scripts and agents++Everything the Workbench does is a public HTTP call, so a script or an agent can run the same pipeline. Generate from a photo:++```bash+# 1. Ask for an upload slot, then PUT the image to upload_url+curl -s https://three.ws/api/forge-upload -H 'content-type: application/json' \+ -d '{"content_type":"image/png","size_bytes":'$(wc -c < photo.png)'}'+curl -X PUT "$UPLOAD_URL" -H 'content-type: image/png' --data-binary @photo.png++# 2. Submit the public_url+curl -s https://three.ws/api/forge -H 'content-type: application/json' \+ -d '{"path":"image","tier":"standard","image_urls":["'"$PUBLIC_URL"'"]}'++# 3. Poll every few seconds until status is "done", then fetch glb_url+curl -s "https://three.ws/api/forge?job=$JOB_ID"+```++The other nodes are one call each: `POST /api/forge-rembg` with `{ "image_url", "model" }`, `POST /api/forge-remesh` with `{ "mesh_url", "remesh_mode", "target_faces" }` (both answer `{ job_id }`, polled with `?job=`), `POST /api/forge?action=rig` with `{ "glb_url" }`, and `POST /api/material-studio?action=restyle` with `{ "glb_url", "instruction" }`. Full request and response shapes are in the [3D API reference](./3d-api.md).++## Where things live++| Piece | File |+|---|---|+| Page shell | [pages/workbench.html](../pages/workbench.html) |+| Controller (views, panels, toolbar, history) | [src/workbench/main.js](../src/workbench/main.js) |+| Viewport (three.js scene, loaders, exporters, undo) | [src/workbench/viewport.js](../src/workbench/viewport.js) |+| In-browser decimate and smooth | [src/workbench/mesh-tools.js](../src/workbench/mesh-tools.js) |+| Node types, templates, validation, storage | [src/workbench/workflows.js](../src/workbench/workflows.js) |+| Workflow runner | [src/workbench/runner.js](../src/workbench/runner.js) |+| Node graph editor | [src/workbench/graph-editor.js](../src/workbench/graph-editor.js) |+| API client | [src/workbench/api.js](../src/workbench/api.js) |+| Styles | [src/workbench/workbench.css](../src/workbench/workbench.css) |++Related: [Forge](./forge.md) for one-shot generation, [Scene Studio](./scene-studio.md) for composing scenes from the models you make here, and [STRUCTURE.md](../STRUCTURE.md) for the map of every surface.diff --git a/pages/workbench.html b/pages/workbench.htmlnew file mode 100644index 000000000..edce77b99--- /dev/null+++ b/pages/workbench.html@@ -0,0 +1,311 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <script>/* three.ws theme boot: no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+ <title data-i18n="workbench.page_title">Workbench · three.ws</title>+ <meta name="description" data-i18n-attr="content:workbench.meta_desc" content="A desktop-style image-to-3D workspace in the browser. Drop a photo, run it through a visual workflow of real GPU nodes (background removal, mesh generation, remeshing, rigging, material restyle), then smooth, decimate and export GLB, OBJ, STL or PLY. Free, no signup." />+ <link rel="canonical" href="https://three.ws/workbench" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/tokens.css" />+ <link rel="stylesheet" href="/src/workbench/workbench.css" />+ <meta property="og:type" content="website" />+ <meta property="og:title" data-i18n-attr="content:workbench.share_title" content="Workbench · three.ws" />+ <meta property="og:description" data-i18n-attr="content:workbench.og_desc" content="Image to 3D in a visual workflow: generate, remesh, rig, restyle, smooth, decimate and export, all in the browser. Free, no signup." />+ <meta property="og:url" content="https://three.ws/workbench" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=build&t=Workbench&d=Image+to+3D+in+a+visual+workflow%3A+generate%2C+remesh%2C+rig%2C+restyle%2C+smooth%2C+decimate+and+export+in+the+browser.&p=%2Fworkbench" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" data-i18n-attr="content:workbench.share_title" content="Workbench · three.ws" />+ <meta name="twitter:description" data-i18n-attr="content:workbench.tw_desc" content="Image to 3D in a visual workflow: generate, remesh, rig, restyle, smooth, decimate and export, all in the browser." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=build&t=Workbench&d=Image+to+3D+in+a+visual+workflow%3A+generate%2C+remesh%2C+rig%2C+restyle%2C+smooth%2C+decimate+and+export+in+the+browser.&p=%2Fworkbench" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="Workbench / three.ws" />+ <meta name="twitter:site" content="@trythreews" />+ <meta property="og:site_name" content="three.ws">+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebApplication","name":"Workbench","applicationCategory":"DesignApplication","operatingSystem":"Any (WebGL 2)","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},"description":"A desktop-style image-to-3D workspace in the browser: visual workflows of real GPU nodes, in-browser smoothing and decimation, and GLB, OBJ, STL and PLY export.","url":"https://three.ws/workbench","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}]}</script>+</head>+<body>+ <div class="wb-app" id="wb-app" data-view="generate">+ <!-- ── top bar ─────────────────────────────────────────── -->+ <header class="wb-top">+ <a class="wb-brand" href="/" aria-label="three.ws home">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round" aria-hidden="true"><path d="M12 2.8 20 7.4v9.2l-8 4.6-8-4.6V7.4z" stroke="var(--wb-accent-hi)"/><path d="M4 7.4 12 12l8-4.6M12 12v9.2" stroke="var(--wb-accent-ink)"/></svg>+ Workbench <small>three.ws</small>+ </a>+ <span class="wb-top-spacer"></span>+ <span class="wb-meter" id="wb-meter" hidden title="JavaScript heap used by this tab">+ RAM <span class="wb-meter-bar"><i id="wb-meter-fill"></i></span> <span id="wb-meter-text">0 MB</span>+ </span>+ <a class="wb-top-link hide-sm" href="/forge">Forge</a>+ <a class="wb-top-link hide-sm" href="/docs/workbench">Docs</a>+ <button class="wb-icon-btn" id="nav-theme-toggle" type="button" aria-label="Toggle light and dark theme" title="Theme">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/></svg>+ </button>+ </header>++ <!-- ── icon rail ───────────────────────────────────────── -->+ <nav class="wb-rail" aria-label="Workbench sections">+ <button class="wb-rail-btn" type="button" data-nav="generate" aria-current="page">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z"/><path d="M19 16l.8 2.2L22 19l-2.2.8L19 22l-.8-2.2L16 19l2.2-.8z"/></svg>+ Generate+ </button>+ <button class="wb-rail-btn" type="button" data-nav="workflows">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="6" height="6" rx="1.5"/><rect x="15" y="15" width="6" height="6" rx="1.5"/><path d="M9 6h4a3 3 0 0 1 3 3v6"/></svg>+ Workflows+ </button>+ <button class="wb-rail-btn" type="button" data-nav="extensions">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 3h4v3a2 2 0 1 0 4 0V3h3v7h-3a2 2 0 1 0 0 4h3v7h-7v-3a2 2 0 1 0-4 0v3H3v-7h3a2 2 0 1 0 0-4H3V3z"/></svg>+ Extensions+ </button>+ <button class="wb-rail-btn" type="button" data-nav="settings">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>+ Settings+ </button>+ </nav>++ <!-- ── generate side panel ─────────────────────────────── -->+ <aside class="wb-side" aria-label="Workflow">+ <div class="wb-side-scroll">+ <p class="wb-label" id="wb-flow-label">Workflow</p>+ <div class="wb-row">+ <select class="wb-select" id="wb-flow-select" aria-labelledby="wb-flow-label"></select>+ <button class="wb-icon-btn" id="wb-flow-edit" type="button" aria-label="Edit this workflow" title="Edit workflow">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/></svg>+ </button>+ </div>+ <div id="wb-nodes" aria-live="polite"></div>+ </div>+ <div class="wb-side-foot">+ <button class="wb-primary" id="wb-run" type="button">+ <span id="wb-run-label">Generate 3D Model</span>+ <span class="wb-progress" id="wb-run-progress"></span>+ </button>+ <ul class="wb-run-log" id="wb-run-log" aria-live="polite"></ul>+ </div>+ </aside>++ <!-- ── viewport ────────────────────────────────────────── -->+ <main class="wb-main" id="wb-main">+ <div class="wb-toolbar" role="toolbar" aria-label="Model tools">+ <button class="wb-tool is-square" id="wb-undo" type="button" aria-label="Undo (Ctrl+Z)" title="Undo (Ctrl+Z)" disabled>+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 14 4 9l5-5"/><path d="M4 9h11a5 5 0 0 1 0 10h-3"/></svg>+ </button>+ <button class="wb-tool is-square" id="wb-redo" type="button" aria-label="Redo (Ctrl+Shift+Z)" title="Redo (Ctrl+Shift+Z)" disabled>+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 14 5-5-5-5"/><path d="M20 9H9a5 5 0 0 0 0 10h3"/></svg>+ </button>+ <span class="wb-sep" aria-hidden="true"></span>+ <div class="wb-menu-wrap">+ <button class="wb-tool" id="wb-import-btn" type="button" aria-haspopup="menu" aria-expanded="false" aria-controls="wb-import-menu">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v12"/><path d="m7 10 5 5 5-5"/><path d="M5 21h14"/></svg>+ Import+ <svg class="caret" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>+ </button>+ <div class="wb-menu" id="wb-import-menu" role="menu">+ <button type="button" role="menuitem" data-import="model">3D model <small>GLB glTF OBJ STL PLY FBX</small></button>+ <button type="button" role="menuitem" data-import="image">Reference image <small>PNG JPG WebP</small></button>+ </div>+ </div>+ <div class="wb-menu-wrap">+ <button class="wb-tool" id="wb-export-btn" type="button" aria-haspopup="menu" aria-expanded="false" aria-controls="wb-export-menu" disabled>+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 15V3"/><path d="m7 8 5-5 5 5"/><path d="M5 21h14"/></svg>+ Export+ <svg class="caret" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>+ </button>+ <div class="wb-menu" id="wb-export-menu" role="menu">+ <button type="button" role="menuitem" data-export="glb">GLB <small>glTF binary, textures kept</small></button>+ <button type="button" role="menuitem" data-export="obj">OBJ <small>geometry</small></button>+ <button type="button" role="menuitem" data-export="stl">STL <small>3D printing</small></button>+ <button type="button" role="menuitem" data-export="ply">PLY <small>point and mesh data</small></button>+ <button type="button" role="menuitem" data-export="link" id="wb-copy-link">Copy GLB link <small>hosted file</small></button>+ </div>+ </div>+ <span class="wb-sep" aria-hidden="true"></span>+ <div class="wb-menu-wrap">+ <button class="wb-tool" id="wb-smooth-btn" type="button" aria-haspopup="dialog" aria-expanded="false" aria-controls="wb-smooth-pop" disabled>+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M3 15c3-6 6-6 9 0s6 6 9 0"/></svg>+ Smooth+ </button>+ <div class="wb-popover" id="wb-smooth-pop" role="dialog" aria-label="Smooth mesh">+ <label class="wb-row" for="wb-smooth-range">Passes <output id="wb-smooth-out">4</output></label>+ <input type="range" id="wb-smooth-range" min="1" max="20" step="1" value="4" />+ <p class="wb-hint">Taubin smoothing keeps volume and moves UV seams together, so textures stay put.</p>+ <button class="wb-tool" id="wb-smooth-apply" type="button">Apply smoothing</button>+ </div>+ </div>+ <div class="wb-menu-wrap">+ <button class="wb-tool" id="wb-decimate-btn" type="button" aria-haspopup="dialog" aria-expanded="false" aria-controls="wb-decimate-pop" disabled>+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round" aria-hidden="true"><path d="M12 3 21 20H3z"/><path d="M12 3v17M7.5 11.5 16.5 11.5"/></svg>+ Decimate+ </button>+ <div class="wb-popover" id="wb-decimate-pop" role="dialog" aria-label="Decimate mesh">+ <label class="wb-row" for="wb-decimate-range">Keep <output id="wb-decimate-out">50%</output></label>+ <input type="range" id="wb-decimate-range" min="0.05" max="0.95" step="0.05" value="0.5" />+ <p class="wb-hint" id="wb-decimate-est">Simplifies every mesh with edge collapse.</p>+ <button class="wb-tool" id="wb-decimate-apply" type="button">Apply decimation</button>+ </div>+ </div>+ <button class="wb-tool" id="wb-free" type="button" title="Drop the model and release its GPU memory">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="6" y="6" width="12" height="12" rx="2"/><path d="M9 2v4M15 2v4M9 18v4M15 18v4M2 9h4M2 15h4M18 9h4M18 15h4"/></svg>+ Free memory+ </button>+ </div>++ <div class="wb-stage" id="wb-stage">+ <div class="wb-canvas" id="wb-canvas"></div>++ <div class="wb-strip" role="toolbar" aria-label="View" aria-orientation="vertical">+ <button class="wb-strip-btn" type="button" data-mode="shaded" data-tip="Shaded (1)" aria-label="Shaded view" aria-pressed="true">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><circle cx="12" cy="12" r="8"/><path d="M12 4a8 8 0 0 1 0 16z" fill="currentColor"/></svg>+ </button>+ <button class="wb-strip-btn" type="button" data-mode="wireframe" data-tip="Wireframe (2)" aria-label="Wireframe view" aria-pressed="false">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" aria-hidden="true"><path d="M12 3 20 7.5v9L12 21l-8-4.5v-9z"/><path d="M4 7.5 20 16.5M20 7.5 4 16.5M12 3v18"/></svg>+ </button>+ <button class="wb-strip-btn" type="button" data-mode="normals" data-tip="Normals (3)" aria-label="Normals view" aria-pressed="false">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M4 18h16"/><path d="M8 18V8M12 18V5M16 18V8"/><path d="m6.5 9.5 1.5-1.5 1.5 1.5M10.5 6.5 12 5l1.5 1.5M14.5 9.5 16 8l1.5 1.5"/></svg>+ </button>+ <button class="wb-strip-btn" type="button" data-mode="clay" data-tip="Clay (4)" aria-label="Clay view" aria-pressed="false">+ <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><circle cx="12" cy="12" r="8" opacity="0.85"/></svg>+ </button>+ <hr />+ <button class="wb-strip-btn" type="button" id="wb-grid" data-tip="Grid (G)" aria-label="Toggle grid" aria-pressed="true">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><path d="M3 9h18M3 15h18M9 3v18M15 3v18"/></svg>+ </button>+ <button class="wb-strip-btn" type="button" id="wb-env" data-tip="Environment light (E)" aria-label="Toggle environment lighting" aria-pressed="true">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg>+ </button>+ <button class="wb-strip-btn" type="button" id="wb-spin" data-tip="Turntable (T)" aria-label="Toggle turntable rotation" aria-pressed="false">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-3-6.7"/><path d="M21 4v5h-5"/></svg>+ </button>+ <button class="wb-strip-btn" type="button" id="wb-history-btn" data-tip="History (H)" aria-label="Generation history" aria-pressed="false" aria-controls="wb-history">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>+ </button>+ <hr />+ <button class="wb-strip-btn" type="button" id="wb-frame" data-tip="Frame model (F)" aria-label="Frame the model">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/><circle cx="12" cy="12" r="2.5"/></svg>+ </button>+ <button class="wb-strip-btn" type="button" id="wb-shot" data-tip="Screenshot (P)" aria-label="Save a screenshot">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" aria-hidden="true"><path d="M3 8h4l2-3h6l2 3h4v12H3z"/><circle cx="12" cy="13" r="3.5"/></svg>+ </button>+ </div>++ <section class="wb-history" id="wb-history" aria-label="Generation history">+ <header>+ <strong>History</strong>+ <button class="wb-btn is-danger" id="wb-history-clear" type="button">Clear</button>+ </header>+ <ul id="wb-history-list"></ul>+ </section>++ <div class="wb-empty" id="wb-empty">+ <div class="wb-empty-card">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round" aria-hidden="true"><path d="M12 2.8 20 7.4v9.2l-8 4.6-8-4.6V7.4z"/><path d="M4 7.4 12 12l8-4.6M12 12v9.2"/></svg>+ <h2>Drop an image to begin</h2>+ <p>Add a photo to the Image node and press <kbd>Ctrl</kbd>+<kbd>Enter</kbd>, or drop a GLB, OBJ, STL or PLY anywhere here to edit an existing model.</p>+ </div>+ </div>++ <div class="wb-busy" id="wb-busy" hidden>+ <div class="wb-busy-card" role="status" aria-live="polite">+ <img id="wb-busy-img" alt="" hidden />+ <div class="wb-spinner" aria-hidden="true"></div>+ <strong id="wb-busy-title">Working</strong>+ <span id="wb-busy-text"></span>+ </div>+ </div>++ <div class="wb-dropveil" id="wb-dropveil" aria-hidden="true">Drop to import</div>+ <div class="wb-stats" id="wb-stats" aria-live="polite"></div>+ <div class="wb-hint-corner">Drag to orbit · Scroll to zoom · Right-drag to pan</div>+ </div>+ </main>++ <!-- ── workflows ───────────────────────────────────────── -->+ <section class="wb-view" data-view="workflows" aria-label="Workflows">+ <div class="wb-flows">+ <div class="wb-flow-list" id="wb-flow-list" role="listbox" aria-label="Saved workflows"></div>+ <div class="wb-flow-editor">+ <div class="wb-flow-bar">+ <label class="wb-sr" for="wb-flow-name">Workflow name</label>+ <input class="wb-input" id="wb-flow-name" maxlength="60" />+ <button class="wb-btn" id="wb-flow-new" type="button">New</button>+ <button class="wb-btn" id="wb-flow-dup" type="button">Duplicate</button>+ <button class="wb-btn" id="wb-flow-tidy" type="button">Tidy</button>+ <button class="wb-btn is-danger" id="wb-flow-del" type="button">Delete</button>+ <span class="wb-flow-status" id="wb-flow-status" role="status"></span>+ <button class="wb-btn is-accent" id="wb-flow-use" type="button">Use in Generate</button>+ </div>+ <div class="wb-graph" id="wb-graph" aria-label="Workflow graph. Drag empty space to pan. Delete removes the selected node."></div>+ <div class="wb-palette" id="wb-palette"><span>Add node</span></div>+ </div>+ </div>+ </section>++ <!-- ── extensions ──────────────────────────────────────── -->+ <section class="wb-view" data-view="extensions" aria-label="Extensions">+ <div class="wb-page">+ <div class="wb-page-head">+ <div>+ <h1>Extensions</h1>+ <p>Every generation engine and mesh tool the Workbench can run, read live from the platform with its current health. Turn an engine off to hide it from the Engine picker.</p>+ </div>+ <button class="wb-btn" id="wb-ext-refresh" type="button">Refresh status</button>+ </div>+ <p class="wb-label">Generation engines</p>+ <div class="wb-ext-grid" id="wb-ext-lanes" aria-busy="true"></div>+ <p class="wb-label" style="margin-top:24px">Mesh tools</p>+ <div class="wb-ext-grid" id="wb-ext-tools"></div>+ </div>+ </section>++ <!-- ── settings ────────────────────────────────────────── -->+ <section class="wb-view" data-view="settings" aria-label="Settings">+ <div class="wb-page">+ <div class="wb-page-head">+ <div>+ <h1>Settings</h1>+ <p>Preferences are kept in this browser. Nothing here needs an account.</p>+ </div>+ </div>+ <div class="wb-settings">+ <section class="wb-card">+ <h2>Viewport</h2>+ <label class="wb-param"><span>Show grid on start</span><select class="wb-select" data-setting="grid"><option value="1">On</option><option value="0">Off</option></select></label>+ <label class="wb-param"><span>Environment lighting</span><select class="wb-select" data-setting="env"><option value="1">On</option><option value="0">Off</option></select></label>+ <label class="wb-param"><span>Turntable after a generation</span><select class="wb-select" data-setting="spin"><option value="0">Off</option><option value="1">On</option></select></label>+ <label class="wb-param"><span>Theme</span><select class="wb-select" id="wb-theme-select"><option value="dark">Dark</option><option value="light">Light</option><option value="auto">Match system</option></select></label>+ </section>+ <section class="wb-card">+ <h2>Your data</h2>+ <p class="wb-hint">Generations are tied to an anonymous id for this browser, the same one <a href="/forge">Forge</a> uses, so your models show up in both.</p>+ <label class="wb-param"><span>Browser id</span><input class="wb-input" id="wb-client-id" readonly /></label>+ <div class="wb-row">+ <button class="wb-btn" id="wb-clear-history" type="button">Clear history</button>+ <button class="wb-btn is-danger" id="wb-reset-flows" type="button">Restore default workflows</button>+ </div>+ </section>+ <section class="wb-card">+ <h2>API and agents</h2>+ <p class="wb-hint">Everything the Workbench does is a public HTTP call, so scripts and agents can run the same pipeline. Upload an image, submit it, then poll the job. Full reference in the <a href="/docs/3d-api">3D API docs</a>.</p>+ <pre class="wb-code" id="wb-api-snippet"></pre>+ <button class="wb-btn" id="wb-copy-snippet" type="button">Copy</button>+ </section>+ </div>+ </div>+ </section>+ </div>++ <input type="file" id="wb-model-input" accept=".glb,.gltf,.obj,.stl,.ply,.fbx" hidden />+ <input type="file" id="wb-image-input" accept="image/png,image/jpeg,image/webp" hidden />+ <div class="wb-toasts" id="wb-toasts" aria-live="assertive"></div>++ <script src="/corner-stack.js"></script>+ <script src="/theme-switcher.js"></script>+ <script type="module" src="/src/workbench/main.js"></script>+ <script type="module" src="/i18n.js"></script>+</body>+</html>diff --git a/src/forge-workflows/editor.js b/src/forge-workflows/editor.jsnew file mode 100644index 000000000..fc30c69cd--- /dev/null+++ b/src/forge-workflows/editor.js@@ -0,0 +1,702 @@+// Forge Workflows: the canvas editor.+//+// A DOM node layer plus one SVG layer for links, both inside a "world" element+// that is panned and zoomed with a single CSS transform. Nodes are real DOM, so+// they are focusable, labelled and readable by assistive tech; the inspector+// offers keyboard-only linking for every input port.+//+// The editor never mutates the workflow it is given. Every edit goes through+// opts.commit(nextWorkflow, label), which owns undo history and autosave.++import { canConnect, connect, findPort, inputPorts, outputPorts, createNode } from './graph.js';+import { PALETTE } from './node-types.js';+import { h, svg, icon, ICONS } from './ui.js';++const MIN_ZOOM = 0.3;+const MAX_ZOOM = 2;+const GRID = 8;++const TYPE_LABEL = { image: 'image', text: 'text', mesh: '3D model' };++/**+ * @param {HTMLElement} root the canvas element+ * @param {object} opts+ * @param {object} opts.types+ * @param {() => object} opts.getWorkflow+ * @param {() => object} opts.getContext live catalog / Modly context for summaries+ * @param {(wf:object, label:string) => void} opts.commit+ * @param {(sel:{nodes:string[], edge:string|null}) => void} opts.onSelect+ * @param {(message:string) => void} opts.onError+ * @param {(nodeId:string) => HTMLElement} opts.resultHost persistent per-node result element+ */+export function createEditor(root, opts) {+ const { types } = opts;+ const view = { x: 40, y: 40, z: 1 };+ const selection = { nodes: new Set(), edge: null };+ let nodeStatus = new Map();+ let issuesByNode = new Map();+ let drag = null;++ const world = h('div', { class: 'fw-world' });+ const edgeLayer = svg('svg', { class: 'fw-edges', width: 1, height: 1, 'aria-hidden': 'true' });+ const nodeLayer = h('div', { class: 'fw-nodes' });+ world.append(edgeLayer, nodeLayer);+ root.append(world);++ const nodeEls = new Map();+ const tempPath = svg('path', { class: 'fw-edge is-temp' });++ // ── View transform ──────────────────────────────────────────────────────+ function applyView() {+ world.style.transform = `translate(${view.x}px, ${view.y}px) scale(${view.z})`;+ root.style.setProperty('--fw-grid', `${24 * view.z}px`);+ root.style.backgroundPosition = `${view.x}px ${view.y}px`;+ root.dataset.zoom = String(Math.round(view.z * 100));+ opts.onView?.(view.z);+ }++ function toWorld(clientX, clientY) {+ const r = root.getBoundingClientRect();+ return { x: (clientX - r.left - view.x) / view.z, y: (clientY - r.top - view.y) / view.z };+ }++ function zoomAt(factor, clientX, clientY) {+ const r = root.getBoundingClientRect();+ const cx = clientX ?? r.left + r.width / 2;+ const cy = clientY ?? r.top + r.height / 2;+ const before = toWorld(cx, cy);+ view.z = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, view.z * factor));+ view.x = cx - r.left - before.x * view.z;+ view.y = cy - r.top - before.y * view.z;+ applyView();+ }++ function fit() {+ const wf = opts.getWorkflow();+ const r = root.getBoundingClientRect();+ if (!wf.nodes.length || !r.width) {+ view.x = 40;+ view.y = 40;+ view.z = 1;+ applyView();+ return;+ }+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;+ for (const n of wf.nodes) {+ const el = nodeEls.get(n.id);+ const w = el?.offsetWidth || 220;+ const ht = el?.offsetHeight || 140;+ minX = Math.min(minX, n.x);+ minY = Math.min(minY, n.y);+ maxX = Math.max(maxX, n.x + w);+ maxY = Math.max(maxY, n.y + ht);+ }+ const pad = 48;+ const z = Math.min(1.1, Math.max(MIN_ZOOM, Math.min((r.width - pad * 2) / (maxX - minX), (r.height - pad * 2) / (maxY - minY))));+ view.z = z;+ view.x = (r.width - (maxX - minX) * z) / 2 - minX * z;+ view.y = (r.height - (maxY - minY) * z) / 2 - minY * z;+ applyView();+ }++ /** World coordinates of the visible centre, for placing a new node. */+ function centerPoint() {+ const r = root.getBoundingClientRect();+ const p = toWorld(r.left + r.width / 2, r.top + r.height / 2);+ const wf = opts.getWorkflow();+ let x = Math.round((p.x - 110) / GRID) * GRID;+ let y = Math.round((p.y - 60) / GRID) * GRID;+ // Step diagonally so repeated adds do not stack exactly on top of each other.+ while (wf.nodes.some((n) => Math.abs(n.x - x) < 16 && Math.abs(n.y - y) < 16)) {+ x += 24;+ y += 24;+ }+ return { x, y };+ }++ // ── Rendering ───────────────────────────────────────────────────────────+ function portRow(node, port, dir) {+ const row = h(+ 'div',+ { class: `fw-port is-${dir}`, dataset: { node: node.id, port: port.id, dir, type: port.type } },+ h('span', { class: 'fw-port-dot', title: `${port.label || port.id}: ${TYPE_LABEL[port.type]}${port.optional ? ' (optional)' : ''}` }),+ h('span', { class: 'fw-port-label' }, port.label || port.id, port.optional ? h('span', { class: 'fw-port-opt' }, ' optional') : null),+ );+ return row;+ }++ function buildNode(node) {+ const def = types[node.type];+ const ctx = opts.getContext();+ const ins = inputPorts(def, node.params);+ const outs = outputPorts(def, node.params);+ const el = h(+ 'div',+ {+ class: `fw-node cat-${def?.category || 'unknown'}`,+ tabindex: 0,+ role: 'group',+ 'aria-roledescription': 'workflow node',+ 'aria-label': `${def?.label || node.type} node`,+ dataset: { id: node.id, type: node.type },+ },+ h(+ 'div',+ { class: 'fw-node-head' },+ h('span', { class: 'fw-node-dot', 'aria-hidden': 'true' }),+ h('span', { class: 'fw-node-title' }, def?.label || node.type),+ h('span', { class: 'fw-node-badge', 'aria-live': 'polite' }),+ ),+ h(+ 'div',+ { class: 'fw-node-ports' },+ h('div', { class: 'fw-node-ins' }, ins.map((p) => portRow(node, p, 'in'))),+ h('div', { class: 'fw-node-outs' }, outs.map((p) => portRow(node, p, 'out'))),+ ),+ h('div', { class: 'fw-node-summary' }, def?.summary ? def.summary(node.params || {}, ctx) : ''),+ h('div', { class: 'fw-node-progress', hidden: true }, h('div', { class: 'fw-bar' }, h('span')), h('div', { class: 'fw-progress-label' })),+ h('div', { class: 'fw-node-issue', hidden: true }),+ );+ el.append(opts.resultHost(node.id));+ el.style.transform = `translate(${node.x}px, ${node.y}px)`;+ return el;+ }++ // The parts of a node card that need a rebuild when they change. Anything+ // else (position, summary) is patched in place, so a live 3D preview inside+ // the card is never torn down by an unrelated edit.+ function shapeKey(node) {+ const def = types[node.type];+ const ports = (list) => list.map((p) => `${p.id}:${p.type}:${p.label || ''}:${p.optional ? 1 : 0}`).join(',');+ return `${node.type}|${ports(inputPorts(def, node.params))}|${ports(outputPorts(def, node.params))}`;+ }++ function render() {+ const wf = opts.getWorkflow();+ const ctx = opts.getContext();+ const live = new Set();+ for (const n of wf.nodes) {+ live.add(n.id);+ const key = shapeKey(n);+ let el = nodeEls.get(n.id);+ if (!el || el.dataset.shape !== key) {+ const fresh = buildNode(n);+ fresh.dataset.shape = key;+ if (el) el.replaceWith(fresh);+ else nodeLayer.append(fresh);+ el = fresh;+ nodeEls.set(n.id, el);+ } else {+ el.style.transform = `translate(${n.x}px, ${n.y}px)`;+ const def = types[n.type];+ el.querySelector('.fw-node-summary').textContent = def?.summary ? def.summary(n.params || {}, ctx) : '';+ }+ }+ for (const [id, el] of nodeEls) {+ if (live.has(id)) continue;+ el.remove();+ nodeEls.delete(id);+ }+ for (const id of [...selection.nodes]) if (!nodeEls.has(id)) selection.nodes.delete(id);+ if (selection.edge && !wf.edges.some((e) => e.id === selection.edge)) selection.edge = null;+ paintSelection();+ paintStatus();+ paintIssues();+ drawEdges();+ }++ function portCenter(nodeId, portId, dir, positions) {+ const el = nodeEls.get(nodeId);+ const dot = el?.querySelector(`.fw-port[data-dir="${dir}"][data-port="${CSS.escape(portId)}"] .fw-port-dot`);+ if (!dot) return null;+ let x = dot.offsetWidth / 2;+ let y = dot.offsetHeight / 2;+ for (let cur = dot; cur && cur !== el; cur = cur.offsetParent) {+ x += cur.offsetLeft;+ y += cur.offsetTop;+ }+ const pos = positions?.get(nodeId) || opts.getWorkflow().nodes.find((n) => n.id === nodeId);+ return { x: pos.x + x, y: pos.y + y };+ }++ function curve(a, b) {+ const dx = Math.max(40, Math.abs(b.x - a.x) * 0.5);+ return `M${a.x},${a.y} C${a.x + dx},${a.y} ${b.x - dx},${b.y} ${b.x},${b.y}`;+ }++ function edgeState(e) {+ const src = nodeStatus.get(e.from.node)?.status;+ const dst = nodeStatus.get(e.to.node)?.status;+ if (dst === 'running') return 'is-flowing';+ if (src === 'done' && (dst === 'done' || dst === 'partial')) return 'is-done';+ return '';+ }++ function drawEdges(positions) {+ const wf = opts.getWorkflow();+ edgeLayer.textContent = '';+ for (const e of wf.edges) {+ const a = portCenter(e.from.node, e.from.port, 'out', positions);+ const b = portCenter(e.to.node, e.to.port, 'in', positions);+ if (!a || !b) continue;+ const type = findPort(types, wf.nodes.find((n) => n.id === e.from.node), e.from.port, 'out')?.type || 'mesh';+ const d = curve(a, b);+ const hit = svg('path', { class: 'fw-edge-hit', d });+ hit.dataset.edge = e.id;+ const path = svg('path', { class: `fw-edge type-${type} ${edgeState(e)} ${selection.edge === e.id ? 'is-selected' : ''}`, d });+ path.dataset.edge = e.id;+ edgeLayer.append(path, hit);+ }+ if (drag?.kind === 'connect') edgeLayer.append(tempPath);+ }++ function paintSelection() {+ for (const [id, el] of nodeEls) el.classList.toggle('is-selected', selection.nodes.has(id));+ }++ function paintStatus() {+ for (const [id, el] of nodeEls) {+ const s = nodeStatus.get(id);+ const status = s?.status || 'idle';+ el.dataset.status = status;+ const badge = el.querySelector('.fw-node-badge');+ const label = STATUS_LABEL[status] || '';+ const count = s && s.total > 1 ? ` ${s.done}/${s.total}` : '';+ badge.textContent = label ? `${label}${count}` : '';+ badge.className = `fw-node-badge is-${status}`;+ const prog = el.querySelector('.fw-node-progress');+ const p = s?.running?.progress;+ if (status === 'running') {+ prog.hidden = false;+ const bar = prog.querySelector('.fw-bar');+ bar.classList.toggle('is-indeterminate', p?.pct == null);+ bar.firstChild.style.transform = `scaleX(${p?.pct != null ? p.pct / 100 : 1})`;+ prog.querySelector('.fw-progress-label').textContent = progressText(p, s);+ } else {+ prog.hidden = true;+ }+ }+ }++ function paintIssues() {+ for (const [id, el] of nodeEls) {+ const list = issuesByNode.get(id) || [];+ const errors = list.filter((i) => i.level !== 'warning');+ el.classList.toggle('has-error', errors.length > 0);+ el.classList.toggle('has-warning', !errors.length && list.length > 0);+ const box = el.querySelector('.fw-node-issue');+ box.hidden = !list.length;+ box.textContent = list.length ? list[0].message.replace(/^[^:]+:\s*/, '') : '';+ }+ }++ // ── Interaction ─────────────────────────────────────────────────────────+ function select(ids, { additive = false } = {}) {+ if (!additive) selection.nodes.clear();+ for (const id of ids) {+ if (additive && selection.nodes.has(id)) selection.nodes.delete(id);+ else selection.nodes.add(id);+ }+ selection.edge = null;+ paintSelection();+ drawEdges();+ opts.onSelect({ nodes: [...selection.nodes], edge: null });+ }++ function selectEdge(id) {+ selection.nodes.clear();+ selection.edge = id;+ paintSelection();+ drawEdges();+ opts.onSelect({ nodes: [], edge: id });+ }++ function clearSelection() {+ if (!selection.nodes.size && !selection.edge) return;+ selection.nodes.clear();+ selection.edge = null;+ paintSelection();+ drawEdges();+ opts.onSelect({ nodes: [], edge: null });+ }++ function markTargets(from) {+ const wf = opts.getWorkflow();+ for (const el of root.querySelectorAll('.fw-port')) {+ const dir = el.dataset.dir;+ el.classList.remove('is-target-ok', 'is-target-bad');+ if (dir === from.dir) continue;+ const pair = from.dir === 'out' ? [{ node: from.node, port: from.port }, { node: el.dataset.node, port: el.dataset.port }] : [{ node: el.dataset.node, port: el.dataset.port }, { node: from.node, port: from.port }];+ const ok = canConnect(wf, types, pair[0], pair[1]).ok;+ el.classList.add(ok ? 'is-target-ok' : 'is-target-bad');+ }+ root.classList.add('is-connecting');+ }++ function clearTargets() {+ for (const el of root.querySelectorAll('.is-target-ok, .is-target-bad')) el.classList.remove('is-target-ok', 'is-target-bad');+ root.classList.remove('is-connecting');+ }++ root.addEventListener('pointerdown', (ev) => {+ if (ev.button !== 0 && ev.pointerType === 'mouse') return;+ closeQuickAdd();+ const portDot = ev.target.closest('.fw-port-dot');+ const nodeEl = ev.target.closest('.fw-node');+ const edgeHit = ev.target.closest('.fw-edge-hit');+ const interactive = ev.target.closest('a, button, input, select, textarea, model-viewer, .fw-result');++ if (portDot) {+ ev.preventDefault();+ startConnect(portDot.closest('.fw-port'), ev);+ return;+ }+ if (interactive) return;+ if (edgeHit) {+ selectEdge(edgeHit.dataset.edge);+ return;+ }+ if (nodeEl) {+ const id = nodeEl.dataset.id;+ if (ev.shiftKey || ev.metaKey || ev.ctrlKey) {+ select([id], { additive: true });+ return;+ }+ if (!selection.nodes.has(id)) select([id]);+ startMove(ev);+ return;+ }+ clearSelection();+ root.focus({ preventScroll: true });+ drag = { kind: 'pan', startX: ev.clientX, startY: ev.clientY, vx: view.x, vy: view.y, pointerId: ev.pointerId };+ root.setPointerCapture(ev.pointerId);+ root.classList.add('is-panning');+ });++ function startMove(ev) {+ const wf = opts.getWorkflow();+ const start = toWorld(ev.clientX, ev.clientY);+ const origin = new Map(wf.nodes.filter((n) => selection.nodes.has(n.id)).map((n) => [n.id, { x: n.x, y: n.y }]));+ drag = { kind: 'move', start, origin, moved: false, pointerId: ev.pointerId, positions: null };+ root.setPointerCapture(ev.pointerId);+ }++ function startConnect(portEl, ev) {+ const wf = opts.getWorkflow();+ let from = { node: portEl.dataset.node, port: portEl.dataset.port, dir: portEl.dataset.dir, type: portEl.dataset.type };+ let detached = null;+ // Grabbing a linked input picks the link up from its source, so it can be+ // moved to another input or dropped on empty canvas to delete it.+ if (from.dir === 'in') {+ const existing = wf.edges.find((e) => e.to.node === from.node && e.to.port === from.port);+ if (existing) {+ detached = existing;+ const srcNode = wf.nodes.find((n) => n.id === existing.from.node);+ from = { node: existing.from.node, port: existing.from.port, dir: 'out', type: findPort(types, srcNode, existing.from.port, 'out')?.type };+ }+ }+ const anchor = portCenter(from.node, from.port, from.dir);+ drag = { kind: 'connect', from, anchor, detached, pointerId: ev.pointerId };+ root.setPointerCapture(ev.pointerId);+ if (detached) {+ const without = { ...wf, edges: wf.edges.filter((e) => e.id !== detached.id) };+ drag.base = without;+ }+ markTargets(from);+ tempPath.setAttribute('class', `fw-edge is-temp type-${from.type}`);+ updateTemp(ev);+ drawEdges();+ }++ function updateTemp(ev) {+ const p = toWorld(ev.clientX, ev.clientY);+ const { anchor, from } = drag;+ tempPath.setAttribute('d', from.dir === 'out' ? curve(anchor, p) : curve(p, anchor));+ }++ root.addEventListener('pointermove', (ev) => {+ if (!drag || ev.pointerId !== drag.pointerId) return;+ if (drag.kind === 'pan') {+ view.x = drag.vx + ev.clientX - drag.startX;+ view.y = drag.vy + ev.clientY - drag.startY;+ applyView();+ } else if (drag.kind === 'move') {+ const p = toWorld(ev.clientX, ev.clientY);+ const dx = p.x - drag.start.x;+ const dy = p.y - drag.start.y;+ if (!drag.moved && Math.hypot(dx, dy) < 3) return;+ drag.moved = true;+ const positions = new Map(opts.getWorkflow().nodes.map((n) => [n.id, { x: n.x, y: n.y }]));+ for (const [id, o] of drag.origin) {+ const x = Math.round((o.x + dx) / GRID) * GRID;+ const y = Math.round((o.y + dy) / GRID) * GRID;+ positions.set(id, { x, y });+ const el = nodeEls.get(id);+ if (el) el.style.transform = `translate(${x}px, ${y}px)`;+ }+ drag.positions = positions;+ root.classList.add('is-dragging');+ drawEdges(positions);+ } else if (drag.kind === 'connect') {+ updateTemp(ev);+ const over = document.elementFromPoint(ev.clientX, ev.clientY)?.closest('.fw-port');+ for (const el of root.querySelectorAll('.fw-port.is-hover')) el.classList.remove('is-hover');+ over?.classList.add('is-hover');+ }+ });++ function endDrag(ev) {+ if (!drag || ev.pointerId !== drag.pointerId) return;+ const d = drag;+ drag = null;+ try {+ root.releasePointerCapture(ev.pointerId);+ } catch {+ // Capture was already released by the browser.+ }+ root.classList.remove('is-panning', 'is-dragging');+ if (d.kind === 'move' && d.moved && d.positions) {+ const wf = opts.getWorkflow();+ const nodes = wf.nodes.map((n) => (d.origin.has(n.id) ? { ...n, ...d.positions.get(n.id) } : n));+ opts.commit({ ...wf, nodes }, d.origin.size > 1 ? 'Move nodes' : 'Move node');+ } else if (d.kind === 'connect') {+ clearTargets();+ for (const el of root.querySelectorAll('.fw-port.is-hover')) el.classList.remove('is-hover');+ finishConnect(d, ev);+ }+ }+ root.addEventListener('pointerup', endDrag);+ root.addEventListener('pointercancel', (ev) => {+ if (drag?.kind === 'connect') clearTargets();+ endDrag(ev);+ render();+ });++ function finishConnect(d, ev) {+ const base = d.base || opts.getWorkflow();+ const target = document.elementFromPoint(ev.clientX, ev.clientY)?.closest('.fw-port');+ if (target && target.dataset.dir !== d.from.dir) {+ const pair = d.from.dir === 'out' ? [{ node: d.from.node, port: d.from.port }, { node: target.dataset.node, port: target.dataset.port }] : [{ node: target.dataset.node, port: target.dataset.port }, { node: d.from.node, port: d.from.port }];+ const res = connect(base, types, pair[0], pair[1]);+ if (res.error) {+ opts.onError(res.error);+ drawEdges();+ return;+ }+ opts.commit(res.workflow, 'Link nodes');+ return;+ }+ if (d.detached) {+ opts.commit(base, 'Remove link');+ return;+ }+ if (!target && d.from.dir === 'out') {+ openQuickAdd(d.from, ev);+ return;+ }+ drawEdges();+ }++ // Drop a link on empty canvas: offer the nodes that can take it.+ let quickAdd = null;+ function openQuickAdd(from, ev) {+ const wf = opts.getWorkflow();+ const at = toWorld(ev.clientX, ev.clientY);+ const choices = [];+ for (const group of PALETTE) {+ for (const type of group.types) {+ const def = types[type];+ const probe = createNode(types, type, at);+ const port = inputPorts(def, probe.params).find((p) => p.type === from.type);+ if (port) choices.push({ type, def, port: port.id });+ }+ }+ if (!choices.length) {+ drawEdges();+ return;+ }+ const r = root.getBoundingClientRect();+ const menu = h(+ 'div',+ { class: 'fw-quickadd', role: 'menu', 'aria-label': `Add a node that takes ${TYPE_LABEL[from.type]}`, style: { left: `${ev.clientX - r.left}px`, top: `${ev.clientY - r.top}px` } },+ h('div', { class: 'fw-quickadd-title' }, `Add a step that takes ${TYPE_LABEL[from.type]}`),+ choices.map((c) =>+ h(+ 'button',+ {+ type: 'button',+ role: 'menuitem',+ class: `fw-quickadd-item cat-${c.def.category}`,+ on: {+ click: () => {+ const node = createNode(types, c.type, { x: Math.round(at.x / GRID) * GRID, y: Math.round((at.y - 30) / GRID) * GRID });+ const added = { ...wf, nodes: [...wf.nodes, node] };+ const res = connect(added, types, { node: from.node, port: from.port }, { node: node.id, port: c.port });+ closeQuickAdd();+ opts.commit(res.workflow, `Add ${c.def.label}`);+ select([node.id]);+ },+ },+ },+ h('span', { class: 'fw-node-dot', 'aria-hidden': 'true' }),+ c.def.label,+ ),+ ),+ );+ menu.addEventListener('keydown', (e) => {+ const items = [...menu.querySelectorAll('button')];+ const i = items.indexOf(document.activeElement);+ if (e.key === 'ArrowDown') {+ e.preventDefault();+ items[(i + 1) % items.length].focus();+ } else if (e.key === 'ArrowUp') {+ e.preventDefault();+ items[(i - 1 + items.length) % items.length].focus();+ } else if (e.key === 'Escape') {+ e.preventDefault();+ closeQuickAdd();+ root.focus();+ }+ });+ root.append(menu);+ quickAdd = menu;+ menu.querySelector('button')?.focus();+ drawEdges();+ }+ function closeQuickAdd() {+ quickAdd?.remove();+ quickAdd = null;+ }++ root.addEventListener(+ 'wheel',+ (ev) => {+ if (ev.target.closest('.fw-result model-viewer, .fw-quickadd')) return;+ ev.preventDefault();+ if (ev.ctrlKey || ev.metaKey) {+ zoomAt(Math.exp(-ev.deltaY * 0.0025), ev.clientX, ev.clientY);+ } else {+ view.x -= ev.deltaX;+ view.y -= ev.deltaY;+ applyView();+ }+ },+ { passive: false },+ );++ root.addEventListener('focusin', (ev) => {+ const nodeEl = ev.target.closest?.('.fw-node');+ if (nodeEl && ev.target === nodeEl && !selection.nodes.has(nodeEl.dataset.id)) select([nodeEl.dataset.id]);+ });++ // Drop from the palette.+ root.addEventListener('dragover', (ev) => {+ if (ev.dataTransfer?.types?.includes('application/x-fw-node')) {+ ev.preventDefault();+ ev.dataTransfer.dropEffect = 'copy';+ }+ });+ root.addEventListener('drop', (ev) => {+ const type = ev.dataTransfer?.getData('application/x-fw-node');+ if (!type || !types[type]) return;+ ev.preventDefault();+ const p = toWorld(ev.clientX, ev.clientY);+ addNode(type, { x: Math.round((p.x - 110) / GRID) * GRID, y: Math.round((p.y - 24) / GRID) * GRID });+ });++ function addNode(type, at = centerPoint()) {+ const wf = opts.getWorkflow();+ const node = createNode(types, type, at);+ opts.commit({ ...wf, nodes: [...wf.nodes, node] }, `Add ${types[type].label}`);+ select([node.id]);+ nodeEls.get(node.id)?.focus({ preventScroll: true });+ return node;+ }++ /** Move the selected nodes with the keyboard. */+ function nudge(dx, dy) {+ if (!selection.nodes.size) return false;+ const wf = opts.getWorkflow();+ const nodes = wf.nodes.map((n) => (selection.nodes.has(n.id) ? { ...n, x: n.x + dx, y: n.y + dy } : n));+ opts.commit({ ...wf, nodes }, 'Move node');+ return true;+ }++ function focusNode(id) {+ const wf = opts.getWorkflow();+ const n = wf.nodes.find((x) => x.id === id);+ const el = nodeEls.get(id);+ if (!n || !el) return;+ const r = root.getBoundingClientRect();+ view.x = r.width / 2 - (n.x + el.offsetWidth / 2) * view.z;+ view.y = r.height / 2 - (n.y + el.offsetHeight / 2) * view.z;+ applyView();+ select([id]);+ el.focus({ preventScroll: true });+ }++ applyView();++ return {+ render,+ fit,+ zoomIn: () => zoomAt(1.2),+ zoomOut: () => zoomAt(1 / 1.2),+ addNode,+ nudge,+ focusNode,+ select,+ clearSelection,+ get selection() {+ return { nodes: [...selection.nodes], edge: selection.edge };+ },+ setStatus(map) {+ nodeStatus = map;+ paintStatus();+ drawEdges();+ },+ setIssues(issues) {+ issuesByNode = new Map();+ for (const i of issues) {+ if (!i.nodeId) continue;+ if (!issuesByNode.has(i.nodeId)) issuesByNode.set(i.nodeId, []);+ issuesByNode.get(i.nodeId).push(i);+ }+ paintIssues();+ },+ /** Refresh summaries without a full rebuild (live catalog arrived). */+ refreshSummaries() {+ const wf = opts.getWorkflow();+ const ctx = opts.getContext();+ for (const n of wf.nodes) {+ const el = nodeEls.get(n.id);+ const def = types[n.type];+ if (el && def?.summary) el.querySelector('.fw-node-summary').textContent = def.summary(n.params || {}, ctx);+ }+ },+ get zoom() {+ return view.z;+ },+ };+}++const STATUS_LABEL = {+ pending: 'Waiting',+ running: 'Running',+ done: 'Done',+ partial: 'Partial',+ failed: 'Failed',+ cancelled: 'Cancelled',+ skipped: 'Skipped',+};++export function progressText(p, s) {+ if (!p) return s?.total > 1 ? `Item ${(s.running?.iter ?? 0) + 1} of ${s.total}` : 'Starting';+ const parts = [p.label || 'Working'];+ if (p.pct != null) parts.push(`${p.estimate ? '~' : ''}${p.pct}%`);+ if (p.elapsed != null) parts.push(p.eta ? `${p.elapsed}s of ~${p.eta}s` : `${p.elapsed}s`);+ if (s?.total > 1) parts.push(`item ${(s.running?.iter ?? 0) + 1}/${s.total}`);+ return parts.join(' · ');+}++export { icon, ICONS };diff --git a/src/forge-workflows/executors.js b/src/forge-workflows/executors.jsnew file mode 100644index 000000000..169ec9e6b--- /dev/null+++ b/src/forge-workflows/executors.js@@ -0,0 +1,620 @@+// Forge Workflows: what each node actually does.+//+// Every executor calls a real three.ws endpoint (or the user's own Modly app on+// localhost) and returns { outputs, result }. `outputs` feeds the next node;+// `result` is what the node card shows (a viewer, a download, a saved link).+//+// Contracts used, all documented in docs/forge-workflows.md:+// POST /api/forge generate (text or image) GET ?job= poll+// POST /api/forge?action=rig auto-rig GET ?job= poll+// POST /api/forge-remesh | -segment | -stylize | -gameready GET ?job= poll+// POST /api/forge-upload presigned PUT for a photo+// POST /api/scene-glb-upload presigned PUT for a GLB+// POST /api/avatars/from-forge save to the signed-in library+// POST /api/creations {op:'publish'} publish to the public gallery++import { StepError } from './runner.js';+import { attachTierPass, getAccess, getTierPass } from '../three-access.js';+import { generateWithModly, MODLY_INSTALL_URL } from '../modly-local.js';++const POLL_MS = 2500;+const POLL_MAX_BACKOFF_MS = 15000;+const JOB_TIMEOUT_MS = 15 * 60 * 1000;+const IMAGE_MAX_BYTES = 8 * 1024 * 1024;+const GLB_MAX_BYTES = 200 * 1024 * 1024;+const IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/webp'];++// ── Identity ─────────────────────────────────────────────────────────────────++// The same anonymous handle /forge uses, so a workflow's generations land in the+// same "My creations" list as the ones made on /forge.+const CLIENT_ID = (() => {+ const KEY = 'forge:cid';+ try {+ let id = localStorage.getItem(KEY);+ if (!id) {+ id = crypto.randomUUID();+ localStorage.setItem(KEY, id);+ }+ return id;+ } catch {+ return `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;+ }+})();++// `x-witness: handled`: this page renders a designed state for every error the+// forge endpoints answer with, so the session recorder should not treat them as+// unhandled failures.+export const CLIENT_HEADERS = Object.freeze({ 'x-forge-client': CLIENT_ID, 'x-witness': 'handled' });++function headers(extra = {}) {+ return attachTierPass({ ...CLIENT_HEADERS, ...extra });+}++// ── Plumbing ─────────────────────────────────────────────────────────────────++function sleep(ms, signal) {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) return reject(new DOMException('Cancelled', 'AbortError'));+ const t = setTimeout(() => {+ signal?.removeEventListener('abort', onAbort);+ resolve();+ }, ms);+ const onAbort = () => {+ clearTimeout(t);+ reject(new DOMException('Cancelled', 'AbortError'));+ };+ signal?.addEventListener('abort', onAbort, { once: true });+ });+}++async function request(url, { method = 'GET', body, signal, extraHeaders = {}, credentials } = {}) {+ let res;+ try {+ res = await fetch(url, {+ method,+ signal,+ credentials,+ headers: headers(body !== undefined ? { 'content-type': 'application/json', ...extraHeaders } : extraHeaders),+ body: body !== undefined ? JSON.stringify(body) : undefined,+ });+ } catch (err) {+ if (signal?.aborted) throw err;+ const e = new StepError('Could not reach three.ws. Check your connection, then retry this step.', { code: 'network' });+ e.transport = true;+ throw e;+ }+ const data = await res.json().catch(() => ({}));+ return { res, data };+}++const SIGN_IN = () => ({ label: 'Sign in', href: `/login?next=${encodeURIComponent(location.pathname + location.search)}` });++/** Turn a non-2xx endpoint answer into an error the node card can act on. */+export function errorFromResponse(res, data, what) {+ const msg = (fallback) => data?.message || data?.error_description || fallback;+ if (res.status === 429 || data?.error === 'rate_limited') {+ const secs = Math.max(1, Math.ceil(Number(data?.retry_after) || Number(res.headers?.get?.('ratelimit-reset')) || 30));+ return new StepError(`${what} is rate limited right now. Retry in about ${secs}s.`, { code: 'rate_limited', retryAfter: secs });+ }+ if (res.status === 402 && data?.error === 'three_hold_required') {+ const actions = [];+ if (data.acquire?.swap_url) actions.push({ label: 'Get $THREE', href: data.acquire.swap_url });+ actions.push({ label: 'Holder perks', href: '/three' });+ return new StepError(msg(`${what} is a $THREE holder perk.`), { code: 'hold_required', actions });+ }+ if (res.status === 401) {+ return new StepError(msg(`Sign in to use ${what}.`), { code: 'auth', action: SIGN_IN() });+ }+ if (data?.error === 'needs_key' || data?.error === 'invalid_key') {+ return new StepError(msg('This engine needs your own API key.'), { code: data.error, action: { label: 'Open Forge', href: '/forge' } });+ }+ if (data?.error === 'image_not_usable') {+ return new StepError(msg('That photo does not look usable for 3D. Try a clearer photo of a single object.'), { code: 'image_not_usable' });+ }+ if (res.status === 503 || data?.error === 'unconfigured' || data?.error === 'storage_unavailable' || data?.error === 'provider_busy') {+ const secs = Number(data?.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 0;+ return new StepError(msg(`${what} is temporarily unavailable.`) + (secs ? ` Retry in about ${secs}s.` : ''), { code: data?.error || 'unavailable', retryAfter: secs });+ }+ return new StepError(msg(`${what} failed (HTTP ${res.status}).`), { code: data?.error || `http_${res.status}` });+}++function estimateProgress(elapsedSec, etaSec) {+ if (!(etaSec > 0) || !(elapsedSec >= 0)) return null;+ return Math.min(95, Math.round((elapsedSec / etaSec) * 100));+}++/**+ * Poll a job until it finishes. `read(data)` maps a poll answer to+ * { done: value } | { failed: message } | { pending: 'queued'|'running' }.+ * Transport hiccups back off and keep going; the server owns the job.+ */+async function pollJob(url, { signal, progress, what, etaSeconds, read }) {+ const started = Date.now();+ let delay = POLL_MS;+ for (;;) {+ await sleep(delay, signal);+ if (Date.now() - started > JOB_TIMEOUT_MS) {+ throw new StepError(`${what} did not finish within ${Math.round(JOB_TIMEOUT_MS / 60000)} minutes. Retry this step.`, { code: 'timeout' });+ }+ let res, data;+ try {+ ({ res, data } = await request(url, { signal }));+ } catch (err) {+ if (err?.transport) {+ progress({ label: 'Connection unstable, still waiting', pct: null });+ delay = Math.min(POLL_MAX_BACKOFF_MS, delay * 2);+ continue;+ }+ throw err;+ }+ delay = POLL_MS;+ if (res.status === 429) {+ delay = Math.min(POLL_MAX_BACKOFF_MS, Math.max(POLL_MS, (Number(data?.retry_after) || 5) * 1000));+ continue;+ }+ // A 502 without a status is the worker blinking; keep polling.+ if (res.status >= 500 && !data?.status) continue;+ if (!res.ok) throw errorFromResponse(res, data, what);+ const step = read(data);+ if (step.done) return step.done;+ if (step.failed) throw new StepError(`${what} failed: ${step.failed}`, { code: 'job_failed' });+ const elapsed = Number.isFinite(data.elapsed_seconds) ? data.elapsed_seconds : (Date.now() - started) / 1000;+ const eta = Number(data.eta_seconds) || etaSeconds || 0;+ const pct = estimateProgress(elapsed, eta);+ progress({+ label: step.pending === 'queued' ? 'Queued for a GPU' : 'Working',+ pct,+ estimate: pct != null,+ elapsed: Math.round(elapsed),+ eta: eta || null,+ });+ }+}++// ── Uploads ──────────────────────────────────────────────────────────────────++// Local bytes for URLs this page uploaded, so a Modly run can send the original+// photo without downloading it again.+const localBlobs = new Map();++async function presignAndPut(endpoint, file, contentType, { signal, what }) {+ const { res, data } = await request(endpoint, { method: 'POST', body: { content_type: contentType, size_bytes: file.size }, signal });+ if (!res.ok || !data.upload_url) throw errorFromResponse(res, data, what);+ let put;+ try {+ put = await fetch(data.upload_url, { method: data.method || 'PUT', headers: data.headers || { 'content-type': contentType }, body: file, signal });+ } catch (err) {+ if (signal?.aborted) throw err;+ throw new StepError(`${what} could not reach storage. Check your connection and try again.`, { code: 'network' });+ }+ if (!put.ok) throw new StepError(`${what} was rejected by storage (HTTP ${put.status}). Try again.`, { code: 'upload_failed' });+ localBlobs.set(data.public_url, file);+ return data.public_url;+}++/** Upload a photo the user picked. Resolves { url, name }. */+export async function uploadImage(file, { signal } = {}) {+ const type = IMAGE_TYPES.includes(file.type) ? file.type : null;+ if (!type) throw new StepError('Use a PNG, JPEG or WebP photo.', { code: 'bad_type' });+ if (file.size > IMAGE_MAX_BYTES) throw new StepError('That photo is over 8 MB. Use a smaller one.', { code: 'too_large' });+ const url = await presignAndPut('/api/forge-upload', file, type, { signal, what: 'The photo upload' });+ return { url, name: file.name || 'photo' };+}++/** Upload a GLB (a local file, or a mesh made on the user's GPU). Resolves the public URL. */+export async function uploadGlb(blob, { signal } = {}) {+ if (blob.size > GLB_MAX_BYTES) throw new StepError('That model is over 200 MB, the upload limit.', { code: 'too_large' });+ const head = new Uint8Array(await blob.slice(0, 4).arrayBuffer());+ if (String.fromCharCode(...head) !== 'glTF') throw new StepError('That file is not a binary glTF (.glb).', { code: 'bad_type' });+ return presignAndPut('/api/scene-glb-upload', blob, 'model/gltf-binary', { signal, what: 'The model upload' });+}++/** A mesh value as a public https URL, uploading local bytes when needed. */+async function publicMeshUrl(mesh, { signal, progress }) {+ if (!mesh) throw new StepError('No model arrived from the previous step.', { code: 'no_input' });+ if (mesh.url) return mesh.url;+ if (!mesh.blob) throw new StepError('The previous step produced no model.', { code: 'no_input' });+ progress({ label: 'Uploading the model', pct: null });+ mesh.url = await uploadGlb(mesh.blob, { signal });+ return mesh.url;+}++async function imageBlob(image, signal) {+ if (image.blob) return image.blob;+ const cached = localBlobs.get(image.url);+ if (cached) return cached;+ let res;+ try {+ res = await fetch(image.url, { signal });+ } catch (err) {+ if (signal?.aborted) throw err;+ throw new StepError('Could not download the photo to send to Modly. Upload it again.', { code: 'network' });+ }+ if (!res.ok) throw new StepError(`The photo is no longer available (HTTP ${res.status}). Upload it again.`, { code: 'gone' });+ return res.blob();+}++// $THREE gated calls carry the holder's tier pass. A wallet-only holder signs a+// free message once; a non-holder is never asked to sign.+async function primeTierProof(feature) {+ try {+ const access = await getAccess(feature, { fresh: true });+ await getTierPass({ interactive: Boolean(access?.access?.eligible ?? access?.eligible) });+ } catch {+ // No proof just means the request goes out unproven and the server answers+ // with its normal hold-or-pay message.+ }+}++// ── Generation ───────────────────────────────────────────────────────────────++function mintProgressId() {+ return crypto.randomUUID().replace(/[^A-Za-z0-9_-]/g, '').slice(0, 48);+}++const CRUMB_LABEL = {+ directed: 'Prompt art-directed',+ reference: 'Reference image ready',+ views: 'Turnaround views painted',+ submitting: 'Sending to the 3D engine',+};++// While the generate POST is still open (prompt direction, reference image),+// read the server's milestone crumbs so the node shows real stages instead of a+// silent spinner.+function watchCrumbs(traceId, progress, signal) {+ let stopped = false;+ const tick = async () => {+ while (!stopped && !signal.aborted) {+ await sleep(POLL_MS, signal).catch(() => {});+ if (stopped || signal.aborted) return;+ try {+ const res = await fetch(`/api/forge?progress=${encodeURIComponent(traceId)}`, { headers: CLIENT_HEADERS, signal });+ if (!res.ok) {+ if (res.status !== 429) return;+ continue;+ }+ const data = await res.json();+ const last = Array.isArray(data?.progress) ? data.progress[data.progress.length - 1] : null;+ const reference = data.progress.find((c) => c.stage === 'reference')?.preview_image_url || null;+ if (!stopped && CRUMB_LABEL[last?.stage]) progress({ label: CRUMB_LABEL[last.stage], pct: null, preview: reference });+ } catch {+ return;+ }+ }+ };+ tick();+ return () => {+ stopped = true;+ };+}++async function generateOnCloud({ params, inputs, signal, progress }) {+ const text = typeof inputs.prompt === 'string' ? inputs.prompt.trim() : '';+ const body = { tier: params.tier || 'draft', path: 'image' };+ if (params.engine && params.engine !== 'auto') body.backend = params.engine;+ if (params.mode === 'image') {+ if (!inputs.image?.url) throw new StepError('No photo arrived from the previous step.', { code: 'no_input' });+ body.image_urls = [inputs.image.url];+ if (text) body.prompt = text.slice(0, 1000);+ } else {+ if (!text) throw new StepError('The prompt is empty.', { code: 'no_input' });+ body.prompt = text.slice(0, 1000);+ body.director = true;+ }+ if (body.tier === 'high') await primeTierProof('forge.high');+ const traceId = mintProgressId();+ body.progress_id = traceId;++ progress({ label: params.mode === 'image' ? 'Submitting the photo' : 'Art-directing the prompt', pct: null });+ const stopCrumbs = watchCrumbs(traceId, progress, signal);+ let res, data;+ try {+ ({ res, data } = await request('/api/forge', { method: 'POST', body, signal }));+ } finally {+ stopCrumbs();+ }+ if (!res.ok) throw errorFromResponse(res, data, 'Generation');++ let done = data;+ if (!(data.status === 'done' && data.glb_url)) {+ if (!data.job_id) throw new StepError(data.message || 'The generator did not return a job.', { code: 'no_job' });+ progress({ label: 'Queued for a GPU', pct: 0, estimate: true, eta: data.eta_seconds || null, preview: data.preview_image_url || null });+ done = await pollJob(`/api/forge?job=${encodeURIComponent(data.job_id)}`, {+ signal,+ progress,+ what: 'Generation',+ etaSeconds: data.eta_seconds,+ read: (d) => (d.status === 'done' && d.glb_url ? { done: d } : d.status === 'failed' ? { failed: d.error || d.message || 'the engine gave up' } : { pending: d.status }),+ });+ }+ const mesh = {+ url: done.glb_url,+ filename: 'forge-model.glb',+ creationId: done.creation_id || data.creation_id || null,+ jobId: data.job_id || null,+ backend: done.backend || data.backend || null,+ previewImageUrl: done.preview_image_url || data.preview_image_url || null,+ prompt: body.prompt || null,+ };+ return {+ outputs: { mesh },+ result: {+ mesh,+ note: mesh.creationId ? 'Saved to My creations automatically.' : '',+ links: mesh.creationId ? [{ label: 'Open model page', href: `/m/${encodeURIComponent(mesh.creationId)}` }] : [],+ cached: Boolean(data.cached),+ },+ };+}++async function generateOnModly({ params, inputs, signal, progress, modly }) {+ if (!modly?.origin) throw new StepError('Connect Modly first: select this node and press Connect.', { code: 'modly_offline' });+ if (!inputs.image) throw new StepError('No photo arrived from the previous step.', { code: 'no_input' });+ const image = await imageBlob(inputs.image, signal);+ try {+ const out = await generateWithModly(modly.origin, {+ image,+ modelId: params.modlyModel,+ signal,+ onProgress: (pct, step) => progress({ label: step || 'Generating on your GPU', pct, estimate: false }),+ });+ const mesh = { url: null, blob: out.blob, filename: out.filename, jobId: out.jobId, backend: `modly:${out.modelId}` };+ return { outputs: { mesh }, result: { mesh, note: 'Made on your GPU. It uploads to three.ws only if a later step needs it.' } };+ } catch (err) {+ if (signal.aborted || err?.code === 'CANCELLED') throw err;+ throw new StepError(err?.message || 'Modly could not finish the generation.', { code: `modly_${String(err?.code || 'failed').toLowerCase()}`, action: { label: 'Get Modly', href: MODLY_INSTALL_URL } });+ }+}++// ── Processing ───────────────────────────────────────────────────────────────++/** Submit a mesh job to one of the forge processing endpoints and wait for it. */+async function processMesh({ endpoint, what, body, signal, progress, feature, pick }) {+ if (feature) await primeTierProof(feature);+ progress({ label: `Submitting to ${what}`, pct: null });+ const { res, data } = await request(endpoint, { method: 'POST', body, signal });+ if (!res.ok || !data.job_id) throw errorFromResponse(res, data, what);+ const done = await pollJob(`${endpoint}?job=${encodeURIComponent(data.job_id)}`, {+ signal,+ progress,+ what,+ etaSeconds: data.eta_seconds,+ read: (d) => {+ if (d.status === 'failed') return { failed: d.error || 'the worker gave up' };+ const url = d.status === 'done' ? pick(d) : null;+ return url ? { done: d } : { pending: d.status };+ },+ });+ return { done, url: pick(done) };+}++function meshFrom(prev, url, extra = {}) {+ return { url, filename: prev?.filename || 'forge-model.glb', prompt: prev?.prompt || null, creationId: null, ...extra };+}++// ── Export ───────────────────────────────────────────────────────────────────++let threePromise = null;+function loadThree() {+ threePromise ||= Promise.all([+ import('three/addons/loaders/GLTFLoader.js'),+ import('three/addons/loaders/DRACOLoader.js'),+ import('three/addons/libs/meshopt_decoder.module.js'),+ import('three/addons/exporters/STLExporter.js'),+ import('three/addons/exporters/OBJExporter.js'),+ import('three/addons/exporters/PLYExporter.js'),+ ]).then(([gltf, draco, meshopt, stl, obj, ply]) => ({ gltf, draco, meshopt, stl, obj, ply }));+ return threePromise;+}++async function meshArrayBuffer(mesh, signal) {+ if (mesh.blob) return mesh.blob.arrayBuffer();+ let res;+ try {+ res = await fetch(mesh.url, { signal });+ } catch (err) {+ if (signal?.aborted) throw err;+ throw new StepError('Could not download the model to convert it. Check your connection and retry.', { code: 'network' });+ }+ if (!res.ok) throw new StepError(`The model is no longer available (HTTP ${res.status}).`, { code: 'gone' });+ return res.arrayBuffer();+}++async function convertInBrowser(mesh, format, signal) {+ const t = await loadThree();+ const buf = await meshArrayBuffer(mesh, signal);+ const loader = new t.gltf.GLTFLoader();+ const draco = new t.draco.DRACOLoader();+ draco.setDecoderPath('/three/draco/gltf/');+ loader.setDRACOLoader(draco);+ loader.setMeshoptDecoder(t.meshopt.MeshoptDecoder);+ let gltf;+ try {+ gltf = await loader.parseAsync(buf, '');+ } catch (err) {+ throw new StepError(`Could not read the model to convert it: ${err?.message || 'invalid glTF'}.`, { code: 'parse_failed' });+ } finally {+ draco.dispose();+ }+ if (format === 'stl') return new Blob([new t.stl.STLExporter().parse(gltf.scene, { binary: true })], { type: 'model/stl' });+ if (format === 'obj') return new Blob([new t.obj.OBJExporter().parse(gltf.scene)], { type: 'model/obj' });+ const ply = await new Promise((resolve, reject) => {+ try {+ new t.ply.PLYExporter().parse(gltf.scene, resolve, { binary: true });+ } catch (err) {+ reject(err);+ }+ });+ return new Blob([ply], { type: 'application/octet-stream' });+}++function triggerDownload(href, filename) {+ const a = document.createElement('a');+ a.href = href;+ a.download = filename;+ a.rel = 'noopener';+ document.body.appendChild(a);+ a.click();+ a.remove();+}++// ── Executors ────────────────────────────────────────────────────────────────++export const EXECUTORS = {+ async prompt({ params }) {+ return { outputs: { text: String(params.text || '').trim() } };+ },++ async image({ params }) {+ const image = (params.images || [])[0];+ if (!image?.url) throw new StepError('Upload a photo first.', { code: 'no_input' });+ return { outputs: { image: { url: image.url, name: image.name } }, result: { image } };+ },++ async loadMesh({ params }) {+ const url = String(params.url || '').trim();+ if (!/^https:\/\//i.test(url)) throw new StepError('Add an https link to a .glb, or upload one.', { code: 'no_input' });+ const mesh = { url, filename: (params.name || url.split('/').pop() || 'model.glb').replace(/[?#].*$/, ''), creationId: null };+ return { outputs: { mesh }, result: { mesh } };+ },++ async generate(ctx) {+ return ctx.params.engine === 'modly' ? generateOnModly(ctx) : generateOnCloud(ctx);+ },++ async rig({ inputs, signal, progress }) {+ const glbUrl = await publicMeshUrl(inputs.mesh, { signal, progress });+ progress({ label: 'Submitting to the rigger', pct: null });+ const { res, data } = await request('/api/forge?action=rig', { method: 'POST', body: { glb_url: glbUrl }, signal });+ if (!res.ok || !data.job_id) {+ if (res.status === 501 || data.error === 'rig_unconfigured') throw new StepError(data.message || 'Auto-rigging is not available right now.', { code: 'rig_unconfigured' });+ throw errorFromResponse(res, data, 'Auto-rig');+ }+ const done = await pollJob(`/api/forge?job=${encodeURIComponent(data.job_id)}`, {+ signal,+ progress,+ what: 'Auto-rig',+ etaSeconds: data.eta_seconds || 90,+ read: (d) => (d.status === 'done' && d.glb_url ? { done: d } : d.status === 'failed' ? { failed: d.error || 'the rigger gave up' } : { pending: d.status }),+ });+ const mesh = meshFrom(inputs.mesh, done.glb_url, { creationId: done.creation_id || null, rigged: true });+ return {+ outputs: { mesh },+ result: { mesh, links: mesh.creationId ? [{ label: 'Open model page', href: `/m/${encodeURIComponent(mesh.creationId)}` }] : [] },+ };+ },++ async remesh({ params, inputs, signal, progress }) {+ const meshUrl = await publicMeshUrl(inputs.mesh, { signal, progress });+ const body = { mesh_url: meshUrl, remesh_mode: params.mode, target_faces: Number(params.targetFaces), texture_size: Number(params.textureSize), output_format: 'glb' };+ if (params.mode === 'triangle') body.operation = params.operation;+ const { done, url } = await processMesh({ endpoint: '/api/forge-remesh', what: 'Remesh', body, signal, progress, pick: (d) => d.result_url });+ const mesh = meshFrom(inputs.mesh, url, { faceCount: done.face_count ?? null });+ return { outputs: { mesh }, result: { mesh, stats: done.face_count ? `${done.face_count.toLocaleString('en-US')} faces` : '' } };+ },++ async segment({ params, inputs, signal, progress }) {+ const meshUrl = await publicMeshUrl(inputs.mesh, { signal, progress });+ const body = { mesh_url: meshUrl, method: params.method, max_parts: Number(params.maxParts) };+ const { done, url } = await processMesh({ endpoint: '/api/forge-segment', what: 'Segment', body, signal, progress, pick: (d) => d.result_url });+ const mesh = meshFrom(inputs.mesh, url, { parts: done.parts || null });+ const count = done.part_count ?? done.parts?.length;+ return { outputs: { mesh }, result: { mesh, stats: count ? `${count} parts` : '' } };+ },++ async stylize({ params, inputs, signal, progress }) {+ const meshUrl = await publicMeshUrl(inputs.mesh, { signal, progress });+ const { done, url } = await processMesh({ endpoint: '/api/forge-stylize', what: 'Stylize', body: { mesh_url: meshUrl, style: params.style, output_format: 'glb' }, signal, progress, pick: (d) => d.result_url });+ const mesh = meshFrom(inputs.mesh, url, { faceCount: done.face_count ?? null });+ return { outputs: { mesh }, result: { mesh, stats: done.face_count ? `${done.face_count.toLocaleString('en-US')} faces` : '' } };+ },++ async gameready({ params, inputs, signal, progress }) {+ const meshUrl = await publicMeshUrl(inputs.mesh, { signal, progress });+ const body = { mesh_url: meshUrl, topology: params.topology, poly_budget: Number(params.polyBudget), texture_size: Number(params.textureSize), formats: ['glb', 'fbx'] };+ const { done, url } = await processMesh({+ endpoint: '/api/forge-gameready',+ what: 'Game-ready',+ body,+ signal,+ progress,+ feature: 'forge.gameready',+ pick: (d) => d.outputs?.glb?.url,+ });+ const mesh = meshFrom(inputs.mesh, url, { fbxUrl: done.outputs?.fbx?.url || null, faceCount: done.face_count ?? null });+ const links = mesh.fbxUrl ? [{ label: 'Download FBX', href: mesh.fbxUrl, download: true }] : [];+ return { outputs: { mesh }, result: { mesh, links, stats: done.face_count ? `${done.face_count.toLocaleString('en-US')} faces` : '' } };+ },++ async preview({ inputs }) {+ if (!inputs.mesh) throw new StepError('No model arrived to preview.', { code: 'no_input' });+ return { result: { mesh: inputs.mesh } };+ },++ async export({ params, inputs, iter, signal, progress }) {+ const mesh = inputs.mesh;+ if (!mesh) throw new StepError('No model arrived to export.', { code: 'no_input' });+ const base = String(params.filename || 'forge-model').trim() + (iter != null ? `-${iter + 1}` : '');+ const format = params.format || 'glb';+ const filename = `${base}.${format}`;+ let href;+ let objectUrl = null;+ if (format === 'glb') {+ if (mesh.blob) href = objectUrl = URL.createObjectURL(mesh.blob);+ else {+ progress({ label: 'Downloading the GLB', pct: null });+ href = objectUrl = URL.createObjectURL(new Blob([await meshArrayBuffer(mesh, signal)], { type: 'model/gltf-binary' }));+ }+ } else if (format === 'fbx') {+ if (mesh.fbxUrl) href = mesh.fbxUrl;+ else {+ const meshUrl = await publicMeshUrl(mesh, { signal, progress });+ const { url } = await processMesh({+ endpoint: '/api/forge-remesh',+ what: 'FBX conversion',+ body: { mesh_url: meshUrl, operation: 'convert', remesh_mode: 'triangle', output_format: 'fbx' },+ signal,+ progress,+ pick: (d) => d.result_url,+ });+ href = url;+ }+ } else {+ progress({ label: `Converting to ${format.toUpperCase()}`, pct: null });+ href = objectUrl = URL.createObjectURL(await convertInBrowser(mesh, format, signal));+ }+ if (params.autoDownload !== false) triggerDownload(href, filename);+ return { result: { download: { href, filename, objectUrl } } };+ },++ async save({ params, inputs, signal, progress }) {+ const mesh = inputs.mesh;+ const glbUrl = await publicMeshUrl(mesh, { signal, progress });+ const name = String(params.name || 'Forge workflow model').trim().slice(0, 80);+ progress({ label: params.destination === 'gallery' ? 'Publishing to the gallery' : 'Saving to your library', pct: null });+ if (params.destination === 'gallery') {+ const { res, data } = await request('/api/creations', {+ method: 'POST',+ body: { op: 'publish', prompt: (mesh.prompt || name).slice(0, 1000), glbUrl, title: name, previewImageUrl: mesh.previewImageUrl || undefined, backend: mesh.backend || undefined },+ signal,+ });+ if (res.status === 400 && data.error === 'invalid_glb_url') {+ throw new StepError('The gallery only accepts models stored on three.ws. Add a Remesh or Save to library step instead.', { code: 'invalid_glb_url' });+ }+ if (!res.ok) throw errorFromResponse(res, data, 'Publishing');+ return { result: { saved: true, links: [{ label: 'View in gallery', href: '/creations' }] } };+ }+ const { res, data } = await request('/api/avatars/from-forge', {+ method: 'POST',+ credentials: 'include',+ body: { glb_url: glbUrl, name, visibility: params.visibility || 'unlisted', source_prompt: mesh.prompt || undefined, rigged: Boolean(mesh.rigged), tags: ['forge-workflow'] },+ signal,+ });+ if (res.status === 401) throw new StepError('Sign in to save models to your library, then retry this step.', { code: 'auth', action: SIGN_IN() });+ if (!res.ok) throw errorFromResponse(res, data, 'Saving');+ const href = data.view_url || (data.avatar?.id ? `/avatars/${data.avatar.id}` : '/dashboard');+ return { result: { saved: true, links: [{ label: 'Open in library', href }] } };+ },+};diff --git a/src/forge-workflows/graph.js b/src/forge-workflows/graph.jsnew file mode 100644index 000000000..83e2b3acc--- /dev/null+++ b/src/forge-workflows/graph.js@@ -0,0 +1,558 @@+// Forge Workflows: the pure graph core.+//+// Adapted from Modly (https://github.com/lightningpixel/modly), MIT License,+// Copyright (c) 2026 Lightning Pixel. The preflight checks mirror Modly's+// src/areas/workflows/preflight.ts (typed ports, required inputs, one issue per+// key) and the For Each body rule mirrors workflowRunStore.ts (a loop's body is+// every executable node reachable downstream of the iterator, replayed once per+// item). Rewritten for a browser graph of three.ws endpoints.+//+// Nothing in this module touches the DOM or the network, so every rule the+// editor and the runner rely on is unit-tested in tests/forge-workflows-graph.test.js.+//+// A workflow is plain JSON:+// { kind, version, name, nodes: [{ id, type, x, y, params }],+// edges: [{ id, from: { node, port }, to: { node, port } }] }+// Port data types are 'image', 'text' and 'mesh'. Node definitions live in+// node-types.js; every function here takes the registry as an argument so the+// core stays independent of which endpoints back the nodes.++export const WORKFLOW_KIND = 'three.ws/forge-workflow';+export const WORKFLOW_VERSION = 1;+export const PORT_TYPES = ['image', 'text', 'mesh'];++const MAX_NODES = 200;+const MAX_EDGES = 600;++/** Resolve a node's input ports (a definition may derive them from params). */+export function inputPorts(def, params = {}) {+ if (!def) return [];+ return typeof def.inputs === 'function' ? def.inputs(params) : def.inputs || [];+}++/** Resolve a node's output ports. */+export function outputPorts(def, params = {}) {+ if (!def) return [];+ return typeof def.outputs === 'function' ? def.outputs(params) : def.outputs || [];+}++export function findPort(types, node, portId, direction) {+ const def = types[node?.type];+ const ports = direction === 'in' ? inputPorts(def, node?.params) : outputPorts(def, node?.params);+ return ports.find((p) => p.id === portId) || null;+}++/** Default params for a node type, from each param's `default`. */+export function defaultParams(def) {+ const out = {};+ for (const p of def?.params || []) {+ if (p.default !== undefined) out[p.id] = structuredCloneSafe(p.default);+ }+ return out;+}++function structuredCloneSafe(v) {+ if (v === null || typeof v !== 'object') return v;+ return JSON.parse(JSON.stringify(v));+}++let idCounter = 0;+/** Short unique id, stable enough for a graph and readable in exported JSON. */+export function makeId(prefix = 'n') {+ idCounter = (idCounter + 1) % 1e6;+ const rand = Math.random().toString(36).slice(2, 7);+ return `${prefix}_${Date.now().toString(36).slice(-4)}${rand}${idCounter.toString(36)}`;+}++export function createNode(types, type, position = {}, params = {}) {+ const def = types[type];+ if (!def) throw new Error(`Unknown node type "${type}"`);+ return {+ id: makeId('n'),+ type,+ x: Math.round(position.x ?? 0),+ y: Math.round(position.y ?? 0),+ params: { ...defaultParams(def), ...params },+ };+}++export function emptyWorkflow(name = 'Untitled workflow') {+ return { kind: WORKFLOW_KIND, version: WORKFLOW_VERSION, name, nodes: [], edges: [] };+}++// ── Adjacency ─────────────────────────────────────────────────────────────────++function liveEdges(workflow) {+ const ids = new Set(workflow.nodes.map((n) => n.id));+ return workflow.edges.filter((e) => ids.has(e.from.node) && ids.has(e.to.node));+}++export function incomingEdges(workflow, nodeId) {+ return workflow.edges.filter((e) => e.to.node === nodeId);+}++export function outgoingEdges(workflow, nodeId) {+ return workflow.edges.filter((e) => e.from.node === nodeId);+}++/** Every node id reachable downstream of `startId` (excluding it). */+export function downstreamOf(workflow, startId) {+ const out = new Set();+ const stack = [startId];+ while (stack.length) {+ const id = stack.pop();+ for (const e of workflow.edges) {+ if (e.from.node !== id || out.has(e.to.node)) continue;+ out.add(e.to.node);+ stack.push(e.to.node);+ }+ }+ return out;+}++/** Every node id reachable upstream of `startId` (excluding it). */+export function upstreamOf(workflow, startId) {+ const out = new Set();+ const stack = [startId];+ while (stack.length) {+ const id = stack.pop();+ for (const e of workflow.edges) {+ if (e.to.node !== id || out.has(e.from.node)) continue;+ out.add(e.from.node);+ stack.push(e.from.node);+ }+ }+ return out;+}++/** True when adding from -> to would close a directed cycle. */+export function wouldCreateCycle(workflow, fromNodeId, toNodeId) {+ if (fromNodeId === toNodeId) return true;+ return downstreamOf(workflow, toNodeId).has(fromNodeId);+}++// ── Topological order ─────────────────────────────────────────────────────────++/**+ * Kahn's algorithm with a stable tie-break (canvas position: left to right, then+ * top to bottom, then insertion order) so the run order matches what the user+ * reads on the canvas. Returns { order, cycle } where `cycle` lists the node ids+ * that could not be ordered (empty when the graph is a DAG).+ */+export function topoSort(workflow) {+ const nodes = workflow.nodes;+ const index = new Map(nodes.map((n, i) => [n.id, i]));+ const inDeg = new Map(nodes.map((n) => [n.id, 0]));+ const adj = new Map(nodes.map((n) => [n.id, []]));+ for (const e of liveEdges(workflow)) {+ adj.get(e.from.node).push(e.to.node);+ inDeg.set(e.to.node, inDeg.get(e.to.node) + 1);+ }+ const byCanvas = (a, b) => {+ const na = nodes[index.get(a)];+ const nb = nodes[index.get(b)];+ return (na.x - nb.x) || (na.y - nb.y) || (index.get(a) - index.get(b));+ };+ const ready = nodes.filter((n) => inDeg.get(n.id) === 0).map((n) => n.id).sort(byCanvas);+ const order = [];+ while (ready.length) {+ const id = ready.shift();+ order.push(id);+ for (const next of adj.get(id)) {+ inDeg.set(next, inDeg.get(next) - 1);+ if (inDeg.get(next) === 0) {+ ready.push(next);+ ready.sort(byCanvas);+ }+ }+ }+ const placed = new Set(order);+ const cycle = nodes.filter((n) => !placed.has(n.id)).map((n) => n.id);+ return { order, cycle };+}++// ── Loops (For Each) ─────────────────────────────────────────────────────────++/** Node ids whose definition marks them as an iterator. */+export function iteratorIds(workflow, types) {+ return workflow.nodes.filter((n) => types[n.type]?.iterator).map((n) => n.id);+}++/**+ * The body of each iterator: every node reachable downstream of it. Mirrors+ * Modly's reachableExecutable(): the body re-runs once per item, and nothing+ * needs a back-edge to express the loop.+ */+export function loopBodies(workflow, types) {+ const bodies = new Map();+ for (const id of iteratorIds(workflow, types)) bodies.set(id, downstreamOf(workflow, id));+ return bodies;+}++/** The items an iterator node will emit, read from its params by its definition. */+export function iteratorItems(types, node) {+ const def = types[node.type];+ if (!def?.iterator) return [];+ return def.items ? def.items(node.params || {}) : [];+}++/**+ * The run plan: an ordered list of steps { nodeId, iter } where `iter` is the+ * item index for loop-body steps and null otherwise.+ *+ * Each loop is emitted as one block (the iterator, then its body in topological+ * order, once per item) at the position of its LAST body node in the global+ * order. Every external input of a body node sorts before that body node, and+ * therefore before the block, so a body never runs ahead of a non-loop input+ * such as a shared text prompt.+ */+export function buildPlan(workflow, types, { order: givenOrder } = {}) {+ const order = givenOrder || topoSort(workflow).order;+ const bodies = loopBodies(workflow, types);+ const position = new Map(order.map((id, i) => [id, i]));+ const owner = new Map();+ for (const [iterId, body] of bodies) for (const id of body) if (!owner.has(id)) owner.set(id, iterId);++ const anchor = new Map();+ for (const [iterId, body] of bodies) {+ let last = iterId;+ for (const id of body) if (position.get(id) > position.get(last)) last = id;+ anchor.set(last, iterId);+ }++ const nodeById = new Map(workflow.nodes.map((n) => [n.id, n]));+ const steps = [];+ for (const id of order) {+ const isIterator = bodies.has(id);+ if (!owner.has(id) && !isIterator) steps.push({ nodeId: id, iter: null });+ const iterId = anchor.get(id);+ if (iterId === undefined) continue;+ const body = bodies.get(iterId);+ const bodyOrder = order.filter((x) => body.has(x));+ const count = iteratorItems(types, nodeById.get(iterId)).length;+ for (let i = 0; i < count; i++) {+ steps.push({ nodeId: iterId, iter: i });+ for (const b of bodyOrder) steps.push({ nodeId: b, iter: i });+ }+ }+ return { steps, bodies, owner };+}++// ── Connection rules ─────────────────────────────────────────────────────────++/**+ * Can an edge go from (fromNode, fromPort) to (toNode, toPort)? Returns+ * { ok: true } or { ok: false, reason } with a sentence the editor shows as-is.+ */+export function canConnect(workflow, types, from, to) {+ const fromNode = workflow.nodes.find((n) => n.id === from.node);+ const toNode = workflow.nodes.find((n) => n.id === to.node);+ if (!fromNode || !toNode) return { ok: false, reason: 'That node no longer exists.' };+ if (fromNode.id === toNode.id) return { ok: false, reason: 'A node cannot feed itself.' };+ const out = findPort(types, fromNode, from.port, 'out');+ const inp = findPort(types, toNode, to.port, 'in');+ if (!out || !inp) return { ok: false, reason: 'Connect an output dot to an input dot.' };+ if (out.type !== inp.type) {+ return {+ ok: false,+ reason: `${types[toNode.type].label} ${inp.label || inp.id} takes ${article(inp.type)}, not ${article(out.type)}.`,+ };+ }+ if (wouldCreateCycle(workflow, fromNode.id, toNode.id)) {+ return { ok: false, reason: 'That link would loop back on itself. Use a For Each node to repeat steps.' };+ }+ return { ok: true };+}++function article(type) {+ return type === 'image' ? 'an image' : type === 'mesh' ? 'a 3D model' : 'text';+}++/**+ * Add an edge, replacing whatever already feeds the target input (every input+ * port takes exactly one link). Returns a new workflow; the input is untouched.+ */+export function connect(workflow, types, from, to) {+ const check = canConnect(workflow, types, from, to);+ if (!check.ok) return { workflow, error: check.reason };+ const edges = workflow.edges.filter((e) => !(e.to.node === to.node && e.to.port === to.port));+ edges.push({ id: makeId('e'), from: { ...from }, to: { ...to } });+ return { workflow: { ...workflow, edges }, error: null };+}++export function removeNodes(workflow, ids) {+ const drop = new Set(ids);+ return {+ ...workflow,+ nodes: workflow.nodes.filter((n) => !drop.has(n.id)),+ edges: workflow.edges.filter((e) => !drop.has(e.from.node) && !drop.has(e.to.node)),+ };+}++/** Drop edges whose ports no longer exist (a param change can retype a port). */+export function pruneInvalidEdges(workflow, types) {+ const nodeById = new Map(workflow.nodes.map((n) => [n.id, n]));+ const edges = workflow.edges.filter((e) => {+ const a = nodeById.get(e.from.node);+ const b = nodeById.get(e.to.node);+ if (!a || !b) return false;+ const out = findPort(types, a, e.from.port, 'out');+ const inp = findPort(types, b, e.to.port, 'in');+ return !!out && !!inp && out.type === inp.type;+ });+ return edges.length === workflow.edges.length ? workflow : { ...workflow, edges };+}++// ── Preflight ─────────────────────────────────────────────────────────────────++/**+ * Validate a workflow before a run. Returns a list of issues+ * { key, nodeId?, message, level } where level is 'error' (blocks the run) or+ * 'warning' (runs anyway). Keys are unique so one problem is reported once.+ *+ * `ctx` is forwarded to each definition's validate(node, ctx) hook, which is+ * where node-specific checks live (an empty prompt, no uploaded image, an engine+ * the live catalog marks as down).+ */+export function preflight(workflow, types, ctx = {}) {+ const issues = [];+ const push = (issue) => {+ if (!issues.some((x) => x.key === issue.key)) issues.push({ level: 'error', ...issue });+ };+ if (!workflow.nodes.length) {+ push({ key: 'empty', message: 'The canvas is empty. Add a node from the palette or start from a template.' });+ return issues;+ }+ const nodeById = new Map(workflow.nodes.map((n) => [n.id, n]));+ const label = (n) => n?.params?.title?.trim() || types[n?.type]?.label || 'Node';++ for (const n of workflow.nodes) {+ if (!types[n.type]) push({ key: `${n.id}:unknown`, nodeId: n.id, message: `Unknown node type "${n.type}". Remove it.` });+ }++ const { cycle } = topoSort(workflow);+ if (cycle.length) {+ push({+ key: 'cycle',+ nodeId: cycle[0],+ message: 'These steps form a loop. Remove one of the links; use a For Each node to repeat steps.',+ });+ }++ for (const e of workflow.edges) {+ const a = nodeById.get(e.from.node);+ const b = nodeById.get(e.to.node);+ if (!a || !b) {+ push({ key: `${e.id}:dangling`, nodeId: a?.id || b?.id, message: 'A link points at a node that no longer exists.' });+ continue;+ }+ if (!types[a.type] || !types[b.type]) continue;+ const out = findPort(types, a, e.from.port, 'out');+ const inp = findPort(types, b, e.to.port, 'in');+ if (!out || !inp) {+ push({ key: `${e.id}:port`, nodeId: b.id, message: `${label(b)} has a link to an input it no longer has.` });+ } else if (out.type !== inp.type) {+ push({+ key: `${e.id}:type`,+ nodeId: b.id,+ message: `${label(b)} expects ${article(inp.type)} on ${inp.label || inp.id}, but ${label(a)} outputs ${article(out.type)}.`,+ });+ }+ }++ for (const n of workflow.nodes) {+ const def = types[n.type];+ if (!def) continue;+ const params = n.params || {};+ const incoming = incomingEdges(workflow, n.id);+ const required = typeof def.required === 'function' ? def.required(params) : inputPorts(def, params).filter((p) => !p.optional).map((p) => p.id);+ for (const portId of required) {+ if (incoming.some((e) => e.to.port === portId)) continue;+ const port = findPort(types, n, portId, 'in');+ push({+ key: `${n.id}:missing:${portId}`,+ nodeId: n.id,+ message: `${label(n)} needs ${article(port?.type || 'text')} connected to ${port?.label || portId}.`,+ });+ }+ for (const message of def.validate ? def.validate(n, ctx) || [] : []) {+ const text = typeof message === 'string' ? message : message.message;+ const level = typeof message === 'string' ? 'error' : message.level || 'error';+ push({ key: `${n.id}:v:${text}`, nodeId: n.id, message: `${label(n)}: ${text}`, level });+ }+ }++ const bodies = loopBodies(workflow, types);+ const seenIn = new Map();+ for (const [iterId, body] of bodies) {+ if (!body.size) {+ push({+ key: `${iterId}:empty-body`,+ nodeId: iterId,+ level: 'warning',+ message: `${label(nodeById.get(iterId))} has nothing connected after it, so it will not do anything.`,+ });+ }+ for (const id of body) {+ if (bodies.has(id)) {+ push({+ key: `${id}:nested-loop`,+ nodeId: id,+ message: `${label(nodeById.get(id))} sits inside another For Each. Nested loops are not supported; use one For Each per chain.`,+ });+ }+ if (seenIn.has(id) && seenIn.get(id) !== iterId) {+ push({+ key: `${id}:two-loops`,+ nodeId: id,+ message: `${label(nodeById.get(id))} is fed by two For Each nodes. Give each loop its own chain.`,+ });+ }+ seenIn.set(id, iterId);+ }+ }++ return issues;+}++export function blockingIssues(issues) {+ return issues.filter((i) => i.level !== 'warning');+}++// ── Serialization ─────────────────────────────────────────────────────────────++/** A workflow as portable JSON text, with runtime-only params stripped. */+export function serializeWorkflow(workflow, types) {+ const nodes = workflow.nodes.map((n) => {+ const def = types[n.type];+ const params = { ...(n.params || {}) };+ for (const p of def?.params || []) if (p.transient) delete params[p.id];+ return { id: n.id, type: n.type, x: Math.round(n.x), y: Math.round(n.y), params };+ });+ const out = {+ kind: WORKFLOW_KIND,+ version: WORKFLOW_VERSION,+ name: String(workflow.name || 'Untitled workflow').slice(0, 120),+ nodes,+ edges: workflow.edges.map((e) => ({ id: e.id, from: { ...e.from }, to: { ...e.to } })),+ };+ return JSON.stringify(out, null, 2);+}++/**+ * Parse workflow JSON from an import or from storage. Throws an Error whose+ * message is safe to show the user when the input is not a usable workflow.+ * Unknown node types are rejected rather than silently dropped, so a file made+ * by a newer version says so instead of loading half a graph.+ */+export function parseWorkflow(input, types) {+ let data = input;+ if (typeof input === 'string') {+ try {+ data = JSON.parse(input);+ } catch {+ throw new Error('That file is not valid JSON.');+ }+ }+ if (!data || typeof data !== 'object') throw new Error('That file does not contain a workflow.');+ if (data.kind !== WORKFLOW_KIND) throw new Error('That file is not a three.ws Forge workflow.');+ if (typeof data.version !== 'number' || data.version > WORKFLOW_VERSION) {+ throw new Error('That workflow was saved by a newer version of the builder. Reload the page and try again.');+ }+ if (!Array.isArray(data.nodes) || !Array.isArray(data.edges)) throw new Error('The workflow is missing its nodes or links.');+ if (data.nodes.length > MAX_NODES) throw new Error(`Workflows are limited to ${MAX_NODES} nodes.`);+ if (data.edges.length > MAX_EDGES) throw new Error(`Workflows are limited to ${MAX_EDGES} links.`);++ const ids = new Set();+ const nodes = data.nodes.map((raw, i) => {+ if (!raw || typeof raw.id !== 'string' || !raw.id || ids.has(raw.id)) throw new Error(`Node ${i + 1} has a missing or duplicate id.`);+ const def = types[raw.type];+ if (!def) throw new Error(`Node ${i + 1} uses an unknown type "${String(raw.type).slice(0, 40)}".`);+ ids.add(raw.id);+ const params = raw.params && typeof raw.params === 'object' && !Array.isArray(raw.params) ? raw.params : {};+ return {+ id: raw.id,+ type: raw.type,+ x: Number.isFinite(raw.x) ? raw.x : 0,+ y: Number.isFinite(raw.y) ? raw.y : 0,+ params: { ...defaultParams(def), ...structuredCloneSafe(params) },+ };+ });+ const edgeIds = new Set();+ const edges = [];+ for (const raw of data.edges) {+ if (!raw?.from || !raw?.to) continue;+ if (!ids.has(raw.from.node) || !ids.has(raw.to.node)) continue;+ const id = typeof raw.id === 'string' && raw.id && !edgeIds.has(raw.id) ? raw.id : makeId('e');+ edgeIds.add(id);+ edges.push({+ id,+ from: { node: raw.from.node, port: String(raw.from.port) },+ to: { node: raw.to.node, port: String(raw.to.port) },+ });+ }+ return {+ kind: WORKFLOW_KIND,+ version: WORKFLOW_VERSION,+ name: typeof data.name === 'string' && data.name.trim() ? data.name.trim().slice(0, 120) : 'Imported workflow',+ nodes,+ edges,+ };+}++/** Deep copy with fresh ids (used when a template is instantiated). */+export function cloneWithFreshIds(workflow) {+ const map = new Map();+ const nodes = workflow.nodes.map((n) => {+ const id = makeId('n');+ map.set(n.id, id);+ return { ...n, id, params: structuredCloneSafe(n.params || {}) };+ });+ const edges = workflow.edges.map((e) => ({+ id: makeId('e'),+ from: { node: map.get(e.from.node), port: e.from.port },+ to: { node: map.get(e.to.node), port: e.to.port },+ }));+ return { ...workflow, nodes, edges };+}++/**+ * The signature of a node's work for a given item: its type, its params, the+ * item it is processing, and the signatures of everything feeding it. The+ * runner reuses a cached output only when this matches, so editing a node+ * invalidates it and everything downstream, and nothing else.+ */+export function stepSignature(workflow, types, nodeId, iter, plan, memo = new Map()) {+ const key = `${nodeId}#${iter ?? ''}`;+ if (memo.has(key)) return memo.get(key);+ const node = workflow.nodes.find((n) => n.id === nodeId);+ const def = types[node?.type];+ const params = { ...(node?.params || {}) };+ for (const p of def?.params || []) if (p.signatureExclude) delete params[p.id];+ const parts = [node?.type, stableStringify(params)];+ if (def?.iterator && iter != null) parts.push(stableStringify(iteratorItems(types, node)[iter] ?? null));+ const sameLoop = (src) => iter != null && (plan.owner.get(src) === plan.owner.get(nodeId) || src === plan.owner.get(nodeId));+ for (const e of incomingEdges(workflow, nodeId).sort((a, b) => (a.to.port < b.to.port ? -1 : 1))) {+ const srcIter = sameLoop(e.from.node) ? iter : null;+ parts.push(`${e.to.port}<${e.from.port}:${stepSignature(workflow, types, e.from.node, srcIter, plan, memo)}`);+ }+ const sig = hash(parts.join('|'));+ memo.set(key, sig);+ return sig;+}++export function stableStringify(v) {+ if (v === null || typeof v !== 'object') return JSON.stringify(v);+ if (Array.isArray(v)) return `[${v.map(stableStringify).join(',')}]`;+ return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(v[k])}`).join(',')}}`;+}++/** FNV-1a 32-bit: a compact, deterministic fingerprint (not a security hash). */+function hash(str) {+ let h = 0x811c9dc5;+ for (let i = 0; i < str.length; i++) {+ h ^= str.charCodeAt(i);+ h = Math.imul(h, 0x01000193);+ }+ return (h >>> 0).toString(36);+}diff --git a/src/forge-workflows/inspector.js b/src/forge-workflows/inspector.jsnew file mode 100644index 000000000..c6345b1d0--- /dev/null+++ b/src/forge-workflows/inspector.js@@ -0,0 +1,578 @@+// Forge Workflows: the inspector panel and the shared param form.+//+// The form renderer is used by both the inspector (desktop) and the phone+// layout, so a prompt or photo is edited the same way everywhere.++import { findPort, inputPorts, outputPorts, incomingEdges } from './graph.js';+import { paramOptions, visibleParams } from './node-types.js';+import { uploadImage, uploadGlb } from './executors.js';+import { h, icon, ICONS, toast, MOD, formatSeconds } from './ui.js';+import { summarizeNode } from './runner.js';++let fieldSeq = 0;+const fid = (p) => `fw-f-${p}-${++fieldSeq}`;++/**+ * Render the editable params of one node.+ *+ * @param {object} node+ * @param {object} def+ * @param {object} ctx live catalog / Modly / sign-in context+ * @param {(paramId:string, value:any, opts:{rerender:boolean, coalesce:boolean}) => void} onChange+ * @param {object} [opts]+ * @param {string[]} [opts.only] restrict to these param ids+ * @param {boolean} [opts.disabled]+ */+export function paramForm(node, def, ctx, onChange, { only, disabled = false } = {}) {+ const params = node.params || {};+ const fields = visibleParams(def, params).filter((p) => !only || only.includes(p.id));+ return h(+ 'div',+ { class: 'fw-form' },+ fields.map((p) => field(node, p, params, ctx, onChange, disabled)),+ );+}++function field(node, p, params, ctx, onChange, disabled) {+ const id = fid(p.id);+ const value = params[p.id];+ const hint = p.hint ? h('div', { class: 'fw-hint', id: `${id}-hint` }, p.hint) : null;+ const described = p.hint ? `${id}-hint` : null;+ let control;++ if (p.kind === 'select') {+ const options = paramOptions(p, ctx, params);+ const known = options.some((o) => String(o.value) === String(value));+ control = h(+ 'select',+ {+ id,+ class: 'fw-input',+ disabled,+ 'aria-describedby': described,+ dataset: { param: p.id },+ on: {+ change: (e) => {+ const opt = options.find((o) => String(o.value) === e.target.value);+ onChange(p.id, opt ? opt.value : e.target.value, { rerender: true });+ },+ },+ },+ !known && value !== '' && value != null ? h('option', { value: String(value) }, `${value} (unavailable)`) : null,+ !known && (value === '' || value == null) ? h('option', { value: '' }, options.length ? 'Choose one' : 'Nothing to choose yet') : null,+ options.map((o) => h('option', { value: String(o.value), selected: String(o.value) === String(value) }, o.label)),+ );+ control.value = String(value ?? '');+ } else if (p.kind === 'textarea') {+ control = h('textarea', {+ id,+ class: 'fw-input',+ rows: p.id === 'prompts' ? 6 : 4,+ maxlength: p.maxLength || null,+ disabled,+ 'aria-describedby': described,+ dataset: { param: p.id },+ value: value ?? '',+ on: { input: (e) => onChange(p.id, e.target.value, { coalesce: true }) },+ });+ } else if (p.kind === 'number') {+ control = h('input', {+ id,+ type: 'number',+ class: 'fw-input',+ min: p.min,+ max: p.max,+ step: p.step || 1,+ inputmode: 'numeric',+ disabled,+ 'aria-describedby': described,+ dataset: { param: p.id },+ value: value ?? '',+ on: {+ change: (e) => {+ let n = Number(e.target.value);+ if (!Number.isFinite(n)) n = p.default;+ n = Math.min(p.max ?? n, Math.max(p.min ?? n, Math.round(n)));+ e.target.value = String(n);+ onChange(p.id, n, {});+ },+ },+ });+ } else if (p.kind === 'checkbox') {+ return h(+ 'label',+ { class: 'fw-check' },+ h('input', { type: 'checkbox', checked: value !== false, disabled, dataset: { param: p.id }, on: { change: (e) => onChange(p.id, e.target.checked, {}) } }),+ h('span', {}, p.label),+ );+ } else if (p.kind === 'images') {+ control = imagesField(id, p, value, onChange, disabled);+ } else if (p.kind === 'mesh-url') {+ control = meshField(id, p, params, onChange, disabled);+ } else {+ control = h('input', {+ id,+ type: 'text',+ class: 'fw-input',+ maxlength: p.maxLength || null,+ disabled,+ 'aria-describedby': described,+ dataset: { param: p.id },+ value: value ?? '',+ on: { input: (e) => onChange(p.id, e.target.value, { coalesce: true }) },+ });+ }+ return h('div', { class: 'fw-field' }, h('label', { class: 'fw-label', for: id }, p.label), control, hint);+}++function imagesField(id, p, value, onChange, disabled) {+ const list = Array.isArray(value) ? value : [];+ const max = p.max || 1;+ const wrap = h('div', { class: 'fw-images' });+ const pending = h('div', { class: 'fw-images-pending', 'aria-live': 'polite' });++ const thumbs = h(+ 'div',+ { class: 'fw-images-grid' },+ list.map((img, i) =>+ h(+ 'figure',+ { class: 'fw-image' },+ h('img', { src: img.url, alt: img.name || `Photo ${i + 1}`, loading: 'lazy' }),+ h(+ 'button',+ {+ type: 'button',+ class: 'fw-image-remove',+ disabled,+ 'aria-label': `Remove ${img.name || `photo ${i + 1}`}`,+ on: { click: () => onChange(p.id, list.filter((_, j) => j !== i), { rerender: true }) },+ },+ icon(ICONS.x, 12),+ ),+ ),+ ),+ );++ async function take(files) {+ const room = max - list.length;+ const picked = [...files].filter((f) => f.type.startsWith('image/'));+ if (!picked.length) {+ toast('Drop a PNG, JPEG or WebP photo.', { tone: 'error' });+ return;+ }+ const batch = max === 1 ? picked.slice(0, 1) : picked.slice(0, Math.max(0, room));+ if (!batch.length) {+ toast(`This node holds up to ${max} photos. Remove one first.`, { tone: 'error' });+ return;+ }+ pending.textContent = `Uploading ${batch.length} photo${batch.length === 1 ? '' : 's'}…`;+ wrap.classList.add('is-uploading');+ const done = [];+ for (const f of batch) {+ try {+ done.push(await uploadImage(f));+ } catch (err) {+ toast(err?.message || 'The photo upload failed. Try again.', { tone: 'error', timeout: 6000 });+ }+ }+ wrap.classList.remove('is-uploading');+ pending.textContent = '';+ if (done.length) onChange(p.id, max === 1 ? done.slice(0, 1) : [...list, ...done].slice(0, max), { rerender: true });+ }++ const input = h('input', {+ id,+ type: 'file',+ accept: 'image/png,image/jpeg,image/webp',+ multiple: max > 1,+ class: 'fw-sr-only',+ disabled,+ on: {+ change: (e) => {+ take(e.target.files);+ e.target.value = '';+ },+ },+ });+ const drop = h(+ 'label',+ { class: 'fw-drop', for: id },+ icon(ICONS.upload, 16),+ h('span', {}, list.length && max === 1 ? 'Replace photo' : max > 1 ? `Add photos (${list.length}/${max})` : 'Choose a photo'),+ h('span', { class: 'fw-drop-sub' }, 'or drop it here'),+ );+ drop.addEventListener('dragover', (e) => {+ e.preventDefault();+ drop.classList.add('is-over');+ });+ drop.addEventListener('dragleave', () => drop.classList.remove('is-over'));+ drop.addEventListener('drop', (e) => {+ e.preventDefault();+ drop.classList.remove('is-over');+ if (!disabled && e.dataTransfer?.files?.length) take(e.dataTransfer.files);+ });+ wrap.append(thumbs, input, drop, pending);+ return wrap;+}++function meshField(id, p, params, onChange, disabled) {+ const url = h('input', {+ id,+ type: 'url',+ class: 'fw-input',+ placeholder: 'https://…/model.glb',+ disabled,+ dataset: { param: p.id },+ value: params[p.id] || '',+ on: { change: (e) => onChange(p.id, e.target.value.trim(), { rerender: false }) },+ });+ const status = h('div', { class: 'fw-hint', 'aria-live': 'polite' });+ const file = h('input', {+ type: 'file',+ accept: '.glb,model/gltf-binary',+ class: 'fw-sr-only',+ id: `${id}-file`,+ disabled,+ on: {+ change: async (e) => {+ const f = e.target.files?.[0];+ e.target.value = '';+ if (!f) return;+ status.textContent = `Uploading ${f.name}…`;+ try {+ const publicUrl = await uploadGlb(f);+ status.textContent = '';+ onChange('name', f.name.replace(/\.glb$/i, ''), {});+ onChange(p.id, publicUrl, { rerender: true });+ } catch (err) {+ status.textContent = err?.message || 'The upload failed. Try again.';+ }+ },+ },+ });+ return h(+ 'div',+ { class: 'fw-mesh-field' },+ url,+ h('label', { class: 'fw-btn is-sm is-ghost', for: `${id}-file` }, icon(ICONS.upload, 13), 'Upload a GLB'),+ file,+ status,+ );+}++/**+ * The inspector panel.+ */+export function createInspector(root, app) {+ const { types } = app;++ function nodeLabel(n) {+ return types[n.type]?.label || n.type;+ }++ function onParam(nodeId) {+ return (paramId, value, { rerender = false, coalesce = false } = {}) => {+ app.updateParam(nodeId, paramId, value, { coalesce });+ if (rerender) {+ const active = document.activeElement?.dataset?.param;+ render();+ if (active) root.querySelector(`[data-param="${CSS.escape(active)}"]`)?.focus();+ }+ };+ }++ function connectionsSection(node) {+ const wf = app.getWorkflow();+ const ins = inputPorts(types[node.type], node.params);+ if (!ins.length) return null;+ return h(+ 'section',+ { class: 'fw-section' },+ h('h3', { class: 'fw-section-title' }, 'Inputs'),+ ins.map((port) => {+ const id = fid(`in-${port.id}`);+ const current = incomingEdges(wf, node.id).find((e) => e.to.port === port.id);+ const choices = [];+ for (const other of wf.nodes) {+ if (other.id === node.id) continue;+ for (const out of outputPorts(types[other.type], other.params)) {+ if (out.type !== port.type) continue;+ const ok = app.canLink({ node: other.id, port: out.id }, { node: node.id, port: port.id });+ if (!ok && !(current && current.from.node === other.id && current.from.port === out.id)) continue;+ choices.push({ value: `${other.id}::${out.id}`, label: `${nodeLabel(other)} · ${out.label || out.id}` });+ }+ }+ const sel = h(+ 'select',+ {+ id,+ class: 'fw-input',+ on: {+ change: (e) => {+ const v = e.target.value;+ if (!v) app.unlinkInput(node.id, port.id);+ else {+ const [fromNode, fromPort] = v.split('::');+ app.linkInput({ node: fromNode, port: fromPort }, { node: node.id, port: port.id });+ }+ render();+ },+ },+ },+ h('option', { value: '' }, port.optional ? 'Not connected (optional)' : 'Not connected'),+ choices.map((c) => h('option', { value: c.value }, c.label)),+ );+ sel.value = current ? `${current.from.node}::${current.from.port}` : '';+ return h('div', { class: 'fw-field' }, h('label', { class: 'fw-label', for: id }, port.label || port.id), sel);+ }),+ );+ }++ function modlySection(node) {+ if (node.type !== 'generate' || node.params.engine !== 'modly') return null;+ const m = app.modly;+ const status = h('div', { class: 'fw-modly-status', 'aria-live': 'polite' });+ const btn = h(+ 'button',+ {+ type: 'button',+ class: 'fw-btn is-sm',+ on: {+ click: async () => {+ btn.disabled = true;+ status.textContent = 'Looking for Modly on this computer…';+ const res = await app.connectModly();+ btn.disabled = false;+ if (res.status === 'connected') {+ render();+ return;+ }+ status.textContent = '';+ status.append(modlyExplain(res));+ },+ },+ },+ icon(ICONS.chip, 13),+ m ? 'Refresh models' : 'Connect Modly',+ );+ if (m) {+ const ready = m.models.filter((x) => x.downloaded).length;+ status.textContent = `Connected at ${m.origin}. ${ready} of ${m.models.length} model${m.models.length === 1 ? '' : 's'} downloaded.`;+ }+ return h(+ 'section',+ { class: 'fw-section fw-modly' },+ h('h3', { class: 'fw-section-title' }, 'Your GPU'),+ h('p', { class: 'fw-hint' }, 'Modly is a free desktop app that runs open image-to-3D models on your own graphics card. The browser may ask to let three.ws reach apps on this computer.'),+ h('div', { class: 'fw-row' }, btn, h('a', { class: 'fw-btn is-sm is-ghost', href: app.modlyInstallUrl, target: '_blank', rel: 'noopener' }, 'Get Modly')),+ status,+ );+ }++ function stepsSection(node) {+ const steps = app.stepsFor(node.id);+ if (!steps.length) return null;+ const sum = summarizeNode(steps);+ const running = app.isRunning();+ const rows = steps.map((s) =>+ h(+ 'li',+ { class: `fw-step is-${s.status}` },+ h('span', { class: 'fw-step-dot', 'aria-hidden': 'true' }),+ h('span', { class: 'fw-step-name' }, s.iter != null ? `Item ${s.iter + 1}` : 'This step'),+ h('span', { class: 'fw-step-state' }, stepWord(s)),+ s.error ? h('div', { class: 'fw-step-error' }, s.error.message) : null,+ ),+ );+ return h(+ 'section',+ { class: 'fw-section' },+ h('h3', { class: 'fw-section-title' }, sum.total > 1 ? `Last run · ${sum.done}/${sum.total} items done` : 'Last run'),+ h('ul', { class: 'fw-steps' }, rows),+ sum.failed && !running+ ? h('button', { type: 'button', class: 'fw-btn is-sm', on: { click: () => app.retryFailed() } }, icon(ICONS.retry, 13), 'Retry failed steps')+ : null,+ );+ }++ function nodeView(node) {+ const def = types[node.type];+ const running = app.isRunning();+ return [+ h(+ 'header',+ { class: 'fw-insp-head' },+ h('span', { class: `fw-cat cat-${def.category}` }, def.category),+ h('h2', { class: 'fw-insp-title' }, def.label),+ h('p', { class: 'fw-insp-blurb' }, def.blurb),+ ),+ def.params?.length ? h('section', { class: 'fw-section' }, h('h3', { class: 'fw-section-title' }, 'Settings'), paramForm(node, def, app.getContext(), onParam(node.id), { disabled: running })) : null,+ modlySection(node),+ connectionsSection(node),+ issuesFor(node.id),+ stepsSection(node),+ h(+ 'section',+ { class: 'fw-section fw-insp-actions' },+ h(+ 'button',+ { type: 'button', class: 'fw-btn is-sm', disabled: running || app.hasBlocking(), title: app.hasBlocking() ? 'Fix the problems listed first' : null, on: { click: () => app.runFrom(node.id) } },+ icon(ICONS.play, 13),+ 'Re-run from here',+ ),+ h('button', { type: 'button', class: 'fw-btn is-sm is-ghost', disabled: running, on: { click: () => app.duplicate([node.id]) } }, 'Duplicate', h('kbd', {}, `${MOD}+D`)),+ h('button', { type: 'button', class: 'fw-btn is-sm is-danger', disabled: running, on: { click: () => app.deleteSelection() } }, icon(ICONS.trash, 13), 'Delete', h('kbd', {}, 'Del')),+ ),+ ];+ }++ function issuesFor(nodeId) {+ const list = app.issues().filter((i) => i.nodeId === nodeId);+ if (!list.length) return null;+ return h(+ 'section',+ { class: 'fw-section' },+ h(+ 'ul',+ { class: 'fw-issues-inline' },+ list.map((i) => h('li', { class: `is-${i.level}` }, icon(ICONS.alert, 13), h('span', {}, i.message))),+ ),+ );+ }++ function edgeView(edgeId) {+ const wf = app.getWorkflow();+ const e = wf.edges.find((x) => x.id === edgeId);+ if (!e) return [];+ const a = wf.nodes.find((n) => n.id === e.from.node);+ const b = wf.nodes.find((n) => n.id === e.to.node);+ const out = findPort(types, a, e.from.port, 'out');+ const inp = findPort(types, b, e.to.port, 'in');+ return [+ h('header', { class: 'fw-insp-head' }, h('span', { class: 'fw-cat' }, 'link'), h('h2', { class: 'fw-insp-title' }, 'Link')),+ h('p', { class: 'fw-insp-blurb' }, `${nodeLabel(a)} ${out?.label || ''} feeds ${nodeLabel(b)} ${inp?.label || ''}.`),+ h('section', { class: 'fw-section fw-insp-actions' }, h('button', { type: 'button', class: 'fw-btn is-sm is-danger', disabled: app.isRunning(), on: { click: () => app.deleteSelection() } }, icon(ICONS.trash, 13), 'Delete link', h('kbd', {}, 'Del'))),+ ];+ }++ function multiView(ids) {+ return [+ h('header', { class: 'fw-insp-head' }, h('h2', { class: 'fw-insp-title' }, `${ids.length} nodes selected`), h('p', { class: 'fw-insp-blurb' }, 'Drag any of them to move the group, or use the arrow keys.')),+ h(+ 'section',+ { class: 'fw-section fw-insp-actions' },+ h('button', { type: 'button', class: 'fw-btn is-sm is-ghost', disabled: app.isRunning(), on: { click: () => app.duplicate(ids) } }, 'Duplicate', h('kbd', {}, `${MOD}+D`)),+ h('button', { type: 'button', class: 'fw-btn is-sm is-danger', disabled: app.isRunning(), on: { click: () => app.deleteSelection() } }, icon(ICONS.trash, 13), 'Delete', h('kbd', {}, 'Del')),+ ),+ ];+ }++ function workflowView() {+ const wf = app.getWorkflow();+ const run = app.runState();+ const nameId = fid('wf-name');+ return [+ h('header', { class: 'fw-insp-head' }, h('span', { class: 'fw-cat' }, 'workflow'), h('h2', { class: 'fw-insp-title' }, 'Workflow')),+ h(+ 'section',+ { class: 'fw-section' },+ h(+ 'div',+ { class: 'fw-field' },+ h('label', { class: 'fw-label', for: nameId }, 'Name'),+ h('input', { id: nameId, class: 'fw-input', type: 'text', maxlength: 120, value: wf.name || '', on: { input: (e) => app.rename(e.target.value) } }),+ ),+ h('p', { class: 'fw-hint' }, `${wf.nodes.length} node${wf.nodes.length === 1 ? '' : 's'}, ${wf.edges.length} link${wf.edges.length === 1 ? '' : 's'}. Saved in this browser as you edit; use Export to keep a file.`),+ ),+ runSummary(run),+ h(+ 'section',+ { class: 'fw-section' },+ h('h3', { class: 'fw-section-title' }, 'Shortcuts'),+ h(+ 'dl',+ { class: 'fw-keys' },+ [+ [`${MOD}+Enter`, 'Run the workflow'],+ ['Delete', 'Remove the selection'],+ [`${MOD}+Z`, 'Undo'],+ [`${MOD}+Shift+Z`, 'Redo'],+ [`${MOD}+D`, 'Duplicate'],+ ['Arrow keys', 'Nudge (Shift for bigger steps)'],+ ['Esc', 'Cancel a run or clear the selection'],+ [`${MOD}+scroll`, 'Zoom at the pointer'],+ ].map(([k, d]) => [h('dt', {}, h('kbd', {}, k)), h('dd', {}, d)]),+ ),+ ),+ ];+ }++ function runSummary(run) {+ if (!run || run.status === 'idle') {+ return h('section', { class: 'fw-section' }, h('h3', { class: 'fw-section-title' }, 'Runs'), h('p', { class: 'fw-hint' }, `Nothing has run yet. Press Run or ${MOD}+Enter. Unchanged steps are reused on the next run, so trying a new setting only redoes what it affects.`));+ }+ const steps = [...run.steps.values()];+ const count = (s) => steps.filter((x) => x.status === s).length;+ const secs = ((run.finishedAt || Date.now()) - run.startedAt) / 1000;+ const word = { running: 'Running', done: 'Finished', failed: 'Finished with failures', cancelled: 'Cancelled' }[run.status] || run.status;+ const failedNodes = [...new Set(steps.filter((s) => s.status === 'failed').map((s) => s.nodeId))];+ return h(+ 'section',+ { class: 'fw-section' },+ h('h3', { class: 'fw-section-title' }, 'Last run'),+ h('p', { class: `fw-run-word is-${run.status}` }, `${word} · ${formatSeconds(secs)}`),+ h('p', { class: 'fw-hint' }, `${count('done')} done, ${count('failed')} failed, ${count('skipped')} skipped, ${count('cancelled')} cancelled of ${steps.length} steps.`),+ failedNodes.length+ ? h(+ 'ul',+ { class: 'fw-failed-list' },+ failedNodes.map((id) => {+ const n = app.getWorkflow().nodes.find((x) => x.id === id);+ return n ? h('li', {}, h('button', { type: 'button', class: 'fw-link', on: { click: () => app.focusNode(id) } }, nodeLabel(n))) : null;+ }),+ )+ : null,+ failedNodes.length && run.status !== 'running' ? h('button', { type: 'button', class: 'fw-btn is-sm', on: { click: () => app.retryFailed() } }, icon(ICONS.retry, 13), 'Retry failed steps') : null,+ );+ }++ function render() {+ const sel = app.selection();+ const wf = app.getWorkflow();+ let content;+ if (sel.edge) content = edgeView(sel.edge);+ else if (sel.nodes.length > 1) content = multiView(sel.nodes);+ else if (sel.nodes.length === 1) {+ const node = wf.nodes.find((n) => n.id === sel.nodes[0]);+ content = node ? nodeView(node) : workflowView();+ } else content = workflowView();+ root.textContent = '';+ root.append(...content.flat().filter(Boolean));+ }++ /** Refresh only the run-driven parts, without touching a field being typed in. */+ function refreshRun() {+ const active = document.activeElement;+ if (active && root.contains(active) && active.matches('input[type="text"], input[type="url"], input[type="number"], textarea')) return;+ render();+ }++ return { render, refreshRun };+}++function stepWord(s) {+ if (s.status === 'done') return s.reused ? 'Reused' : 'Done';+ return { pending: 'Waiting', running: 'Running', failed: 'Failed', cancelled: 'Cancelled', skipped: 'Skipped (an earlier step failed)' }[s.status] || s.status;+}++export function modlyExplain(res) {+ if (res.status === 'blocked' && res.reason === 'lna-denied') {+ return h('span', {}, 'Your browser blocked three.ws from reaching apps on this computer. Allow "Local network access" for three.ws in the site settings (the icon left of the address bar), then press Connect again.');+ }+ if (res.status === 'blocked') {+ return h('span', {}, 'This browser does not let an https page reach http://localhost. Open this page in Chrome or Edge, then press Connect again.');+ }+ return h('span', {}, 'Modly is not running on this computer. Open Modly (it listens on port 8765), then press Connect again.');+}+diff --git a/src/forge-workflows/main.js b/src/forge-workflows/main.jsnew file mode 100644index 000000000..547a457e8--- /dev/null+++ b/src/forge-workflows/main.js@@ -0,0 +1,821 @@+// Forge Workflows: page entry.+//+// Wires the pure graph core, the node registry, the runner and the real+// /api/forge executors to the canvas editor, the inspector and the phone layout.+// The page owns one workflow value; every edit replaces it through commit(),+// which records undo history and autosaves to this browser.++import {+ blockingIssues,+ cloneWithFreshIds,+ connect,+ canConnect,+ emptyWorkflow,+ parseWorkflow,+ preflight,+ pruneInvalidEdges,+ removeNodes,+ serializeWorkflow,+ topoSort,+} from './graph.js';+import { NODE_TYPES, PALETTE } from './node-types.js';+import { TEMPLATES, instantiateTemplate } from './templates.js';+import { createRunner, summarizeNode } from './runner.js';+import { EXECUTORS, CLIENT_HEADERS } from './executors.js';+import { createEditor, progressText } from './editor.js';+import { createInspector, paramForm } from './inspector.js';+import { createResults, releaseObjectUrls } from './results.js';+import { h, icon, ICONS, announce, toast, MOD, formatSeconds, typingInField } from './ui.js';+import { MODLY_INSTALL_URL, probeModly } from '../modly-local.js';++const types = NODE_TYPES;+const STORE_KEY = 'forge-workflows:v1:current';+const HISTORY_MAX = 100;+const COALESCE_MS = 1200;++const app = document.getElementById('fw-app');++// ── State ───────────────────────────────────────────────────────────────────+let workflow = loadSaved() || emptyWorkflow();+const past = [];+const future = [];+let lastCommit = { coalesce: null, at: 0 };+const ctx = { catalog: null, health: null, modly: null, signedIn: undefined };+let issues = [];+let saveTimer = 0;++function loadSaved() {+ let raw = null;+ try {+ raw = localStorage.getItem(STORE_KEY);+ } catch {+ return null;+ }+ if (!raw) return null;+ try {+ return parseWorkflow(raw, types);+ } catch (err) {+ queueMicrotask(() => toast(`Your saved workflow could not be restored: ${err.message}`, { tone: 'error', timeout: 7000 }));+ return null;+ }+}++function persist() {+ clearTimeout(saveTimer);+ saveTimer = setTimeout(() => {+ try {+ localStorage.setItem(STORE_KEY, serializeWorkflow(workflow, types));+ els.saved.textContent = 'Saved in this browser';+ } catch {+ els.saved.textContent = 'Not saved: browser storage is unavailable. Use Export.';+ }+ }, 400);+}++// ── Layout ──────────────────────────────────────────────────────────────────+const els = {};++function buildShell() {+ els.runBtn = h('button', { type: 'button', class: 'fw-btn is-primary', on: { click: () => (isRunning() ? runner.cancel() : runWorkflow()) } });+ els.freshBtn = h('button', { type: 'button', class: 'fw-btn is-ghost', title: 'Ignore reused results and run every step again', on: { click: () => runWorkflow({ mode: 'fresh' }) } }, icon(ICONS.retry, 14), h('span', { class: 'fw-hide-sm' }, 'Run fresh'));+ els.retryBtn = h('button', { type: 'button', class: 'fw-btn is-ghost', hidden: true, on: { click: retryFailed } }, icon(ICONS.retry, 14), 'Retry failed');+ els.status = h('div', { class: 'fw-runstatus', role: 'status', 'aria-live': 'polite' });+ els.undo = h('button', { type: 'button', class: 'fw-icon-btn', 'aria-label': `Undo (${MOD}+Z)`, title: `Undo (${MOD}+Z)`, on: { click: undo } }, icon(ICONS.undo));+ els.redo = h('button', { type: 'button', class: 'fw-icon-btn', 'aria-label': `Redo (${MOD}+Shift+Z)`, title: `Redo (${MOD}+Shift+Z)`, on: { click: redo } }, icon(ICONS.redo));+ els.importInput = h('input', { type: 'file', accept: '.json,application/json', class: 'fw-sr-only', id: 'fw-import', on: { change: onImportFile } });+ els.saved = h('span', { class: 'fw-saved' });+ els.templatesBtn = h('button', { type: 'button', class: 'fw-btn is-ghost', 'aria-haspopup': 'menu', 'aria-expanded': 'false', on: { click: toggleTemplates } }, icon(ICONS.grid, 14), 'Templates');+ els.templatesMenu = h(+ 'div',+ { class: 'fw-menu', role: 'menu', hidden: true },+ TEMPLATES.map((t) =>+ h(+ 'button',+ { type: 'button', role: 'menuitem', class: 'fw-menu-item', on: { click: () => loadTemplate(t.id) } },+ h('span', { class: 'fw-menu-title' }, t.title),+ h('span', { class: 'fw-menu-sub' }, t.description),+ ),+ ),+ h('div', { class: 'fw-menu-sep', role: 'separator' }),+ h('button', { type: 'button', role: 'menuitem', class: 'fw-menu-item', on: { click: clearCanvas } }, h('span', { class: 'fw-menu-title' }, 'Blank canvas'), h('span', { class: 'fw-menu-sub' }, 'Start from scratch. Undo brings the current graph back.')),+ );++ const toolbar = h(+ 'div',+ { class: 'fw-toolbar', role: 'toolbar', 'aria-label': 'Workflow' },+ h(+ 'div',+ { class: 'fw-tb-group' },+ h('a', { class: 'fw-crumb', href: '/forge' }, 'Forge'),+ h('span', { class: 'fw-crumb-sep', 'aria-hidden': 'true' }, '/'),+ h('h1', { class: 'fw-title' }, 'Workflows'),+ els.saved,+ ),+ h(+ 'div',+ { class: 'fw-tb-group' },+ h('div', { class: 'fw-menu-wrap' }, els.templatesBtn, els.templatesMenu),+ els.undo,+ els.redo,+ h('label', { class: 'fw-btn is-ghost', for: 'fw-import', title: 'Open a workflow file' }, icon(ICONS.upload, 14), h('span', { class: 'fw-hide-sm' }, 'Import')),+ els.importInput,+ h('button', { type: 'button', class: 'fw-btn is-ghost', title: 'Save this workflow as a file', on: { click: exportFile } }, icon(ICONS.download, 14), h('span', { class: 'fw-hide-sm' }, 'Export')),+ ),+ h('div', { class: 'fw-tb-group is-run' }, els.status, els.retryBtn, els.freshBtn, els.runBtn),+ );++ els.palette = h(+ 'aside',+ { class: 'fw-palette', 'aria-label': 'Add nodes' },+ h('p', { class: 'fw-palette-hint' }, 'Click to add, or drag onto the canvas.'),+ PALETTE.map((g) =>+ h(+ 'section',+ { class: 'fw-palette-group' },+ h('h2', { class: 'fw-palette-title' }, g.label),+ g.types.map((type) => {+ const def = types[type];+ const b = h(+ 'button',+ {+ type: 'button',+ class: `fw-palette-item cat-${def.category}`,+ draggable: 'true',+ title: def.blurb,+ on: {+ click: () => guardEdit() && editor.addNode(type),+ dragstart: (e) => {+ e.dataTransfer.setData('application/x-fw-node', type);+ e.dataTransfer.effectAllowed = 'copy';+ },+ },+ },+ h('span', { class: 'fw-node-dot', 'aria-hidden': 'true' }),+ h('span', {}, def.label),+ );+ return b;+ }),+ ),+ ),+ h('p', { class: 'fw-palette-foot' }, 'Run models on your own GPU: pick "Your GPU (Modly)" as the Generate engine.'),+ );++ els.canvas = h('div', { class: 'fw-canvas', tabindex: 0, role: 'application', 'aria-label': 'Workflow canvas. Tab to move between nodes; the inspector edits the selected node.' });+ els.empty = h(+ 'div',+ { class: 'fw-empty', hidden: true },+ h('h2', { class: 'fw-empty-title' }, 'Chain three.ws tools into one run'),+ h('p', { class: 'fw-empty-sub' }, 'Start from a template, or drag nodes in from the left and link an output dot to an input dot.'),+ h(+ 'div',+ { class: 'fw-empty-grid' },+ TEMPLATES.map((t) =>+ h(+ 'button',+ { type: 'button', class: 'fw-tcard', on: { click: () => loadTemplate(t.id) } },+ h('span', { class: 'fw-tcard-title' }, t.title),+ h('span', { class: 'fw-tcard-desc' }, t.description),+ h('span', { class: 'fw-tcard-needs' }, `Needs: ${t.needs}`),+ ),+ ),+ ),+ );+ els.zoomLabel = h('span', { class: 'fw-zoom-label' }, '100%');+ const zoom = h(+ 'div',+ { class: 'fw-zoom', role: 'group', 'aria-label': 'Zoom' },+ h('button', { type: 'button', class: 'fw-icon-btn', 'aria-label': 'Zoom out', on: { click: () => editor.zoomOut() } }, icon(ICONS.minus)),+ els.zoomLabel,+ h('button', { type: 'button', class: 'fw-icon-btn', 'aria-label': 'Zoom in', on: { click: () => editor.zoomIn() } }, icon(ICONS.plus)),+ h('button', { type: 'button', class: 'fw-icon-btn', 'aria-label': 'Fit the workflow on screen', title: 'Fit', on: { click: () => editor.fit() } }, icon(ICONS.fit)),+ );+ els.issues = h('div', { class: 'fw-issues', hidden: true });+ els.canvasWrap = h('section', { class: 'fw-canvas-wrap' }, els.canvas, els.empty, zoom, els.issues);+ els.inspector = h('aside', { class: 'fw-inspector', 'aria-label': 'Inspector' });+ els.linear = h('section', { class: 'fw-linear', 'aria-label': 'Workflow steps', hidden: true });++ app.textContent = '';+ app.append(toolbar, h('div', { class: 'fw-body' }, els.palette, els.canvasWrap, els.inspector), els.linear);+ app.dataset.state = 'ready';+}++// ── Commit / history ────────────────────────────────────────────────────────+function isRunning() {+ return runner.state.status === 'running';+}++/** Structural edits wait for the run to finish; moving nodes never does. */+function guardEdit() {+ if (!isRunning()) return true;+ toast('A run is in progress. Cancel it (Esc) to edit the workflow.', { tone: 'error' });+ return false;+}++function commit(next, label = 'Edit', { coalesce = null, structural = true } = {}) {+ if (isRunning() && !/^Move/.test(label)) {+ guardEdit();+ editor.render();+ return;+ }+ const now = Date.now();+ const merge = coalesce && lastCommit.coalesce === coalesce && now - lastCommit.at < COALESCE_MS;+ if (!merge) {+ past.push(workflow);+ if (past.length > HISTORY_MAX) past.shift();+ }+ future.length = 0;+ lastCommit = { coalesce, at: now };+ workflow = pruneInvalidEdges(next, types);+ afterChange({ structural });+}++function afterChange({ structural = true } = {}) {+ persist();+ recomputeIssues();+ editor.render();+ results.prune(new Set(workflow.nodes.map((n) => n.id)));+ paintRun();+ updateChrome();+ if (structural && isLinear()) renderLinear();+}++function undo() {+ if (!past.length || isRunning()) return;+ future.push(workflow);+ workflow = past.pop();+ lastCommit = { coalesce: null, at: 0 };+ afterChange();+ inspector.render();+ announce('Undone');+}++function redo() {+ if (!future.length || isRunning()) return;+ past.push(workflow);+ workflow = future.pop();+ lastCommit = { coalesce: null, at: 0 };+ afterChange();+ inspector.render();+ announce('Redone');+}++/** Replace the whole graph (template, import, blank). Undo restores the old one. */+function replaceWorkflow(next, label) {+ if (!guardEdit()) return;+ runner.clearCache();+ runner.reset();+ releaseObjectUrls();+ results.resetPages();+ commit(next, label);+ editor.clearSelection();+ inspector.render();+ requestAnimationFrame(() => editor.fit());+}++// ── Issues ──────────────────────────────────────────────────────────────────+function recomputeIssues() {+ issues = preflight(workflow, types, ctx);+ editor.setIssues(issues);+ const blocking = blockingIssues(issues);+ const warnings = issues.filter((i) => i.level === 'warning');+ els.issues.textContent = '';+ const show = workflow.nodes.length > 0 && issues.length > 0;+ els.issues.hidden = !show;+ if (!show) return;+ const open = els.issues.dataset.open === 'true';+ const head = h(+ 'button',+ {+ type: 'button',+ class: `fw-issues-head ${blocking.length ? 'is-error' : 'is-warning'}`,+ 'aria-expanded': String(open),+ on: {+ click: () => {+ els.issues.dataset.open = String(!open);+ recomputeIssues();+ },+ },+ },+ icon(ICONS.alert, 14),+ blocking.length ? `${blocking.length} thing${blocking.length === 1 ? '' : 's'} to fix before running` : `${warnings.length} note${warnings.length === 1 ? '' : 's'} before you run`,+ blocking.length && warnings.length ? h('span', { class: 'fw-issues-sub' }, ` and ${warnings.length} note${warnings.length === 1 ? '' : 's'}`) : null,+ );+ els.issues.append(head);+ if (open) {+ els.issues.append(+ h(+ 'ul',+ { class: 'fw-issues-list' },+ issues.map((i) =>+ h(+ 'li',+ { class: `is-${i.level}` },+ i.nodeId+ ? h('button', { type: 'button', class: 'fw-link', on: { click: () => editor.focusNode(i.nodeId) } }, i.message)+ : h('span', {}, i.message),+ ),+ ),+ ),+ );+ }+}++// ── Running ─────────────────────────────────────────────────────────────────+const runner = createRunner({ types, executors: EXECUTORS, onChange: () => schedulePaint() });++let paintQueued = false;+function schedulePaint() {+ if (paintQueued) return;+ paintQueued = true;+ requestAnimationFrame(() => {+ paintQueued = false;+ paintRun();+ });+}++let lastInspectorSig = '';+function paintRun() {+ const status = new Map();+ const ids = workflow.nodes.map((n) => n.id);+ for (const id of ids) {+ const steps = runner.stepsFor(id);+ if (steps.length) status.set(id, summarizeNode(steps));+ }+ editor.setStatus(status);+ const surface = isLinear() ? 'linear' : 'canvas';+ results.paintAll(ids, surface);+ if (surface === 'linear') paintLinearStatus(status);+ updateChrome();+ const sig = [runner.state.status, ...[...runner.state.steps.values()].map((s) => `${s.nodeId}${s.iter}${s.status}`)].join('|');+ if (sig !== lastInspectorSig) {+ lastInspectorSig = sig;+ inspector.refreshRun();+ }+}++async function runWorkflow({ mode = 'reuse', fromNodeId = null } = {}) {+ if (isRunning()) return;+ recomputeIssues();+ const blocking = blockingIssues(issues);+ if (blocking.length) {+ els.issues.dataset.open = 'true';+ recomputeIssues();+ const first = blocking.find((i) => i.nodeId);+ if (first && !isLinear()) editor.focusNode(first.nodeId);+ toast(blocking.length === 1 ? blocking[0].message : `Fix ${blocking.length} problems before running.`, { tone: 'error', timeout: 6000 });+ return;+ }+ if (mode === 'fresh') releaseObjectUrls();+ results.resetPages();+ announce('Workflow running');+ let final;+ try {+ final = await runner.run(workflow, { mode, fromNodeId, context: { modly: ctx.modly } });+ } catch (err) {+ toast(err?.message || 'The run could not start.', { tone: 'error' });+ return;+ }+ reportRun(final);+}++function reportRun(final) {+ const steps = [...final.steps.values()];+ const failed = steps.filter((s) => s.status === 'failed');+ const secs = formatSeconds((final.finishedAt - final.startedAt) / 1000);+ if (final.status === 'done') {+ const reused = steps.filter((s) => s.reused).length;+ const msg = reused === steps.length ? 'Nothing changed, so every step was reused.' : `Workflow finished in ${secs}.`;+ toast(msg, { tone: 'success' });+ announce(msg);+ } else if (final.status === 'cancelled') {+ toast('Run cancelled. Finished steps are kept; Run picks up where it stopped.');+ announce('Run cancelled');+ } else {+ const names = [...new Set(failed.map((s) => types[workflow.nodes.find((n) => n.id === s.nodeId)?.type]?.label).filter(Boolean))];+ const msg = `${failed.length} step${failed.length === 1 ? '' : 's'} failed (${names.join(', ')}). The rest of the run finished; open a red node to see why and retry.`;+ toast(msg, { tone: 'error', timeout: 8000 });+ announce(msg);+ const first = failed[0]?.nodeId;+ if (first && !isLinear()) editor.select([first]);+ }+}++function retryFailed() {+ runWorkflow({ mode: 'reuse' });+}++function runFrom(nodeId) {+ runWorkflow({ mode: 'reuse', fromNodeId: nodeId });+}++function updateChrome() {+ const running = isRunning();+ const state = runner.state;+ els.runBtn.textContent = '';+ els.runBtn.classList.toggle('is-danger', running);+ els.runBtn.classList.toggle('is-primary', !running);+ els.runBtn.append(icon(running ? ICONS.stop : ICONS.play, 14), running ? 'Cancel' : 'Run', h('kbd', { class: 'fw-hide-sm' }, running ? 'Esc' : `${MOD}+↵`));+ const blocked = blockingIssues(issues).length > 0;+ els.runBtn.setAttribute('aria-disabled', String(!running && blocked));+ els.runBtn.title = !running && blocked ? 'Fix the listed problems first' : '';+ els.freshBtn.hidden = running || state.status === 'idle';+ const anyFailed = [...state.steps.values()].some((s) => s.status === 'failed');+ els.retryBtn.hidden = running || !anyFailed;+ els.undo.disabled = running || !past.length;+ els.redo.disabled = running || !future.length;+ els.empty.hidden = workflow.nodes.length > 0;+ els.canvasWrap.classList.toggle('is-empty', workflow.nodes.length === 0);+ app.classList.toggle('is-running', running);+ els.status.textContent = statusLine(state);+ els.status.className = `fw-runstatus is-${state.status}`;+ if (els.linearRun) {+ els.linearRun.textContent = '';+ els.linearRun.append(icon(running ? ICONS.stop : ICONS.play, 16), running ? 'Cancel run' : 'Run workflow');+ els.linearRun.classList.toggle('is-danger', running);+ els.linearRun.classList.toggle('is-primary', !running);+ }+}++function statusLine(state) {+ if (state.status === 'idle') return '';+ const steps = [...state.steps.values()];+ if (state.status === 'running') {+ const active = state.activeKey ? state.steps.get(state.activeKey) : null;+ const node = active && workflow.nodes.find((n) => n.id === active.nodeId);+ const done = steps.filter((s) => s.status === 'done').length;+ const pct = active?.progress?.pct;+ const name = node ? types[node.type].label : 'Starting';+ return `${name}${pct != null ? ` ${active.progress.estimate ? '~' : ''}${pct}%` : ''} · ${done}/${steps.length} steps`;+ }+ const secs = formatSeconds(((state.finishedAt || Date.now()) - state.startedAt) / 1000);+ const failed = steps.filter((s) => s.status === 'failed').length;+ if (state.status === 'done') return `Done in ${secs}`;+ if (state.status === 'cancelled') return 'Cancelled';+ return `${failed} failed · ${secs}`;+}++// ── Editing helpers used by the inspector ───────────────────────────────────+function updateParam(nodeId, paramId, value, { coalesce = false } = {}) {+ const nodes = workflow.nodes.map((n) => (n.id === nodeId ? { ...n, params: { ...n.params, [paramId]: value } } : n));+ commit({ ...workflow, nodes }, 'Edit setting', { coalesce: coalesce ? `${nodeId}:${paramId}` : null, structural: false });+}++function deleteSelection() {+ if (!guardEdit()) return;+ const sel = editor.selection;+ if (sel.edge) {+ commit({ ...workflow, edges: workflow.edges.filter((e) => e.id !== sel.edge) }, 'Remove link');+ editor.clearSelection();+ announce('Link removed');+ return;+ }+ if (!sel.nodes.length) return;+ commit(removeNodes(workflow, sel.nodes), sel.nodes.length > 1 ? 'Delete nodes' : 'Delete node');+ editor.clearSelection();+ els.canvas.focus({ preventScroll: true });+ announce(sel.nodes.length > 1 ? `${sel.nodes.length} nodes deleted` : 'Node deleted');+}++function duplicate(ids) {+ if (!guardEdit() || !ids.length) return;+ const pick = new Set(ids);+ const sub = {+ ...workflow,+ nodes: workflow.nodes.filter((n) => pick.has(n.id)).map((n) => ({ ...n, x: n.x + 32, y: n.y + 32 })),+ edges: workflow.edges.filter((e) => pick.has(e.from.node) && pick.has(e.to.node)),+ };+ const copy = cloneWithFreshIds(sub);+ commit({ ...workflow, nodes: [...workflow.nodes, ...copy.nodes], edges: [...workflow.edges, ...copy.edges] }, 'Duplicate');+ editor.select(copy.nodes.map((n) => n.id));+}++async function connectModly() {+ const res = await probeModly();+ if (res.status === 'connected') {+ ctx.modly = { origin: res.origin, models: res.models || [] };+ const ready = ctx.modly.models.find((m) => m.downloaded);+ // Point every Modly generate node that has no model yet at the first ready one.+ if (ready) {+ const nodes = workflow.nodes.map((n) => (n.type === 'generate' && n.params.engine === 'modly' && !n.params.modlyModel ? { ...n, params: { ...n.params, modlyModel: ready.id } } : n));+ if (nodes.some((n, i) => n !== workflow.nodes[i])) commit({ ...workflow, nodes }, 'Pick Modly model');+ }+ recomputeIssues();+ editor.render();+ toast(ctx.modly.models.length ? `Modly connected with ${ctx.modly.models.length} model${ctx.modly.models.length === 1 ? '' : 's'}.` : 'Modly is running but has no models yet. Install one in Modly.', { tone: 'success' });+ }+ return res;+}++// ── Templates, import, export ───────────────────────────────────────────────+function toggleTemplates(force) {+ const open = typeof force === 'boolean' ? force : els.templatesMenu.hidden;+ els.templatesMenu.hidden = !open;+ els.templatesBtn.setAttribute('aria-expanded', String(open));+ if (open) els.templatesMenu.querySelector('button')?.focus();+}++function loadTemplate(id) {+ toggleTemplates(false);+ const t = TEMPLATES.find((x) => x.id === id);+ if (!t) return;+ const had = workflow.nodes.length > 0;+ replaceWorkflow(instantiateTemplate(id), `Load ${t.title}`);+ toast(had ? `Loaded "${t.title}". Undo (${MOD}+Z) brings back your previous graph.` : `Loaded "${t.title}". Fill in the inputs, then Run.`, { tone: 'success' });+}++function clearCanvas() {+ toggleTemplates(false);+ if (!workflow.nodes.length) return;+ replaceWorkflow(emptyWorkflow(), 'Clear canvas');+ toast(`Canvas cleared. Undo (${MOD}+Z) restores it.`);+}++async function onImportFile(e) {+ const file = e.target.files?.[0];+ e.target.value = '';+ if (!file) return;+ if (file.size > 2 * 1024 * 1024) {+ toast('That file is too large to be a workflow (over 2 MB).', { tone: 'error' });+ return;+ }+ try {+ const next = parseWorkflow(await file.text(), types);+ replaceWorkflow(next, 'Import');+ toast(`Imported "${next.name}".`, { tone: 'success' });+ } catch (err) {+ toast(err.message || 'That file could not be imported.', { tone: 'error', timeout: 6000 });+ }+}++function exportFile() {+ const text = serializeWorkflow(workflow, types);+ const slug = String(workflow.name || 'workflow').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'workflow';+ const url = URL.createObjectURL(new Blob([text], { type: 'application/json' }));+ const a = h('a', { href: url, download: `${slug}.forge-workflow.json` });+ document.body.append(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(url), 0);+ toast('Workflow file downloaded. Import it here any time.', { tone: 'success' });+}++// ── Phone layout ────────────────────────────────────────────────────────────+const phone = window.matchMedia('(max-width: 760px)');+function isLinear() {+ return phone.matches;+}++function applyLayout() {+ const linear = isLinear();+ app.dataset.layout = linear ? 'linear' : 'canvas';+ els.linear.hidden = !linear;+ if (linear) renderLinear();+ else {+ editor.render();+ requestAnimationFrame(() => editor.fit());+ }+ paintRun();+}++const LINEAR_EDITABLE = { prompt: ['text'], image: ['images'], forEach: ['mode', 'images', 'prompts'], loadMesh: ['url'] };++function renderLinear() {+ const order = topoSort(workflow).order;+ const nodes = order.map((id) => workflow.nodes.find((n) => n.id === id)).filter(Boolean);+ const pickId = 'fw-linear-template';+ const picker = h(+ 'select',+ {+ id: pickId,+ class: 'fw-input',+ on: {+ change: (e) => {+ if (e.target.value) loadTemplate(e.target.value);+ },+ },+ },+ h('option', { value: '' }, workflow.nodes.length ? `Current: ${workflow.name}` : 'Choose a template'),+ TEMPLATES.map((t) => h('option', { value: t.id }, t.title)),+ );+ els.linearSteps = new Map();+ const list = h(+ 'ol',+ { class: 'fw-linear-steps' },+ nodes.map((n, i) => {+ const def = types[n.type];+ const editable = LINEAR_EDITABLE[n.type];+ const badge = h('span', { class: 'fw-node-badge' });+ const prog = h('div', { class: 'fw-progress-label', hidden: true });+ els.linearSteps.set(n.id, { badge, prog });+ return h(+ 'li',+ { class: `fw-linear-step cat-${def.category}`, dataset: { id: n.id } },+ h('div', { class: 'fw-linear-head' }, h('span', { class: 'fw-linear-num' }, String(i + 1)), h('span', { class: 'fw-linear-title' }, def.label), badge),+ h('div', { class: 'fw-node-summary' }, def.summary ? def.summary(n.params || {}, ctx) : ''),+ editable+ ? paramForm(n, def, ctx, (paramId, value, { rerender } = {}) => {+ updateParam(n.id, paramId, value, { coalesce: !rerender });+ if (rerender) renderLinear();+ }, { only: editable, disabled: isRunning() })+ : null,+ prog,+ results.hostFor(n.id, 'linear'),+ );+ }),+ );+ els.linearRun = h('button', { type: 'button', class: 'fw-btn is-primary is-block', on: { click: () => (isRunning() ? runner.cancel() : runWorkflow()) } });+ const blocking = blockingIssues(issues);+ els.linear.textContent = '';+ els.linear.append(+ h('div', { class: 'fw-field' }, h('label', { class: 'fw-label', for: pickId }, 'Workflow'), picker),+ h('p', { class: 'fw-hint' }, 'Rearranging nodes needs a larger screen. Here you can pick a template, fill in its prompt or photos, and run it.'),+ nodes.length ? list : h('p', { class: 'fw-linear-empty' }, 'Pick a template above to get started.'),+ blocking.length ? h('ul', { class: 'fw-issues-list is-inline' }, blocking.map((i) => h('li', { class: 'is-error' }, i.message))) : null,+ h('div', { class: 'fw-linear-bar' }, els.linearRun),+ );+ updateChrome();+ paintRun();+}++function paintLinearStatus(status) {+ if (!els.linearSteps) return;+ for (const [id, parts] of els.linearSteps) {+ const s = status.get(id);+ const st = s?.status || 'idle';+ parts.badge.className = `fw-node-badge is-${st}`;+ parts.badge.textContent = st === 'idle' ? '' : `${{ pending: 'Waiting', running: 'Running', done: 'Done', partial: 'Partial', failed: 'Failed', cancelled: 'Cancelled', skipped: 'Skipped' }[st]}${s.total > 1 ? ` ${s.done}/${s.total}` : ''}`;+ parts.prog.hidden = st !== 'running';+ if (st === 'running') parts.prog.textContent = progressText(s.running?.progress, s);+ }+}++// ── Keyboard ────────────────────────────────────────────────────────────────+function onKey(e) {+ const mod = e.metaKey || e.ctrlKey;+ if (mod && e.key === 'Enter') {+ e.preventDefault();+ if (!isRunning()) runWorkflow();+ return;+ }+ if (e.key === 'Escape') {+ if (!els.templatesMenu.hidden) {+ toggleTemplates(false);+ els.templatesBtn.focus();+ return;+ }+ if (isRunning()) {+ runner.cancel();+ return;+ }+ if (!typingInField(e.target)) editor.clearSelection();+ return;+ }+ if (typingInField(e.target) || isLinear()) return;+ if (mod && (e.key === 'z' || e.key === 'Z')) {+ e.preventDefault();+ if (e.shiftKey) redo();+ else undo();+ return;+ }+ if (mod && (e.key === 'y' || e.key === 'Y')) {+ e.preventDefault();+ redo();+ return;+ }+ const inApp = app.contains(e.target) || e.target === document.body;+ if (!inApp) return;+ if (mod && (e.key === 'd' || e.key === 'D')) {+ e.preventDefault();+ duplicate(editor.selection.nodes);+ return;+ }+ if (e.key === 'Delete' || e.key === 'Backspace') {+ if (e.target.closest?.('button, a')) return;+ e.preventDefault();+ deleteSelection();+ return;+ }+ const arrows = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] };+ if (arrows[e.key] && editor.selection.nodes.length && !e.target.closest?.('button, a, .fw-quickadd')) {+ e.preventDefault();+ const step = e.shiftKey ? 40 : 8;+ editor.nudge(arrows[e.key][0] * step, arrows[e.key][1] * step);+ }+}++// ── Live context ────────────────────────────────────────────────────────────+async function loadContext() {+ const get = async (url, init) => {+ try {+ const res = await fetch(url, init);+ return res.ok ? await res.json() : null;+ } catch {+ return null;+ }+ };+ const [catalog, health, me] = await Promise.all([+ get('/api/forge?catalog=1', { headers: CLIENT_HEADERS }),+ get('/api/forge?health=1', { headers: CLIENT_HEADERS }),+ get('/api/auth/me', { credentials: 'include', headers: { 'x-witness': 'handled' } }),+ ]);+ ctx.catalog = catalog;+ ctx.health = health?.backends || null;+ ctx.signedIn = me ? Boolean(me.user) : undefined;+ if (!catalog) toast('The engine list did not load, so engine checks are limited. Auto still picks a working engine when you run.', { tone: 'error', timeout: 7000 });+ recomputeIssues();+ editor.render();+ inspector.render();+ if (isLinear()) renderLinear();+ updateChrome();+}++// ── Boot ────────────────────────────────────────────────────────────────────+buildShell();++const results = createResults({+ types,+ getNode: (id) => workflow.nodes.find((n) => n.id === id),+ stepsFor: (id) => runner.stepsFor(id),+ onRetry: (nodeId) => {+ if (isRunning()) return;+ runWorkflow({ mode: 'reuse' });+ announce(`Retrying ${types[workflow.nodes.find((n) => n.id === nodeId)?.type]?.label || 'step'}`);+ },+});++const editor = createEditor(els.canvas, {+ types,+ getWorkflow: () => workflow,+ getContext: () => ctx,+ commit: (wf, label) => commit(wf, label),+ onSelect: () => inspector.render(),+ onError: (msg) => toast(msg, { tone: 'error' }),+ resultHost: (id) => results.hostFor(id, 'canvas'),+ onView: (z) => {+ if (els.zoomLabel) els.zoomLabel.textContent = `${Math.round(z * 100)}%`;+ },+});++const inspector = createInspector(els.inspector, {+ types,+ getWorkflow: () => workflow,+ getContext: () => ctx,+ selection: () => editor.selection,+ updateParam,+ canLink: (from, to) => canConnect({ ...workflow, edges: workflow.edges.filter((e) => !(e.to.node === to.node && e.to.port === to.port)) }, types, from, to).ok,+ linkInput: (from, to) => {+ if (!guardEdit()) return;+ const res = connect(workflow, types, from, to);+ if (res.error) toast(res.error, { tone: 'error' });+ else commit(res.workflow, 'Link nodes');+ },+ unlinkInput: (nodeId, portId) => {+ if (!guardEdit()) return;+ commit({ ...workflow, edges: workflow.edges.filter((e) => !(e.to.node === nodeId && e.to.port === portId)) }, 'Remove link');+ },+ stepsFor: (id) => runner.stepsFor(id),+ runState: () => runner.state,+ isRunning,+ issues: () => issues,+ hasBlocking: () => blockingIssues(issues).length > 0,+ runFrom,+ retryFailed,+ duplicate,+ deleteSelection,+ focusNode: (id) => editor.focusNode(id),+ rename: (name) => {+ commit({ ...workflow, name: name.slice(0, 120) }, 'Rename', { coalesce: 'name' });+ },+ connectModly,+ get modly() {+ return ctx.modly;+ },+ modlyInstallUrl: MODLY_INSTALL_URL,+});++document.addEventListener('keydown', onKey);+document.addEventListener('pointerdown', (e) => {+ if (!els.templatesMenu.hidden && !e.target.closest('.fw-menu-wrap')) toggleTemplates(false);+});+phone.addEventListener('change', applyLayout);+window.addEventListener('beforeunload', (e) => {+ if (isRunning()) {+ e.preventDefault();+ e.returnValue = '';+ }+});++const requested = new URLSearchParams(location.search).get('template');+if (requested && TEMPLATES.some((t) => t.id === requested)) {+ workflow = instantiateTemplate(requested);+ history.replaceState(null, '', location.pathname);+ persist();+}++recomputeIssues();+editor.render();+inspector.render();+updateChrome();+applyLayout();+requestAnimationFrame(() => editor.fit());+loadContext();diff --git a/src/forge-workflows/node-types.js b/src/forge-workflows/node-types.jsnew file mode 100644index 000000000..959bcc66d--- /dev/null+++ b/src/forge-workflows/node-types.js@@ -0,0 +1,475 @@+// Forge Workflows: the node registry.+//+// Each entry describes one kind of node: its ports, its params (which drive the+// inspector form), which inputs a run needs, and node-specific preflight checks.+// The registry is pure data plus small pure functions, so graph.js and the tests+// can use it without a browser. The network side of each node lives in+// executors.js under the same key.+//+// Param fields:+// id, label, kind ('text' | 'textarea' | 'select' | 'number' | 'images' | 'mesh-url'),+// default, options ([{ value, label }] or a function of ctx for live catalogs),+// min / max / step (number), hint (one line under the field),+// showIf(params) (hide the field when false), transient (never exported),+// signatureExclude (editing it does not invalidate a cached result).++/** Engines the workflow can drive, read from the live /api/forge catalog. */+export function engineOptions(ctx, mode) {+ const options = [{ value: 'auto', label: 'Auto (best free engine)' }];+ for (const b of ctx?.catalog?.backends || []) {+ if (!Array.isArray(b.paths) || !b.paths.includes('image')) continue;+ if (mode === 'image' && !b.user_images) continue;+ if (!b.configured || b.byok) continue;+ const health = ctx?.health?.[b.id]?.status;+ const suffix = health === 'down' ? ' (down right now)' : health === 'degraded' ? ' (degraded)' : b.free ? ' (free)' : '';+ options.push({ value: b.id, label: `${b.label.replace(/\s*\(free\)\s*$/i, '')}${suffix}` });+ }+ if (mode === 'image') options.push({ value: 'modly', label: 'Your GPU (Modly)' });+ return options;+}++const TIER_OPTIONS = [+ { value: 'draft', label: 'Draft (fastest)' },+ { value: 'standard', label: 'Standard' },+ { value: 'high', label: 'High ($THREE holders)' },+];++const IMAGE_URL_RE = /^https:\/\/[^\s]+$/i;++export function promptLines(text) {+ return String(text || '')+ .split(/\r?\n/)+ .map((s) => s.trim())+ .filter(Boolean)+ .slice(0, 50);+}++function imageList(value) {+ return (Array.isArray(value) ? value : []).filter((i) => i && typeof i.url === 'string' && IMAGE_URL_RE.test(i.url));+}++export const NODE_TYPES = {+ image: {+ label: 'Image',+ category: 'input',+ blurb: 'A photo to turn into 3D. Uploaded once to three.ws storage, so the workflow file stays portable.',+ inputs: [],+ outputs: [{ id: 'image', type: 'image', label: 'Image' }],+ params: [{ id: 'images', label: 'Photo', kind: 'images', max: 1, default: [], hint: 'PNG, JPEG or WebP up to 8 MB.' }],+ validate(node) {+ return imageList(node.params.images).length ? [] : ['upload a photo.'];+ },+ summary(params) {+ return imageList(params.images)[0]?.name || 'No photo yet';+ },+ },++ prompt: {+ label: 'Text prompt',+ category: 'input',+ blurb: 'Describe the object. Generate turns it into a reference image, then a 3D model.',+ inputs: [],+ outputs: [{ id: 'text', type: 'text', label: 'Text' }],+ params: [{ id: 'text', label: 'Prompt', kind: 'textarea', default: '', maxLength: 1000, hint: 'One clear object works best, e.g. "a weathered brass lantern".' }],+ validate(node) {+ const t = String(node.params.text || '').trim();+ if (!t) return ['write a prompt.'];+ if (t.length > 1000) return ['keep the prompt under 1000 characters.'];+ return [];+ },+ summary(params) {+ return String(params.text || '').trim() || 'Empty prompt';+ },+ },++ loadMesh: {+ label: 'Load 3D',+ category: 'input',+ blurb: 'Start from an existing GLB: paste a public https link or upload a file.',+ inputs: [],+ outputs: [{ id: 'mesh', type: 'mesh', label: 'Model' }],+ params: [+ { id: 'url', label: 'GLB', kind: 'mesh-url', default: '', hint: 'A public https link to a .glb, or upload one (up to 200 MB).' },+ { id: 'name', label: 'Name', kind: 'text', default: '', signatureExclude: true },+ ],+ validate(node) {+ const url = String(node.params.url || '').trim();+ if (!url) return ['add a GLB link or upload a file.'];+ if (!/^https:\/\//i.test(url)) return ['the GLB link must start with https://.'];+ return [];+ },+ summary(params) {+ return params.name || (params.url ? String(params.url).split('/').pop().slice(0, 40) : 'No model yet');+ },+ },++ forEach: {+ label: 'For Each',+ category: 'input',+ iterator: true,+ blurb: 'Runs everything connected after it once per item, in order. A failed item does not stop the rest.',+ inputs: [],+ outputs(params) {+ return params.mode === 'text' ? [{ id: 'item', type: 'text', label: 'Prompt' }] : [{ id: 'item', type: 'image', label: 'Image' }];+ },+ params: [+ {+ id: 'mode',+ label: 'Repeat over',+ kind: 'select',+ default: 'image',+ options: [+ { value: 'image', label: 'A batch of photos' },+ { value: 'text', label: 'A list of prompts' },+ ],+ },+ { id: 'images', label: 'Photos', kind: 'images', max: 12, default: [], showIf: (p) => p.mode !== 'text', hint: 'Up to 12 photos, each processed separately.' },+ { id: 'prompts', label: 'Prompts', kind: 'textarea', default: '', showIf: (p) => p.mode === 'text', hint: 'One prompt per line, up to 50.' },+ ],+ items(params) {+ return params.mode === 'text' ? promptLines(params.prompts) : imageList(params.images);+ },+ validate(node) {+ const count = NODE_TYPES.forEach.items(node.params).length;+ if (!count) return [node.params.mode === 'text' ? 'add at least one prompt (one per line).' : 'upload at least one photo.'];+ return [];+ },+ summary(params) {+ const n = NODE_TYPES.forEach.items(params).length;+ return params.mode === 'text' ? `${n} prompt${n === 1 ? '' : 's'}` : `${n} photo${n === 1 ? '' : 's'}`;+ },+ },++ generate: {+ label: 'Generate 3D',+ category: 'generate',+ blurb: 'Turns a prompt or a photo into a textured 3D model on three.ws engines, or on your own GPU through Modly.',+ inputs(params) {+ return params.mode === 'image'+ ? [+ { id: 'image', type: 'image', label: 'Image' },+ { id: 'prompt', type: 'text', label: 'Hint', optional: true },+ ]+ : [{ id: 'prompt', type: 'text', label: 'Prompt' }];+ },+ outputs: [{ id: 'mesh', type: 'mesh', label: 'Model' }],+ params: [+ {+ id: 'mode',+ label: 'From',+ kind: 'select',+ default: 'text',+ options: [+ { value: 'text', label: 'Text prompt' },+ { value: 'image', label: 'Photo' },+ ],+ },+ { id: 'engine', label: 'Engine', kind: 'select', default: 'auto', options: (ctx, params) => engineOptions(ctx, params.mode) },+ { id: 'tier', label: 'Quality', kind: 'select', default: 'draft', options: TIER_OPTIONS, showIf: (p) => p.engine !== 'modly' },+ {+ id: 'modlyModel',+ label: 'Modly model',+ kind: 'select',+ default: '',+ options: (ctx) =>+ (ctx?.modly?.models || []).map((m) => ({ value: m.id, label: `${m.name}${m.downloaded ? '' : ' (not downloaded)'}` })),+ showIf: (p) => p.engine === 'modly',+ hint: 'Runs on your machine. Connect Modly in the inspector to list your models.',+ },+ ],+ validate(node, ctx = {}) {+ const p = node.params;+ const out = [];+ if (p.engine === 'modly') {+ if (p.mode !== 'image') out.push('Your GPU (Modly) turns photos into 3D. Switch From to Photo, or pick a cloud engine.');+ if (!ctx.modly) out.push('connect Modly first (select this node, then Connect in the inspector).');+ else if (!p.modlyModel) out.push('pick a Modly model.');+ else {+ const model = ctx.modly.models?.find((m) => m.id === p.modlyModel);+ if (!model) out.push(`Modly does not have "${p.modlyModel}" installed.`);+ else if (!model.downloaded) out.push(`download ${model.name} in Modly first.`);+ }+ return out;+ }+ if (p.engine !== 'auto' && ctx.catalog) {+ const b = ctx.catalog.backends?.find((x) => x.id === p.engine);+ if (!b) out.push(`the engine "${p.engine}" is not available. Pick another engine.`);+ else if (b.byok) out.push(`${b.label} needs your own API key. Use /forge for key-based engines, or pick a free engine here.`);+ else if (!b.configured) out.push(`${b.label} is not enabled on three.ws right now. Pick another engine.`);+ else if (p.mode === 'image' && !b.user_images) out.push(`${b.label} only takes text prompts. Pick another engine for photos.`);+ else if (ctx.health?.[b.id]?.status === 'down') out.push({ level: 'warning', message: `${b.label} is reporting down; the run may fail. Auto picks a healthy engine.` });+ }+ if (p.tier === 'high') out.push({ level: 'warning', message: 'High quality is a $THREE holder perk. Non-holders get a clear prompt to hold or pay when it runs.' });+ return out;+ },+ summary(params, ctx) {+ const engine = engineOptions(ctx, params.mode).find((o) => o.value === params.engine)?.label || params.engine;+ return params.engine === 'modly' ? `Modly${params.modlyModel ? ` · ${params.modlyModel}` : ''}` : `${engine} · ${params.tier}`;+ },+ },++ remesh: {+ label: 'Remesh',+ category: 'process',+ blurb: 'Rebuilds the topology: clean triangles, quads, or a low-poly look, at a face budget.',+ inputs: [{ id: 'mesh', type: 'mesh', label: 'Model' }],+ outputs: [{ id: 'mesh', type: 'mesh', label: 'Model' }],+ params: [+ {+ id: 'mode',+ label: 'Topology',+ kind: 'select',+ default: 'triangle',+ options: [+ { value: 'triangle', label: 'Triangles' },+ { value: 'quad', label: 'Quads' },+ { value: 'lowpoly', label: 'Low-poly' },+ ],+ },+ {+ id: 'operation',+ label: 'Operation',+ kind: 'select',+ default: 'full',+ showIf: (p) => p.mode === 'triangle',+ options: [+ { value: 'full', label: 'Repair and simplify' },+ { value: 'simplify', label: 'Simplify only' },+ { value: 'repair', label: 'Repair only' },+ { value: 'convert', label: 'Convert only' },+ ],+ },+ { id: 'targetFaces', label: 'Target faces', kind: 'number', default: 50000, min: 1000, max: 500000, step: 1000 },+ {+ id: 'textureSize',+ label: 'Texture',+ kind: 'select',+ default: 1024,+ options: [+ { value: 512, label: '512 px' },+ { value: 1024, label: '1024 px' },+ { value: 2048, label: '2048 px' },+ ],+ },+ ],+ summary(params) {+ return `${params.mode} · ${Number(params.targetFaces).toLocaleString('en-US')} faces`;+ },+ },++ rig: {+ label: 'Auto-rig',+ category: 'process',+ blurb: 'Adds a humanoid skeleton so the model can be animated. Works best on a character standing upright.',+ inputs: [{ id: 'mesh', type: 'mesh', label: 'Model' }],+ outputs: [{ id: 'mesh', type: 'mesh', label: 'Rigged model' }],+ params: [],+ summary() {+ return 'Humanoid skeleton';+ },+ },++ segment: {+ label: 'Segment',+ category: 'process',+ blurb: 'Splits the model into separate named parts you can recolor or animate one by one.',+ inputs: [{ id: 'mesh', type: 'mesh', label: 'Model' }],+ outputs: [{ id: 'mesh', type: 'mesh', label: 'Parts' }],+ params: [+ {+ id: 'method',+ label: 'Method',+ kind: 'select',+ default: 'auto',+ options: [+ { value: 'auto', label: 'Auto' },+ { value: 'connected', label: 'Connected pieces' },+ { value: 'crease', label: 'Sharp creases' },+ ],+ },+ { id: 'maxParts', label: 'Max parts', kind: 'number', default: 24, min: 2, max: 64, step: 1 },+ ],+ summary(params) {+ return `${params.method} · up to ${params.maxParts} parts`;+ },+ },++ stylize: {+ label: 'Stylize',+ category: 'process',+ blurb: 'Rebuilds the model in a new style: voxels, bricks, Voronoi cells or low-poly facets.',+ inputs: [{ id: 'mesh', type: 'mesh', label: 'Model' }],+ outputs: [{ id: 'mesh', type: 'mesh', label: 'Model' }],+ params: [+ {+ id: 'style',+ label: 'Style',+ kind: 'select',+ default: 'voxel',+ options: [+ { value: 'voxel', label: 'Voxel' },+ { value: 'brick', label: 'Brick' },+ { value: 'voronoi', label: 'Voronoi' },+ { value: 'lowpoly', label: 'Low-poly' },+ ],+ },+ ],+ summary(params) {+ return params.style;+ },+ },++ gameready: {+ label: 'Game-ready',+ category: 'process',+ blurb: 'Retopologizes to a poly budget and bakes PBR textures, with GLB and FBX ready for Unity or Unreal. A $THREE holder tool.',+ inputs: [{ id: 'mesh', type: 'mesh', label: 'Model' }],+ outputs: [{ id: 'mesh', type: 'mesh', label: 'Model' }],+ params: [+ {+ id: 'topology',+ label: 'Topology',+ kind: 'select',+ default: 'quad',+ options: [+ { value: 'quad', label: 'Quads' },+ { value: 'tri', label: 'Triangles' },+ ],+ },+ {+ id: 'polyBudget',+ label: 'Poly budget',+ kind: 'select',+ default: 15000,+ options: [+ { value: 5000, label: '5,000 (mobile)' },+ { value: 15000, label: '15,000 (default)' },+ { value: 50000, label: '50,000 (hero asset)' },+ ],+ },+ {+ id: 'textureSize',+ label: 'Texture',+ kind: 'select',+ default: 1024,+ options: [+ { value: 1024, label: '1024 px' },+ { value: 2048, label: '2048 px' },+ ],+ },+ ],+ summary(params) {+ return `${params.topology} · ${Number(params.polyBudget).toLocaleString('en-US')} polys`;+ },+ },++ preview: {+ label: 'Preview',+ category: 'output',+ blurb: 'Shows the model in an interactive 3D viewer right on the node.',+ inputs: [{ id: 'mesh', type: 'mesh', label: 'Model' }],+ outputs: [],+ params: [],+ summary() {+ return 'Interactive viewer';+ },+ },++ export: {+ label: 'Export',+ category: 'output',+ blurb: 'Downloads the model as GLB, or converts it to STL, OBJ or PLY in your browser.',+ inputs: [{ id: 'mesh', type: 'mesh', label: 'Model' }],+ outputs: [],+ params: [+ {+ id: 'format',+ label: 'Format',+ kind: 'select',+ default: 'glb',+ options: [+ { value: 'glb', label: 'GLB (textured)' },+ { value: 'fbx', label: 'FBX (from Game-ready)' },+ { value: 'stl', label: 'STL (3D printing)' },+ { value: 'obj', label: 'OBJ' },+ { value: 'ply', label: 'PLY' },+ ],+ },+ { id: 'filename', label: 'File name', kind: 'text', default: 'forge-model', signatureExclude: true },+ { id: 'autoDownload', label: 'Download automatically when done', kind: 'checkbox', default: true, signatureExclude: true },+ ],+ validate(node) {+ const name = String(node.params.filename || '').trim();+ if (!name) return ['give the file a name.'];+ if (/[\\/:*?"<>|]/.test(name)) return ['the file name cannot contain \\ / : * ? " < > |.'];+ return [];+ },+ summary(params) {+ return `${params.filename || 'model'}.${params.format}`;+ },+ },++ save: {+ label: 'Save',+ category: 'output',+ blurb: 'Keeps the model on three.ws: in your avatar library (signed in) or in the public creations gallery.',+ inputs: [{ id: 'mesh', type: 'mesh', label: 'Model' }],+ outputs: [],+ params: [+ {+ id: 'destination',+ label: 'Save to',+ kind: 'select',+ default: 'library',+ options: [+ { value: 'library', label: 'My library (sign in)' },+ { value: 'gallery', label: 'Public creations gallery' },+ ],+ },+ { id: 'name', label: 'Name', kind: 'text', default: 'Forge workflow model', maxLength: 80 },+ {+ id: 'visibility',+ label: 'Visibility',+ kind: 'select',+ default: 'unlisted',+ showIf: (p) => p.destination === 'library',+ options: [+ { value: 'private', label: 'Private' },+ { value: 'unlisted', label: 'Unlisted (link only)' },+ { value: 'public', label: 'Public' },+ ],+ },+ ],+ validate(node, ctx = {}) {+ const name = String(node.params.name || '').trim();+ if (!name) return ['give the model a name.'];+ if (name.length > 80) return ['keep the name under 80 characters.'];+ if (node.params.destination === 'library' && ctx.signedIn === false) {+ return [{ level: 'warning', message: 'you are signed out, so saving to your library will ask you to sign in.' }];+ }+ return [];+ },+ summary(params) {+ return params.destination === 'gallery' ? 'Public gallery' : `Library · ${params.visibility}`;+ },+ },+};++/** Palette groups in display order. */+export const PALETTE = [+ { id: 'input', label: 'Inputs', types: ['prompt', 'image', 'loadMesh', 'forEach'] },+ { id: 'generate', label: 'Generate', types: ['generate'] },+ { id: 'process', label: 'Process', types: ['remesh', 'rig', 'segment', 'stylize', 'gameready'] },+ { id: 'output', label: 'Outputs', types: ['preview', 'export', 'save'] },+];++/** Resolve a param's options (static list or a function of the live context). */+export function paramOptions(param, ctx, params) {+ if (typeof param.options === 'function') return param.options(ctx, params) || [];+ return param.options || [];+}++/** Params that should currently show in the inspector. */+export function visibleParams(def, params) {+ return (def?.params || []).filter((p) => !p.showIf || p.showIf(params));+}diff --git a/src/forge-workflows/results.js b/src/forge-workflows/results.jsnew file mode 100644index 000000000..e1f0612a0--- /dev/null+++ b/src/forge-workflows/results.js@@ -0,0 +1,209 @@+// Forge Workflows: what a node shows after it runs.+//+// One persistent host element per node and surface (the canvas card or the+// phone layout). A host is only rebuilt when what it shows actually changed, so+// a 3D preview keeps its camera while other steps report progress.++import { h, icon, ICONS } from './ui.js';++const blobUrls = new Map();++/** A stable object URL for a local model (made on the user's GPU). */+export function blobUrl(blob) {+ let url = blobUrls.get(blob);+ if (!url) {+ url = URL.createObjectURL(blob);+ blobUrls.set(blob, url);+ }+ return url;+}++const exportUrls = new Set();++/** Free every object URL the page made. Called when cached results are dropped. */+export function releaseObjectUrls() {+ for (const url of blobUrls.values()) URL.revokeObjectURL(url);+ blobUrls.clear();+ for (const url of exportUrls) URL.revokeObjectURL(url);+ exportUrls.clear();+}++export function meshSrc(mesh) {+ if (!mesh) return null;+ if (mesh.url) return mesh.url;+ if (mesh.blob) return blobUrl(mesh.blob);+ return null;+}++/**+ * @param {object} opts+ * @param {(nodeId:string) => object|undefined} opts.getNode+ * @param {(nodeId:string) => Array} opts.stepsFor+ * @param {(nodeId:string, iter:number|null) => void} opts.onRetry+ */+export function createResults({ getNode, stepsFor, onRetry, types }) {+ const hosts = { canvas: new Map(), linear: new Map() };+ const page = new Map();+ const shown = new Map();++ function hostFor(nodeId, surface = 'canvas') {+ let el = hosts[surface].get(nodeId);+ if (!el) {+ el = h('div', { class: 'fw-result', dataset: { node: nodeId } });+ hosts[surface].set(nodeId, el);+ }+ return el;+ }++ function viewKey(nodeId, steps, idx) {+ const s = steps[idx];+ if (!s) return 'none';+ const r = s.result || {};+ return [steps.length, idx, s.status, meshSrc(r.mesh) || '', r.download?.href || '', s.error?.message || '', (r.links || []).map((l) => l.href).join(','), r.stats || '', r.note || '', s.reused ? 1 : 0].join('|');+ }++ function pickIndex(nodeId, steps) {+ if (!steps.length) return 0;+ const want = page.get(nodeId);+ if (want != null && want < steps.length) return want;+ // Default to the item that needs attention, else the latest finished one.+ const failed = steps.findIndex((s) => s.status === 'failed');+ if (failed >= 0) return failed;+ for (let i = steps.length - 1; i >= 0; i--) if (steps[i].status === 'done') return i;+ return 0;+ }++ function paint(nodeId, surface = 'canvas') {+ const host = hostFor(nodeId, surface);+ const node = getNode(nodeId);+ if (!node) return;+ const steps = stepsFor(nodeId);+ const idx = pickIndex(nodeId, steps);+ const key = `${surface}:${viewKey(nodeId, steps, idx)}`;+ if (shown.get(host) === key) return;+ shown.set(host, key);+ host.textContent = '';+ const step = steps[idx];+ if (!step || !['done', 'failed'].includes(step.status)) {+ host.hidden = true;+ return;+ }+ host.hidden = false;+ if (steps.length > 1) host.append(pager(nodeId, steps, idx, surface));+ if (step.status === 'failed') host.append(errorBlock(nodeId, step));+ else host.append(...doneBlock(node, step));+ }++ function pager(nodeId, steps, idx, surface) {+ const go = (d) => {+ page.set(nodeId, (idx + d + steps.length) % steps.length);+ paint(nodeId, surface);+ };+ const dot = (s) => (s.status === 'done' ? 'is-done' : s.status === 'failed' ? 'is-failed' : '');+ return h(+ 'div',+ { class: 'fw-pager' },+ h('button', { type: 'button', class: 'fw-icon-btn is-sm', 'aria-label': 'Previous item', on: { click: () => go(-1) } }, '‹'),+ h('span', { class: 'fw-pager-label' }, `Item ${idx + 1} of ${steps.length}`),+ h('span', { class: 'fw-pager-dots', 'aria-hidden': 'true' }, steps.slice(0, 12).map((s, i) => h('span', { class: `fw-pager-dot ${dot(s)} ${i === idx ? 'is-current' : ''}` }))),+ h('button', { type: 'button', class: 'fw-icon-btn is-sm', 'aria-label': 'Next item', on: { click: () => go(1) } }, '›'),+ );+ }++ function errorBlock(nodeId, step) {+ const err = step.error || {};+ return h(+ 'div',+ { class: 'fw-error', role: 'alert' },+ h('div', { class: 'fw-error-msg' }, icon(ICONS.alert, 14), h('span', {}, err.message || 'This step failed.')),+ h(+ 'div',+ { class: 'fw-error-actions' },+ (err.actions || []).map((a) => h('a', { class: 'fw-btn is-sm is-ghost', href: a.href, target: /^https?:/.test(a.href) ? '_blank' : null, rel: /^https?:/.test(a.href) ? 'noopener' : null }, a.label)),+ h('button', { type: 'button', class: 'fw-btn is-sm', on: { click: () => onRetry(nodeId, step.iter) } }, icon(ICONS.retry, 13), err.retryAfter ? `Retry (wait ~${err.retryAfter}s)` : 'Retry'),+ ),+ );+ }++ function doneBlock(node, step) {+ const r = step.result || {};+ const out = [];+ const def = types[node.type];+ if (node.type === 'preview' && r.mesh) {+ const viewer = h('model-viewer', {+ class: 'fw-viewer',+ src: meshSrc(r.mesh),+ poster: r.mesh.previewImageUrl || null,+ 'camera-controls': true,+ 'auto-rotate': true,+ 'shadow-intensity': '1',+ exposure: '1',+ 'interaction-prompt': 'none',+ 'touch-action': 'pan-y',+ alt: `3D preview from ${def?.label || 'the workflow'}`,+ });+ out.push(viewer);+ } else if (node.type === 'image' && r.image?.url) {+ out.push(h('img', { class: 'fw-thumb', src: r.image.url, alt: r.image.name || 'Uploaded photo', loading: 'lazy' }));+ } else if (r.mesh?.previewImageUrl && node.type === 'generate') {+ out.push(h('img', { class: 'fw-thumb', src: r.mesh.previewImageUrl, alt: 'Reference image the model was built from', loading: 'lazy' }));+ }+ const meta = [];+ if (step.reused) meta.push('Reused from the last run');+ else if (r.cached) meta.push('Served from cache');+ if (r.stats) meta.push(r.stats);+ if (r.saved) meta.push('Saved');+ if (meta.length) out.push(h('div', { class: 'fw-result-meta' }, icon(ICONS.check, 12), meta.join(' · ')));+ if (r.note) out.push(h('div', { class: 'fw-result-note' }, r.note));+ const links = [...(r.links || [])];+ if (r.download) {+ if (r.download.objectUrl) exportUrls.add(r.download.objectUrl);+ links.unshift({ label: `Download ${r.download.filename}`, href: r.download.href, download: r.download.filename });+ }+ if (links.length) {+ out.push(+ h(+ 'div',+ { class: 'fw-result-links' },+ links.map((l) =>+ h(+ 'a',+ {+ class: 'fw-btn is-sm is-ghost',+ href: l.href,+ download: l.download === true ? '' : l.download || null,+ target: !l.download && /^https?:/.test(l.href) ? '_blank' : null,+ rel: /^https?:/.test(l.href) ? 'noopener' : null,+ },+ l.download ? icon(ICONS.download, 13) : icon(ICONS.link, 13),+ l.label,+ ),+ ),+ ),+ );+ }+ return out;+ }++ function paintAll(nodeIds, surface) {+ for (const id of nodeIds) paint(id, surface);+ }++ /** Forget hosts for nodes that no longer exist. */+ function prune(liveIds) {+ for (const map of Object.values(hosts)) {+ for (const [id, el] of map) {+ if (liveIds.has(id)) continue;+ el.remove();+ map.delete(id);+ page.delete(id);+ }+ }+ }++ function resetPages() {+ page.clear();+ }++ return { hostFor, paint, paintAll, prune, resetPages };+}diff --git a/src/forge-workflows/runner.js b/src/forge-workflows/runner.jsnew file mode 100644index 000000000..e252ab5e3--- /dev/null+++ b/src/forge-workflows/runner.js@@ -0,0 +1,265 @@+// Forge Workflows: the run engine.+//+// Adapted from Modly (https://github.com/lightningpixel/modly), MIT License,+// Copyright (c) 2026 Lightning Pixel. The run model follows Modly's+// workflowRunStore.ts: steps execute one at a time in topological order, a For+// Each replays its downstream body once per item, the active step reports live+// progress, and a cancel flag stops the run between and during steps. Unlike+// Modly, a failed step does not pause the whole run: independent branches and+// the remaining loop items carry on, and the failure can be retried later+// without redoing the steps that already succeeded.+//+// The runner is network-free. Each node type's work is an executor function+// passed in by the caller (executors.js in the browser), which keeps the+// scheduling, reuse and cancel logic unit-testable.++import { buildPlan, incomingEdges, iteratorItems, downstreamOf, stepSignature, topoSort } from './graph.js';++/** Terminal step states. 'skipped' means an upstream step failed or was cancelled. */+export const STEP_STATES = ['pending', 'running', 'done', 'failed', 'cancelled', 'skipped'];++export class StepError extends Error {+ /**+ * @param {string} message shown to the user as-is+ * @param {{ code?: string, action?: {label:string, href:string}, actions?: Array<{label:string, href:string}>, retryAfter?: number }} [info]+ */+ constructor(message, info = {}) {+ super(message);+ this.name = 'StepError';+ this.code = info.code || 'failed';+ this.actions = info.actions || (info.action ? [info.action] : []);+ this.retryAfter = info.retryAfter || 0;+ }+}++function isAbort(err, signal) {+ return signal?.aborted || err?.name === 'AbortError' || err?.code === 'CANCELLED';+}++function key(nodeId, iter) {+ return `${nodeId}#${iter ?? ''}`;+}++/**+ * Aggregate a node's per-item step states into one card state.+ * A loop node with 3 items, 2 done and 1 failed reads as 'failed' with done=2.+ */+export function summarizeNode(steps) {+ const list = steps || [];+ const total = list.length;+ const count = (s) => list.filter((x) => x.status === s).length;+ const done = count('done');+ const failed = count('failed');+ const running = list.find((x) => x.status === 'running');+ let status = 'pending';+ if (running) status = 'running';+ else if (failed) status = 'failed';+ else if (total && done === total) status = 'done';+ else if (count('cancelled')) status = 'cancelled';+ else if (count('skipped') && count('skipped') + done === total) status = 'skipped';+ else if (done) status = 'partial';+ return { status, total, done, failed, running: running || null };+}++/**+ * Create a runner bound to a node registry and its executors.+ *+ * @param {object} opts+ * @param {object} opts.types the node registry (node-types.js)+ * @param {object} opts.executors { [type]: async (ctx) => ({ outputs, result }) }+ * @param {(state:object)=>void} [opts.onChange] called after every state change+ */+export function createRunner({ types, executors, onChange = () => {} }) {+ // Results that survive between runs, keyed by node and item, each tagged with+ // the signature of the work that produced it.+ const cache = new Map();+ let controller = null;+ let state = idleState();++ function idleState() {+ return { status: 'idle', steps: new Map(), startedAt: 0, finishedAt: 0, plan: null, activeKey: null };+ }++ function emit() {+ try {+ onChange(state);+ } catch (err) {+ // A rendering error must not break the run; surface it for debugging.+ console.error('[forge-workflows] state listener failed', err);+ }+ }++ function setStep(nodeId, iter, patch) {+ const k = key(nodeId, iter);+ const prev = state.steps.get(k) || { nodeId, iter, status: 'pending' };+ state.steps.set(k, { ...prev, ...patch });+ if (patch.status === 'running') state.activeKey = k;+ else if (state.activeKey === k && patch.status) state.activeKey = null;+ emit();+ }++ /** Every step for a node, in item order. */+ function stepsFor(nodeId) {+ return [...state.steps.values()].filter((s) => s.nodeId === nodeId).sort((a, b) => (a.iter ?? -1) - (b.iter ?? -1));+ }++ function sourceIter(plan, srcId, nodeId, iter) {+ if (iter == null) return null;+ const loop = plan.owner.get(nodeId);+ return srcId === loop || plan.owner.get(srcId) === loop ? iter : null;+ }++ function resolveInputs(workflow, plan, nodeId, iter) {+ const inputs = {};+ for (const e of incomingEdges(workflow, nodeId)) {+ const src = state.steps.get(key(e.from.node, sourceIter(plan, e.from.node, nodeId, iter)));+ if (!src || src.status !== 'done') return { blocked: src?.status || 'pending' };+ inputs[e.to.port] = src.outputs?.[e.from.port];+ }+ return { inputs };+ }++ async function runStep(workflow, plan, step, ctxBase, sigMemo) {+ const node = workflow.nodes.find((n) => n.id === step.nodeId);+ const def = types[node.type];+ const { nodeId, iter } = step;+ const sig = stepSignature(workflow, types, nodeId, iter, plan, sigMemo);++ const { inputs, blocked } = resolveInputs(workflow, plan, nodeId, iter);+ if (blocked) {+ setStep(nodeId, iter, { status: blocked === 'cancelled' ? 'cancelled' : 'skipped', error: null });+ return;+ }++ const hit = cache.get(key(nodeId, iter));+ if (hit && hit.sig === sig) {+ setStep(nodeId, iter, { status: 'done', outputs: hit.outputs, result: hit.result, reused: true, error: null, progress: null });+ return;+ }++ const startedAt = Date.now();+ setStep(nodeId, iter, { status: 'running', startedAt, progress: null, error: null, reused: false, outputs: null, result: null });++ if (def.iterator) {+ const item = iteratorItems(types, node)[iter];+ const outputs = { item };+ cache.set(key(nodeId, iter), { sig, outputs, result: null });+ setStep(nodeId, iter, { status: 'done', outputs, finishedAt: Date.now() });+ return;+ }++ const execute = executors[node.type];+ if (!execute) {+ setStep(nodeId, iter, { status: 'failed', error: { message: `No runner for ${def.label}.`, actions: [] } });+ return;+ }+ const signal = controller.signal;+ const progress = (info) => {+ if (signal.aborted) return;+ const cur = state.steps.get(key(nodeId, iter));+ if (cur?.status !== 'running') return;+ setStep(nodeId, iter, { progress: { ...info, at: Date.now() } });+ };+ try {+ const res = (await execute({ node, params: node.params || {}, inputs, iter, signal, progress, ...ctxBase })) || {};+ if (signal.aborted) throw new DOMException('Cancelled', 'AbortError');+ const outputs = res.outputs || {};+ cache.set(key(nodeId, iter), { sig, outputs, result: res.result || null });+ setStep(nodeId, iter, { status: 'done', outputs, result: res.result || null, finishedAt: Date.now(), progress: null });+ } catch (err) {+ if (isAbort(err, signal)) {+ setStep(nodeId, iter, { status: 'cancelled', progress: null, finishedAt: Date.now() });+ return;+ }+ setStep(nodeId, iter, {+ status: 'failed',+ progress: null,+ finishedAt: Date.now(),+ error: {+ message: err?.message || 'This step failed.',+ code: err?.code || 'failed',+ actions: Array.isArray(err?.actions) ? err.actions : [],+ retryAfter: err?.retryAfter || 0,+ },+ });+ }+ }++ /**+ * Run a workflow.+ * @param {object} workflow+ * @param {object} [opts]+ * @param {'reuse'|'fresh'} [opts.mode] 'reuse' keeps unchanged results from the last run+ * @param {string} [opts.fromNodeId] invalidate this node and everything after it first+ * @param {object} [opts.context] extra fields passed to every executor+ * @returns {Promise<object>} the final state+ */+ async function run(workflow, { mode = 'reuse', fromNodeId = null, context = {} } = {}) {+ if (state.status === 'running') throw new Error('A run is already in progress.');+ if (mode === 'fresh') cache.clear();+ if (fromNodeId) invalidate(workflow, fromNodeId);++ const { order, cycle } = topoSort(workflow);+ if (cycle.length) throw new Error('The workflow has a loop. Remove one of the links first.');+ const plan = buildPlan(workflow, types, { order });++ controller = new AbortController();+ state = { status: 'running', steps: new Map(), startedAt: Date.now(), finishedAt: 0, plan, activeKey: null };+ for (const s of plan.steps) state.steps.set(key(s.nodeId, s.iter), { nodeId: s.nodeId, iter: s.iter, status: 'pending' });+ emit();++ const sigMemo = new Map();+ const ctxBase = { workflow, ...context };+ for (const step of plan.steps) {+ if (controller.signal.aborted) {+ const cur = state.steps.get(key(step.nodeId, step.iter));+ if (cur.status === 'pending') setStep(step.nodeId, step.iter, { status: 'cancelled' });+ continue;+ }+ await runStep(workflow, plan, step, ctxBase, sigMemo);+ }++ const all = [...state.steps.values()];+ const anyFailed = all.some((s) => s.status === 'failed');+ const anyCancelled = all.some((s) => s.status === 'cancelled');+ state.status = controller.signal.aborted || (anyCancelled && !anyFailed) ? 'cancelled' : anyFailed ? 'failed' : 'done';+ state.finishedAt = Date.now();+ state.activeKey = null;+ controller = null;+ emit();+ return state;+ }++ /** Forget cached results for a node and everything downstream of it. */+ function invalidate(workflow, nodeId) {+ const ids = downstreamOf(workflow, nodeId);+ ids.add(nodeId);+ for (const k of [...cache.keys()]) if (ids.has(k.slice(0, k.lastIndexOf('#')))) cache.delete(k);+ }++ function cancel() {+ if (controller && !controller.signal.aborted) controller.abort();+ }++ /** Drop the visible run state (keeps reusable results). */+ function reset() {+ if (state.status === 'running') return;+ state = idleState();+ emit();+ }++ return {+ run,+ cancel,+ reset,+ invalidate,+ clearCache: () => cache.clear(),+ stepsFor,+ get state() {+ return state;+ },+ get cacheSize() {+ return cache.size;+ },+ };+}diff --git a/src/forge-workflows/templates.js b/src/forge-workflows/templates.jsnew file mode 100644index 000000000..118edd96a--- /dev/null+++ b/src/forge-workflows/templates.js@@ -0,0 +1,115 @@+// Forge Workflows: starter templates.+//+// Each template is a complete, runnable graph in the same JSON shape the editor+// saves and exports. Instantiate one with instantiateTemplate(), which gives every+// node and link a fresh id so two copies never collide.++import { WORKFLOW_KIND, WORKFLOW_VERSION, cloneWithFreshIds, defaultParams } from './graph.js';+import { NODE_TYPES } from './node-types.js';++function node(id, type, x, y, params = {}) {+ return { id, type, x, y, params: { ...defaultParams(NODE_TYPES[type]), ...params } };+}++function edge(id, from, fromPort, to, toPort) {+ return { id, from: { node: from, port: fromPort }, to: { node: to, port: toPort } };+}++function workflow(name, nodes, edges) {+ return { kind: WORKFLOW_KIND, version: WORKFLOW_VERSION, name, nodes, edges };+}++export const TEMPLATES = [+ {+ id: 'text-rig-export',+ title: 'Text to rigged character',+ description: 'Write a prompt, generate a model on the free engine, auto-rig it, preview it and download the GLB.',+ needs: 'A prompt',+ build: () =>+ workflow(+ 'Text to rigged character',+ [+ node('t_prompt', 'prompt', 40, 120, { text: 'a friendly cartoon robot standing upright, arms at its sides' }),+ node('t_gen', 'generate', 320, 120, { mode: 'text', engine: 'auto', tier: 'draft' }),+ node('t_rig', 'rig', 600, 120),+ node('t_prev', 'preview', 880, 40),+ node('t_exp', 'export', 880, 240, { format: 'glb', filename: 'rigged-character' }),+ ],+ [+ edge('t_e1', 't_prompt', 'text', 't_gen', 'prompt'),+ edge('t_e2', 't_gen', 'mesh', 't_rig', 'mesh'),+ edge('t_e3', 't_rig', 'mesh', 't_prev', 'mesh'),+ edge('t_e4', 't_rig', 'mesh', 't_exp', 'mesh'),+ ],+ ),+ },+ {+ id: 'image-preview',+ title: 'Photo to 3D',+ description: 'Upload one photo, turn it into a textured model and inspect it in the viewer.',+ needs: 'A photo',+ build: () =>+ workflow(+ 'Photo to 3D',+ [+ node('i_img', 'image', 40, 120),+ node('i_gen', 'generate', 320, 120, { mode: 'image', engine: 'auto', tier: 'draft' }),+ node('i_prev', 'preview', 600, 120),+ ],+ [edge('i_e1', 'i_img', 'image', 'i_gen', 'image'), edge('i_e2', 'i_gen', 'mesh', 'i_prev', 'mesh')],+ ),+ },+ {+ id: 'batch-save',+ title: 'Batch photos to library',+ description: 'Drop in several photos. For Each generates a model from every one and saves each to your library.',+ needs: 'Photos and a sign-in',+ build: () =>+ workflow(+ 'Batch photos to library',+ [+ node('b_each', 'forEach', 40, 120, { mode: 'image' }),+ node('b_gen', 'generate', 320, 120, { mode: 'image', engine: 'auto', tier: 'draft' }),+ node('b_prev', 'preview', 600, 40),+ node('b_save', 'save', 600, 240, { destination: 'library', name: 'Batch model', visibility: 'unlisted' }),+ ],+ [+ edge('b_e1', 'b_each', 'item', 'b_gen', 'image'),+ edge('b_e2', 'b_gen', 'mesh', 'b_prev', 'mesh'),+ edge('b_e3', 'b_gen', 'mesh', 'b_save', 'mesh'),+ ],+ ),+ },+ {+ id: 'image-gameready',+ title: 'Photo to game asset',+ description: 'Generate from a photo, clean the topology, retopologize and bake for a game engine, then download.',+ needs: 'A photo and $THREE',+ build: () =>+ workflow(+ 'Photo to game asset',+ [+ node('g_img', 'image', 40, 120),+ node('g_gen', 'generate', 300, 120, { mode: 'image', engine: 'auto', tier: 'draft' }),+ node('g_rem', 'remesh', 560, 120, { mode: 'triangle', operation: 'full', targetFaces: 50000 }),+ node('g_game', 'gameready', 820, 120, { topology: 'quad', polyBudget: 15000 }),+ node('g_prev', 'preview', 1080, 40),+ node('g_exp', 'export', 1080, 240, { format: 'glb', filename: 'game-asset' }),+ ],+ [+ edge('g_e1', 'g_img', 'image', 'g_gen', 'image'),+ edge('g_e2', 'g_gen', 'mesh', 'g_rem', 'mesh'),+ edge('g_e3', 'g_rem', 'mesh', 'g_game', 'mesh'),+ edge('g_e4', 'g_game', 'mesh', 'g_prev', 'mesh'),+ edge('g_e5', 'g_game', 'mesh', 'g_exp', 'mesh'),+ ],+ ),+ },+];++/** A fresh, independent copy of a template's graph. */+export function instantiateTemplate(id) {+ const t = TEMPLATES.find((x) => x.id === id);+ if (!t) throw new Error(`Unknown template "${id}"`);+ return cloneWithFreshIds(t.build());+}diff --git a/src/forge-workflows/ui.js b/src/forge-workflows/ui.jsnew file mode 100644index 000000000..665531992--- /dev/null+++ b/src/forge-workflows/ui.js@@ -0,0 +1,106 @@+// Forge Workflows: small DOM helpers shared by the editor, inspector and page.++/**+ * Build an element. `attrs` keys: class, text, html is not supported on purpose+ * (every string goes in as text), on:{event:fn}, dataset:{}, style:{}, and any+ * other key becomes an attribute (false/null/undefined skip it, true sets "").+ */+export function h(tag, attrs = {}, ...children) {+ const el = document.createElement(tag);+ for (const [k, v] of Object.entries(attrs || {})) {+ if (v === false || v === null || v === undefined) continue;+ if (k === 'class') el.className = v;+ else if (k === 'text') el.textContent = v;+ else if (k === 'on') for (const [ev, fn] of Object.entries(v)) el.addEventListener(ev, fn);+ else if (k === 'dataset') Object.assign(el.dataset, v);+ else if (k === 'style') Object.assign(el.style, v);+ else if (k === 'value') el.value = v;+ else if (k === 'checked') el.checked = Boolean(v);+ else el.setAttribute(k, v === true ? '' : String(v));+ }+ for (const c of children.flat()) {+ if (c === null || c === undefined || c === false) continue;+ el.append(c instanceof Node ? c : document.createTextNode(String(c)));+ }+ return el;+}++const SVG_NS = 'http://www.w3.org/2000/svg';+export function svg(tag, attrs = {}) {+ const el = document.createElementNS(SVG_NS, tag);+ for (const [k, v] of Object.entries(attrs)) if (v !== undefined && v !== null) el.setAttribute(k, String(v));+ return el;+}++/** Inline icon from a path list (24px grid, stroke = currentColor). */+export function icon(paths, size = 16) {+ const el = svg('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': 2, 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' });+ for (const d of paths) el.append(svg('path', { d }));+ return el;+}++export const ICONS = {+ play: ['M7 4v16l13-8z'],+ stop: ['M6 6h12v12H6z'],+ undo: ['M9 14 4 9l5-5', 'M4 9h10.5a5.5 5.5 0 0 1 0 11H11'],+ redo: ['m15 14 5-5-5-5', 'M20 9H9.5a5.5 5.5 0 0 0 0 11H13'],+ upload: ['M12 15V3', 'm7 8 5-5 5 5', 'M5 21h14'],+ download: ['M12 3v12', 'm7 10 5 5 5-5', 'M5 21h14'],+ grid: ['M3 3h7v7H3z', 'M14 3h7v7h-7z', 'M3 14h7v7H3z', 'M14 14h7v7h-7z'],+ fit: ['M3 8V3h5', 'M21 8V3h-5', 'M3 16v5h5', 'M21 16v5h-5'],+ plus: ['M12 5v14', 'M5 12h14'],+ minus: ['M5 12h14'],+ trash: ['M3 6h18', 'M8 6V4h8v2', 'M6 6l1 14h10l1-14'],+ retry: ['M3 12a9 9 0 1 0 3-6.7', 'M3 4v5h5'],+ check: ['M5 12l5 5L20 7'],+ x: ['M6 6l12 12', 'M18 6 6 18'],+ alert: ['M12 9v4', 'M12 17h.01', 'M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z'],+ chip: ['M9 3v2', 'M15 3v2', 'M9 19v2', 'M15 19v2', 'M3 9h2', 'M3 15h2', 'M19 9h2', 'M19 15h2', 'M6 5h12v14H6z'],+ link: ['M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7', 'M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7'],+};++/** Polite live-region announcer for screen readers. */+let liveRegion = null;+export function announce(message) {+ if (!liveRegion) {+ liveRegion = h('div', { class: 'fw-sr-only', 'aria-live': 'polite', role: 'status' });+ document.body.append(liveRegion);+ }+ liveRegion.textContent = '';+ requestAnimationFrame(() => {+ liveRegion.textContent = message;+ });+}++/** Transient toast in the corner. */+export function toast(message, { tone = 'info', timeout = 4200 } = {}) {+ let host = document.querySelector('.fw-toasts');+ if (!host) {+ host = h('div', { class: 'fw-toasts' });+ document.body.append(host);+ }+ const t = h('div', { class: `fw-toast is-${tone}`, role: tone === 'error' ? 'alert' : 'status' }, message);+ host.append(t);+ requestAnimationFrame(() => t.classList.add('is-in'));+ setTimeout(() => {+ t.classList.remove('is-in');+ t.addEventListener('transitionend', () => t.remove(), { once: true });+ setTimeout(() => t.remove(), 400);+ }, timeout);+}++export function formatSeconds(sec) {+ const s = Math.max(0, Math.round(sec));+ if (s < 60) return `${s}s`;+ return `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, '0')}s`;+}++export const isMac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);+export const MOD = isMac ? '⌘' : 'Ctrl';++/** True when keyboard focus is inside a text field, where shortcuts must not fire. */+export function typingInField(target) {+ const el = target instanceof Element ? target : null;+ if (!el) return false;+ return Boolean(el.closest('input, textarea, select, [contenteditable="true"]'));+}diff --git a/src/workbench/api.js b/src/workbench/api.jsnew file mode 100644index 000000000..3e2476c0e--- /dev/null+++ b/src/workbench/api.js@@ -0,0 +1,252 @@+// Workbench network client. Every call here is a real platform endpoint:+// /api/forge-upload presigned image upload+// /api/forge image or prompt to 3D, plus ?catalog, ?health, ?action=rig+// /api/forge-rembg background removal+// /api/forge-remesh server-side retopology+// /api/material-studio durable GLB checkpoint + AI material restyle+//+// Failures surface as WorkbenchError with a `kind` the UI branches on, and a+// message written for the person looking at the screen.++const POLL_INTERVAL_MS = 2500;+const MAX_POLL_MS = 12 * 60 * 1000;++export class WorkbenchError extends Error {+ constructor(message, { kind = 'failed', retryAfter = null, retryBackends = null, status = null } = {}) {+ super(message);+ this.kind = kind;+ this.retryAfter = retryAfter;+ this.retryBackends = retryBackends;+ this.status = status;+ }+}++// The same anonymous browser handle /forge uses, so creations made here land in+// the same per-browser gallery.+export const CLIENT_ID = (() => {+ const KEY = 'forge:cid';+ try {+ let id = localStorage.getItem(KEY);+ if (!id) {+ id = crypto.randomUUID();+ localStorage.setItem(KEY, id);+ }+ return id;+ } catch {+ return crypto.randomUUID();+ }+})();++const baseHeaders = (extra) => ({ 'x-forge-client': CLIENT_ID, ...extra });++const sleep = (ms, signal) =>+ new Promise((resolve, reject) => {+ const t = setTimeout(resolve, ms);+ signal?.addEventListener(+ 'abort',+ () => {+ clearTimeout(t);+ reject(new WorkbenchError('Cancelled.', { kind: 'cancelled' }));+ },+ { once: true },+ );+ });++async function request(url, init = {}) {+ let res;+ try {+ res = await fetch(url, init);+ } catch (err) {+ if (err?.name === 'AbortError') throw new WorkbenchError('Cancelled.', { kind: 'cancelled' });+ throw new WorkbenchError('No connection to three.ws. Check your network and try again.', { kind: 'network' });+ }+ const data = await res.json().catch(() => ({}));+ return { res, data };+}++/** Map an error response from any forge endpoint onto a WorkbenchError. */+function toError(res, data, fallback) {+ const message = data?.message || fallback;+ const code = data?.error;+ if (res.status === 429 || code === 'rate_limited') {+ const header = Number(res.headers.get('ratelimit-reset'));+ const secs = Number(data?.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : header > 0 ? Math.ceil(header) : 30;+ return new WorkbenchError(data?.message || `Rate limit reached. It resets in about ${secs}s.`, {+ kind: 'rate_limited',+ retryAfter: secs,+ status: 429,+ });+ }+ if (code === 'provider_busy' || code === 'free_lane_unavailable') {+ return new WorkbenchError(message, {+ kind: 'busy',+ retryAfter: Number(data?.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 15,+ retryBackends: Array.isArray(data?.retry_backends) ? data.retry_backends : null,+ status: res.status,+ });+ }+ if (res.status === 402 && code === 'three_hold_required') {+ return new WorkbenchError(+ data?.message || 'High quality is a $THREE holder perk. Switch to Draft or Standard, or unlock High on /forge.',+ { kind: 'hold_required', status: 402 },+ );+ }+ if (res.status === 422 && code === 'image_not_usable') return new WorkbenchError(message, { kind: 'not_usable', status: 422 });+ if (res.status === 403 && code === 'region_restricted') return new WorkbenchError(message, { kind: 'region', status: 403 });+ if (code === 'needs_key' || code === 'invalid_key') return new WorkbenchError(message, { kind: 'needs_key', status: res.status });+ if (res.status === 503 || code === 'unconfigured') return new WorkbenchError(message, { kind: 'unconfigured', status: res.status });+ if (res.status === 400) return new WorkbenchError(message, { kind: 'invalid', status: 400 });+ return new WorkbenchError(message, { status: res.status });+}++/** Upload an image file and return its public https URL. */+export async function uploadImage(file, { signal } = {}) {+ if (!/^image\/(png|jpe?g|webp)$/i.test(file.type)) {+ throw new WorkbenchError('Use a PNG, JPG or WebP image.', { kind: 'invalid' });+ }+ if (file.size > 8 * 1024 * 1024) throw new WorkbenchError('Images must be 8 MB or smaller.', { kind: 'invalid' });+ const { res, data } = await request('/api/forge-upload', {+ method: 'POST',+ signal,+ headers: baseHeaders({ 'content-type': 'application/json' }),+ body: JSON.stringify({ content_type: file.type, size_bytes: file.size }),+ });+ if (res.status === 503) {+ throw new WorkbenchError(+ data.error === 'storage_unavailable' ? 'Uploads are down right now. Try again shortly.' : 'Uploads are unavailable on this deployment.',+ { kind: 'unconfigured' },+ );+ }+ if (!res.ok || !data.upload_url || !data.public_url) throw toError(res, data, 'The upload could not start.');+ let put;+ try {+ put = await fetch(data.upload_url, { method: 'PUT', signal, headers: { 'content-type': file.type }, body: file });+ } catch {+ throw new WorkbenchError('Storage refused the upload. Try again shortly.', { kind: 'network' });+ }+ if (!put.ok) throw new WorkbenchError(`Storage rejected the file (${put.status}).`);+ return data.public_url;+}++/** Persist a GLB blob and return a durable https URL other tools can read. */+export async function uploadGlb(blob, { signal } = {}) {+ const { res, data } = await request('/api/material-studio?action=upload', {+ method: 'POST',+ signal,+ headers: { 'content-type': 'model/gltf-binary' },+ body: blob,+ });+ if (!res.ok || !data.url) throw toError(res, data, 'The model could not be saved for the next step.');+ return data.url;+}++export async function fetchCatalog() {+ const { res, data } = await request('/api/forge?catalog=1', { headers: baseHeaders() });+ if (!res.ok || !Array.isArray(data.backends)) throw toError(res, data, 'The engine catalog is unavailable.');+ return data;+}++export async function fetchHealth() {+ const { res, data } = await request('/api/forge?health=1', { headers: baseHeaders() });+ if (!res.ok || !data.backends) throw toError(res, data, 'Lane health is unavailable.');+ return data;+}++/**+ * Submit an image (or prompt) to 3D job and poll it to completion.+ * @returns {Promise<{glb_url:string, backend?:string, tier?:string}>}+ */+export async function generateMesh(body, { signal, onStatus } = {}) {+ const { res, data } = await request('/api/forge', {+ method: 'POST',+ signal,+ headers: baseHeaders({ 'content-type': 'application/json', 'x-witness': 'handled' }),+ body: JSON.stringify(body),+ });+ if (!res.ok || data.error) throw toError(res, data, `The generator returned ${res.status}.`);+ if (data.status === 'done' && data.glb_url) return data;+ if (!data.job_id) throw new WorkbenchError('The generator did not return a job.');+ onStatus?.({ status: data.status || 'queued', eta: data.eta_seconds, coldStart: data.cold_start });+ return pollForge(data.job_id, { signal, onStatus });+}++async function pollForge(jobId, { signal, onStatus }) {+ let deadline = performance.now() + MAX_POLL_MS;+ while (performance.now() < deadline) {+ await sleep(POLL_INTERVAL_MS, signal);+ const { res, data } = await request(`/api/forge?job=${encodeURIComponent(jobId)}`, { signal, headers: baseHeaders() });+ if (data.error === 'unconfigured') throw toError(res, data, 'This engine is not configured.');+ if (data.status === 'done' && data.glb_url) return data;+ if (data.status === 'failed') {+ throw new WorkbenchError(data.error || 'Generation failed.', {+ kind: data.retryable && data.retry_backends?.length ? 'lane_failed' : 'failed',+ retryBackends: data.retry_backends || null,+ });+ }+ // Waiting for a GPU is progress, not a stall: keep the budget for run time.+ if (data.status === 'queued') deadline = performance.now() + MAX_POLL_MS;+ if (data.status) onStatus?.({ status: data.status, eta: data.eta_seconds, coldStart: data.cold_start });+ }+ throw new WorkbenchError('Generation timed out after 12 minutes. Try a lower quality or another engine.', { kind: 'timeout' });+}++/** Submit-then-poll for the GCP tool lanes that share the { job_id } → ?job= contract. */+async function runToolJob(path, body, { signal, onStatus, label }) {+ const { res, data } = await request(path, {+ method: 'POST',+ signal,+ headers: baseHeaders({ 'content-type': 'application/json' }),+ body: JSON.stringify(body),+ });+ if (!res.ok || !data.job_id) throw toError(res, data, `${label} could not start.`);+ onStatus?.({ status: 'queued', eta: data.eta_seconds });+ const deadline = performance.now() + MAX_POLL_MS;+ while (performance.now() < deadline) {+ await sleep(POLL_INTERVAL_MS, signal);+ const poll = await request(`${path}?job=${encodeURIComponent(data.job_id)}`, { signal, headers: baseHeaders() });+ const s = poll.data;+ if (poll.res.status === 429) continue;+ if (s.status === 'done' && s.result_url) return s;+ if (s.status === 'failed') throw new WorkbenchError(s.error ? `${label} failed: ${s.error}` : `${label} failed.`);+ if (s.status) onStatus?.({ status: s.status });+ }+ throw new WorkbenchError(`${label} timed out.`, { kind: 'timeout' });+}++export function removeBackground(imageUrl, model, opts) {+ return runToolJob('/api/forge-rembg', { image_url: imageUrl, model }, { ...opts, label: 'Background removal' });+}++export function remesh(meshUrl, { mode, targetFaces }, opts) {+ return runToolJob(+ '/api/forge-remesh',+ { mesh_url: meshUrl, remesh_mode: mode, target_faces: targetFaces, output_format: 'glb' },+ { ...opts, label: 'Remesh' },+ );+}++export async function rig(glbUrl, { signal, onStatus } = {}) {+ const { res, data } = await request('/api/forge?action=rig', {+ method: 'POST',+ signal,+ headers: baseHeaders({ 'content-type': 'application/json' }),+ body: JSON.stringify({ glb_url: glbUrl }),+ });+ if (data.error === 'rig_unconfigured') {+ throw new WorkbenchError('Auto-rigging is not configured on this deployment.', { kind: 'unconfigured' });+ }+ if (!res.ok || !data.job_id) throw toError(res, data, 'Rigging could not start.');+ onStatus?.({ status: 'queued' });+ return pollForge(data.job_id, { signal, onStatus });+}++export async function restyle(glbUrl, instruction, { signal } = {}) {+ const { res, data } = await request('/api/material-studio?action=restyle', {+ method: 'POST',+ signal,+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ glb_url: glbUrl, instruction }),+ });+ if (!res.ok || !data.glbUrl) throw toError(res, data, 'The material restyle failed.');+ return data;+}diff --git a/src/workbench/graph-editor.js b/src/workbench/graph-editor.jsnew file mode 100644index 000000000..3e2669c9c--- /dev/null+++ b/src/workbench/graph-editor.js@@ -0,0 +1,334 @@+// Node-graph editor for Workbench workflows.+//+// Drag a node by its header, drag the canvas to pan, drag from an output dot+// to an input dot to wire them (or click one then the other, which also works+// from the keyboard). Clicking a wired input dot unplugs it. Delete removes the+// selected node. Every change is validated and reported through onChange.++import { NODE_TYPES, removeNode, validate } from './workflows.js';++const SVG_NS = 'http://www.w3.org/2000/svg';+const X_ICON =+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>';++function summary(node) {+ const p = node.params || {};+ switch (node.type) {+ case 'image':+ return 'Photo or prompt';+ case 'generate':+ return [p.backend === 'auto' || !p.backend ? 'Auto engine' : p.backend, p.tier, p.resolution && `${p.resolution} grid`]+ .filter(Boolean)+ .join(' · ');+ case 'rembg':+ return p.model;+ case 'restyle':+ return `"${String(p.instruction || '').slice(0, 26)}"`;+ case 'remesh':+ return `${p.mode} · ${Number(p.target_faces).toLocaleString()} faces`;+ case 'decimate':+ return `keep ${Math.round(Number(p.ratio) * 100)}%`;+ case 'smooth':+ return `${p.iterations} passes`;+ case 'rig':+ return 'Skeleton + skin weights';+ case 'output':+ return 'Viewport + history';+ default:+ return '';+ }+}++export function mountGraphEditor(graphEl, { onChange, onStatus }) {+ const layer = document.createElement('div');+ layer.className = 'wb-graph-layer';+ const svg = document.createElementNS(SVG_NS, 'svg');+ svg.classList.add('wires');+ svg.setAttribute('aria-hidden', 'true');+ layer.appendChild(svg);+ graphEl.appendChild(layer);+ graphEl.tabIndex = 0;++ let flow = null;+ let pan = { x: 0, y: 0 };+ let selected = null;+ let pendingFrom = null;+ let pendingPath = null;+ const nodeEls = new Map();++ const applyPan = () => (layer.style.transform = `translate(${pan.x}px, ${pan.y}px)`);++ function portPoint(nodeId, dir) {+ const el = nodeEls.get(nodeId)?.querySelector(`.port.${dir} .dot`);+ if (!el) return null;+ const r = el.getBoundingClientRect();+ const base = layer.getBoundingClientRect();+ return { x: r.left + r.width / 2 - base.left, y: r.top + r.height / 2 - base.top };+ }++ function curve(a, b) {+ const dx = Math.max(40, Math.abs(b.x - a.x) * 0.5);+ return `M${a.x},${a.y} C${a.x + dx},${a.y} ${b.x - dx},${b.y} ${b.x},${b.y}`;+ }++ function drawWires() {+ svg.querySelectorAll('path:not(.pending)').forEach((p) => p.remove());+ for (const e of flow.edges) {+ const a = portPoint(e.from, 'out');+ const b = portPoint(e.to, 'in');+ if (!a || !b) continue;+ const path = document.createElementNS(SVG_NS, 'path');+ path.setAttribute('d', curve(a, b));+ svg.insertBefore(path, svg.firstChild);+ }+ }++ function report() {+ const result = validate(flow);+ const bad = new Set(result.errors.map((e) => e.nodeId).filter(Boolean));+ for (const [id, el] of nodeEls) el.dataset.invalid = String(bad.has(id));+ onStatus?.(result);+ return result;+ }++ function commit() {+ report();+ onChange?.(flow);+ }++ function select(id) {+ selected = id;+ for (const [nid, el] of nodeEls) el.dataset.selected = String(nid === id);+ }++ function cancelPending() {+ pendingFrom = null;+ pendingPath?.remove();+ pendingPath = null;+ graphEl.classList.remove('is-wiring');+ }++ function connect(fromId, toId) {+ const a = flow.nodes.find((n) => n.id === fromId);+ const b = flow.nodes.find((n) => n.id === toId);+ if (!a || !b || a.id === b.id) return;+ const outT = NODE_TYPES[a.type].out;+ const inT = NODE_TYPES[b.type].in;+ if (outT !== inT) {+ onStatus?.({ ok: false, errors: [{ message: `${NODE_TYPES[a.type].label} outputs ${outT}; ${NODE_TYPES[b.type].label} takes ${inT}.` }] });+ return;+ }+ flow.edges = flow.edges.filter((e) => e.from !== a.id && e.to !== b.id);+ flow.edges.push({ from: a.id, to: b.id });+ drawWires();+ commit();+ }++ function startWire(nodeId, ev) {+ cancelPending();+ pendingFrom = nodeId;+ graphEl.classList.add('is-wiring');+ pendingPath = document.createElementNS(SVG_NS, 'path');+ pendingPath.classList.add('pending');+ svg.appendChild(pendingPath);+ if (!ev) return;+ const a = portPoint(nodeId, 'out');+ const base = layer.getBoundingClientRect();+ const startX = ev.clientX;+ const startY = ev.clientY;+ let moved = false;+ const move = (e) => {+ if (Math.hypot(e.clientX - startX, e.clientY - startY) > 4) moved = true;+ pendingPath.setAttribute('d', curve(a, { x: e.clientX - base.left, y: e.clientY - base.top }));+ };+ const up = (e) => {+ window.removeEventListener('pointermove', move);+ window.removeEventListener('pointerup', up);+ if (!moved) return; // a click: stay in click-to-connect mode+ const target = document.elementFromPoint(e.clientX, e.clientY)?.closest('.port.in .dot');+ const toId = target?.closest('.wb-gnode')?.dataset.id;+ const from = pendingFrom;+ cancelPending();+ if (toId) connect(from, toId);+ };+ window.addEventListener('pointermove', move);+ window.addEventListener('pointerup', up);+ }++ function dragNode(node, el, ev) {+ const sx = ev.clientX;+ const sy = ev.clientY;+ const ox = node.x;+ const oy = node.y;+ el.setPointerCapture(ev.pointerId);+ const move = (e) => {+ node.x = Math.round(ox + e.clientX - sx);+ node.y = Math.round(oy + e.clientY - sy);+ el.style.left = `${node.x}px`;+ el.style.top = `${node.y}px`;+ drawWires();+ };+ const up = () => {+ el.removeEventListener('pointermove', move);+ el.removeEventListener('pointerup', up);+ if (node.x !== ox || node.y !== oy) onChange?.(flow);+ };+ el.addEventListener('pointermove', move);+ el.addEventListener('pointerup', up);+ }++ function nodeElement(node) {+ const t = NODE_TYPES[node.type];+ const el = document.createElement('div');+ el.className = 'wb-gnode';+ el.dataset.id = node.id;+ el.dataset.type = node.type;+ el.style.left = `${node.x}px`;+ el.style.top = `${node.y}px`;+ el.setAttribute('role', 'group');+ el.setAttribute('aria-label', `${t.label} node`);++ const head = document.createElement('header');+ head.innerHTML = `<i aria-hidden="true"></i><span>${t.label}</span>`;+ if (!t.locked) {+ const del = document.createElement('button');+ del.type = 'button';+ del.innerHTML = X_ICON;+ del.setAttribute('aria-label', `Remove ${t.label}`);+ del.addEventListener('click', () => {+ removeNode(flow, node.id);+ render(flow);+ commit();+ });+ head.appendChild(del);+ }+ head.addEventListener('pointerdown', (ev) => {+ if (ev.target.closest('button')) return;+ select(node.id);+ dragNode(node, head, ev);+ });++ const ports = document.createElement('div');+ ports.className = 'ports';+ const inPort = document.createElement('div');+ inPort.className = 'port in';+ if (t.in) {+ const dot = document.createElement('button');+ dot.type = 'button';+ dot.className = 'dot';+ dot.setAttribute('aria-label', `${t.label} input (${t.in}). Click to connect or unplug.`);+ dot.addEventListener('click', () => {+ if (pendingFrom) {+ const from = pendingFrom;+ cancelPending();+ connect(from, node.id);+ return;+ }+ const before = flow.edges.length;+ flow.edges = flow.edges.filter((e) => e.to !== node.id);+ if (flow.edges.length !== before) {+ drawWires();+ commit();+ }+ });+ inPort.append(dot, t.in);+ }+ const outPort = document.createElement('div');+ outPort.className = 'port out';+ if (t.out) {+ const dot = document.createElement('button');+ dot.type = 'button';+ dot.className = 'dot';+ dot.setAttribute('aria-label', `${t.label} output (${t.out}). Drag or click, then pick an input.`);+ dot.addEventListener('pointerdown', (ev) => {+ ev.stopPropagation();+ startWire(node.id, ev);+ });+ dot.addEventListener('keydown', (ev) => {+ if (ev.key === 'Enter' || ev.key === ' ') {+ ev.preventDefault();+ startWire(node.id, null);+ onStatus?.({ ok: true, errors: [], hint: `Wiring from ${t.label}. Pick an input dot, or press Escape.` });+ }+ });+ outPort.append(t.out, dot);+ }+ ports.append(inPort, outPort);++ const sub = document.createElement('div');+ sub.className = 'sub';+ sub.textContent = summary(node);+ if (!t.locked && node.enabled === false) sub.textContent += ' · off';++ el.append(head, ports, sub);+ el.addEventListener('pointerdown', () => select(node.id));+ return el;+ }++ function render(next) {+ flow = next;+ cancelPending();+ for (const el of nodeEls.values()) el.remove();+ nodeEls.clear();+ for (const node of flow.nodes) {+ const el = nodeElement(node);+ nodeEls.set(node.id, el);+ layer.appendChild(el);+ }+ select(flow.nodes.some((n) => n.id === selected) ? selected : null);+ requestAnimationFrame(drawWires);+ report();+ }++ // Pan by dragging empty canvas.+ graphEl.addEventListener('pointerdown', (ev) => {+ if (ev.target !== graphEl && ev.target !== layer && ev.target !== svg) return;+ if (pendingFrom) cancelPending();+ select(null);+ const sx = ev.clientX - pan.x;+ const sy = ev.clientY - pan.y;+ graphEl.setPointerCapture(ev.pointerId);+ graphEl.classList.add('is-panning');+ const move = (e) => {+ pan = { x: e.clientX - sx, y: e.clientY - sy };+ applyPan();+ };+ const up = () => {+ graphEl.classList.remove('is-panning');+ graphEl.removeEventListener('pointermove', move);+ graphEl.removeEventListener('pointerup', up);+ };+ graphEl.addEventListener('pointermove', move);+ graphEl.addEventListener('pointerup', up);+ });++ graphEl.addEventListener('keydown', (ev) => {+ if (ev.key === 'Escape' && pendingFrom) {+ cancelPending();+ report();+ return;+ }+ if ((ev.key === 'Delete' || ev.key === 'Backspace') && selected && !ev.target.closest('input, textarea')) {+ const node = flow.nodes.find((n) => n.id === selected);+ if (!node || NODE_TYPES[node.type].locked) return;+ ev.preventDefault();+ removeNode(flow, selected);+ selected = null;+ render(flow);+ commit();+ }+ });++ const ro = new ResizeObserver(() => flow && drawWires());+ ro.observe(graphEl);++ return {+ render,+ resetView() {+ pan = { x: 0, y: 0 };+ applyPan();+ },+ redraw: () => flow && drawWires(),+ destroy: () => ro.disconnect(),+ };+}diff --git a/src/workbench/main.js b/src/workbench/main.jsnew file mode 100644index 000000000..98f7fab9d--- /dev/null+++ b/src/workbench/main.js@@ -0,0 +1,1615 @@+// Workbench controller: wires the viewport, the workflow model, the graph+// editor and the platform API into the four rail views (Generate, Workflows,+// Extensions, Settings). Everything persistent lives in localStorage under+// the wb: prefix; everything remote goes through ./api.js.++import { mountViewport } from './viewport.js';+import { mountGraphEditor } from './graph-editor.js';+import { runWorkflow } from './runner.js';+import { countScene, decimateScene, smoothScene } from './mesh-tools.js';+import { CLIENT_ID, fetchCatalog, fetchHealth, uploadImage } from './api.js';+import {+ NODE_TYPES,+ PALETTE,+ TEMPLATES,+ duplicateWorkflow,+ insertNode,+ loadActiveId,+ loadWorkflows,+ resetWorkflows,+ saveActiveId,+ saveWorkflows,+ tidy,+ validate,+} from './workflows.js';++const $ = (id) => document.getElementById(id);+const VIEWS = ['generate', 'workflows', 'extensions', 'settings'];+const HISTORY_KEY = 'wb:history';+const HISTORY_MAX = 30;+const LANES_OFF_KEY = 'wb:lanes-off';+const SETTINGS_KEY = 'wb:settings';+const PROMPT_MAX = 1000;++const ICONS = {+ chevron: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m18 15-6-6-6 6"/></svg>',+ image: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-5-5L5 21"/></svg>',+ close: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>',+ dice: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="3"/><circle cx="8" cy="8" r="1.2" fill="currentColor"/><circle cx="16" cy="16" r="1.2" fill="currentColor"/><circle cx="12" cy="12" r="1.2" fill="currentColor"/></svg>',+ plus: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>',+};++// ── storage ────────────────────────────────────────────────────++function readJSON(key, fallback) {+ try {+ const v = JSON.parse(localStorage.getItem(key) || 'null');+ return v ?? fallback;+ } catch {+ return fallback;+ }+}++function writeJSON(key, value) {+ try {+ localStorage.setItem(key, JSON.stringify(value));+ } catch {+ // Storage full or blocked: this session keeps working from memory.+ }+}++// ── state ──────────────────────────────────────────────────────++const app = $('wb-app');+let vp = null;+let graph = null;+let flows = loadWorkflows();+let activeId = loadActiveId(flows);+let editingId = activeId;+let catalog = null;+let health = null;+let lanesOff = new Set(readJSON(LANES_OFF_KEY, []));+const settings = { grid: true, env: true, spin: false, ...readJSON(SETTINGS_KEY, {}) };+let recent = readJSON(HISTORY_KEY, []);++// The image waiting in the Image node. Uploading starts the moment it is+// dropped so the run does not wait for it.+let source = { file: null, preview: null, url: null, upload: null, error: null };+let promptText = '';++// What the viewport currently shows, so "Copy GLB link" only offers a URL that+// matches the pixels. editDepth tracks undo-able edits since the last save.+let current = { url: null, name: 'model' };+let editDepth = 0;+let hasModel = false;+let run = null;++const activeFlow = () => flows.find((f) => f.id === activeId) || flows[0];+const editingFlow = () => flows.find((f) => f.id === editingId) || activeFlow();++function persistFlows() {+ saveWorkflows(flows);+}++// ── small DOM helpers ──────────────────────────────────────────++function h(tag, props = {}, ...children) {+ const node = document.createElement(tag);+ for (const [k, v] of Object.entries(props)) {+ if (v == null || v === false) continue;+ if (k === 'class') node.className = v;+ else if (k === 'text') node.textContent = v;+ else if (k === 'html') node.innerHTML = v;+ else if (k.startsWith('on')) node.addEventListener(k.slice(2), v);+ else if (k === 'dataset') Object.assign(node.dataset, v);+ else node.setAttribute(k, v === true ? '' : v);+ }+ for (const c of children.flat()) if (c != null && c !== false) node.append(c);+ return node;+}++function timeAgo(ts) {+ const s = Math.max(1, Math.round((Date.now() - ts) / 1000));+ if (s < 60) return `${s}s ago`;+ const m = Math.round(s / 60);+ if (m < 60) return `${m}m ago`;+ const hr = Math.round(m / 60);+ if (hr < 48) return `${hr}h ago`;+ return new Date(ts).toLocaleDateString();+}++function clock(ms) {+ const s = Math.floor(ms / 1000);+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;+}++function download(blob, filename) {+ const url = URL.createObjectURL(blob);+ const a = h('a', { href: url, download: filename });+ document.body.append(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(url), 4000);+}++const safeName = (s) =>+ String(s || 'model')+ .replace(/\.[a-z0-9]+$/i, '')+ .replace(/[^a-z0-9-_]+/gi, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 48) || 'model';++// ── toasts ─────────────────────────────────────────────────────++function toast(message, { tone = 'info', actions = [], timeout } = {}) {+ const box = $('wb-toasts');+ const el = h('div', { class: 'wb-toast', role: tone === 'err' ? 'alert' : 'status', dataset: { tone } }, h('p', { text: message }));+ const close = () => {+ el.dataset.leaving = 'true';+ setTimeout(() => el.remove(), 200);+ };+ for (const a of actions) {+ el.append(+ h('button', {+ type: 'button',+ text: a.label,+ onclick: () => {+ close();+ a.run();+ },+ }),+ );+ }+ el.append(h('button', { type: 'button', class: 'wb-toast-x', 'aria-label': 'Dismiss', html: ICONS.close, onclick: close }));+ box.append(el);+ while (box.children.length > 4) box.firstElementChild.remove();+ const ms = timeout ?? (tone === 'err' ? 12000 : actions.length ? 9000 : 4500);+ if (ms) setTimeout(close, ms);+ return close;+}++// ── views / routing ────────────────────────────────────────────++function setView(view, { push = true } = {}) {+ if (!VIEWS.includes(view)) view = 'generate';+ app.dataset.view = view;+ for (const b of document.querySelectorAll('.wb-rail-btn')) {+ if (b.dataset.nav === view) b.setAttribute('aria-current', 'page');+ else b.removeAttribute('aria-current');+ }+ closeMenus();+ if (push && location.hash.slice(1) !== view) syncHash(view);+ if (view === 'workflows') renderWorkflowsView();+ if (view === 'extensions' && !health) loadExtensions();+ if (view === 'settings') renderSettings();+}++function syncHash(view) {+ const url = view === 'generate' ? location.pathname + location.search : `#${view}`;+ window.history.replaceState(null, '', url);+}++// ── generate panel: node cards ─────────────────────────────────++function availableLanes() {+ if (!catalog) return [];+ return catalog.backends.filter(+ (b) => b.paths?.includes('image') && b.user_images && b.configured && !b.byok && !lanesOff.has(b.id),+ );+}++function renderFlowSelect() {+ const sel = $('wb-flow-select');+ sel.replaceChildren(...flows.map((f) => h('option', { value: f.id, text: f.name })));+ sel.value = activeFlow().id;+}++function paramControl(node, p) {+ const value = node.params[p.key];+ const id = `wb-p-${node.id}-${p.key}`;+ const set = (v) => {+ node.params[p.key] = v;+ persistFlows();+ };+ let control;+ switch (p.type) {+ case 'select':+ case 'lane': {+ const options =+ p.type === 'lane'+ ? [['auto', 'Auto (best available)'], ...availableLanes().map((b) => [b.id, b.label])]+ : p.options;+ if (p.type === 'lane' && catalog && value !== 'auto' && !options.some(([v]) => v === value)) {+ // The pinned engine was switched off or went away: fall back to routing.+ node.params[p.key] = 'auto';+ persistFlows();+ }+ if (p.type === 'lane' && !catalog && value !== 'auto') options.push([value, value]);+ control = h(+ 'select',+ { class: 'wb-select', id, onchange: (e) => set(e.target.value) },+ options.map(([v, label]) => h('option', { value: v, text: label })),+ );+ control.value = String(node.params[p.key] ?? '');+ break;+ }+ case 'number':+ control = h('input', {+ class: 'wb-input',+ id,+ type: 'number',+ inputmode: 'numeric',+ min: p.min,+ max: p.max,+ step: p.step,+ placeholder: p.placeholder,+ value: value === '' || value == null ? '' : String(value),+ onchange: (e) => {+ const raw = e.target.value.trim();+ if (raw === '') return set('');+ const n = Math.min(p.max, Math.max(p.min, Math.round(Number(raw))));+ e.target.value = String(n);+ set(n);+ },+ });+ break;+ case 'range': {+ const fmt = (v) => (p.format === 'percent' ? `${Math.round(Number(v) * 100)}%` : String(v));+ const out = h('output', { for: id, text: fmt(value) });+ const input = h('input', {+ type: 'range',+ id,+ min: p.min,+ max: p.max,+ step: p.step,+ value: String(value),+ oninput: (e) => (out.textContent = fmt(e.target.value)),+ onchange: (e) => set(Number(e.target.value)),+ });+ control = h('div', { class: 'wb-range' }, input, out);+ break;+ }+ case 'text':+ control = h('input', {+ class: 'wb-input',+ id,+ type: 'text',+ maxlength: p.maxLength,+ value: String(value ?? ''),+ onchange: (e) => set(e.target.value.trim()),+ });+ break;+ case 'seed': {+ const input = h('input', {+ class: 'wb-input',+ id,+ type: 'number',+ min: 0,+ max: 2147483647,+ placeholder: 'Random',+ value: value === '' || value == null ? '' : String(value),+ onchange: (e) => set(e.target.value.trim() === '' ? '' : Math.max(0, Math.floor(Number(e.target.value)))),+ });+ const dice = h('button', {+ type: 'button',+ class: 'wb-icon-btn',+ 'aria-label': 'Pick a random seed',+ title: 'Random seed',+ html: ICONS.dice,+ onclick: () => {+ const n = crypto.getRandomValues(new Uint32Array(1))[0] % 2147483647;+ input.value = String(n);+ set(n);+ },+ });+ control = h('div', { class: 'wb-row' }, input, dice);+ break;+ }+ default:+ return null;+ }+ const row = h('label', { class: 'wb-param', for: id }, h('span', { text: p.label, title: p.hint || p.label }), control);+ if (p.type === 'range' || p.type === 'seed') row.removeAttribute('for');+ return row;+}++function imageNodeBody() {+ const status = h('div', { class: 'wb-drop-status', id: 'wb-drop-status', hidden: true });+ const img = h('img', { alt: 'Reference image', hidden: !source.preview, src: source.preview || null });+ const input = h('input', {+ type: 'file',+ accept: 'image/png,image/jpeg,image/webp',+ 'aria-label': 'Choose a reference image',+ onchange: (e) => e.target.files[0] && setImage(e.target.files[0]),+ });+ const clear = h('button', {+ type: 'button',+ class: 'wb-icon-btn wb-drop-clear',+ 'aria-label': 'Remove image',+ title: 'Remove image',+ hidden: !source.preview,+ html: ICONS.close,+ onclick: (e) => {+ e.stopPropagation();+ clearImage();+ },+ });+ const empty = h(+ 'div',+ { class: 'wb-drop-empty', hidden: Boolean(source.preview) },+ h('span', { html: ICONS.image }),+ h('strong', { text: 'Drop image here' }),+ h('span', { text: 'or click to browse. Paste works too.' }),+ );+ const drop = h('div', { class: 'wb-drop', id: 'wb-drop' }, input, empty, img, clear, status);+ drop.addEventListener('dragover', (e) => {+ e.preventDefault();+ e.stopPropagation();+ drop.classList.add('is-over');+ });+ drop.addEventListener('dragleave', () => drop.classList.remove('is-over'));+ drop.addEventListener('drop', (e) => {+ e.preventDefault();+ e.stopPropagation();+ drop.classList.remove('is-over');+ const file = [...(e.dataTransfer?.files || [])].find((f) => f.type.startsWith('image/'));+ if (file) setImage(file);+ else toast('Drop a PNG, JPG or WebP image here. Models go on the viewport.', { tone: 'warn' });+ });+ const promptBox = h('textarea', {+ class: 'wb-input wb-prompt',+ id: 'wb-prompt',+ rows: 2,+ maxlength: PROMPT_MAX,+ placeholder: 'Or describe it: a weathered bronze dragon statue',+ 'aria-label': 'Describe the object instead of using an image',+ disabled: Boolean(source.file),+ oninput: (e) => (promptText = e.target.value),+ });+ promptBox.value = promptText;+ queueMicrotask(updateDropStatus);+ return [drop, promptBox];+}++function renderNodes() {+ const flow = activeFlow();+ const { ok, order, errors } = validate(flow);+ const box = $('wb-nodes');+ const nodes = ok ? order : flow.nodes;+ const cards = nodes.map((node) => {+ const t = NODE_TYPES[node.type];+ const off = !t.locked && node.enabled === false;+ const head = h('div', { class: 'wb-node-head' });+ if (!t.locked) {+ head.append(+ h(+ 'label',+ { class: 'wb-switch', title: off ? `Turn ${t.label} on` : `Skip ${t.label}` },+ h('input', {+ type: 'checkbox',+ checked: !off,+ 'aria-label': `Run ${t.label}`,+ onchange: (e) => {+ node.enabled = e.target.checked;+ card.dataset.off = String(!node.enabled);+ persistFlows();+ },+ }),+ h('span'),+ ),+ );+ }+ head.append(+ h(+ 'div',+ { class: 'wb-node-title' },+ h('strong', { text: t.label }),+ h(+ 'span',+ { class: 'wb-io' },+ h('span', { class: 'in', text: t.in || 'source' }),+ h('span', { class: 'arrow', text: '→' }),+ h('span', { class: 'out', text: t.out || 'scene' }),+ ),+ ),+ );+ const chev = h('button', {+ type: 'button',+ class: 'wb-chev',+ 'aria-label': `Collapse ${t.label}`,+ 'aria-expanded': String(!node.collapsed),+ html: ICONS.chevron,+ onclick: () => {+ node.collapsed = !node.collapsed;+ card.dataset.collapsed = String(node.collapsed);+ chev.setAttribute('aria-expanded', String(!node.collapsed));+ persistFlows();+ },+ });+ head.append(chev);+ const body = h('div', { class: 'wb-node-body' });+ if (node.type === 'image') body.append(...imageNodeBody());+ for (const p of t.params) {+ const row = paramControl(node, p);+ if (row) body.append(row);+ }+ if (!t.params.length && node.type !== 'image') body.append(h('p', { class: 'wb-hint', text: t.blurb }));+ const card = h(+ 'section',+ {+ class: 'wb-node',+ dataset: { id: node.id, type: node.type, off: String(off), collapsed: String(Boolean(node.collapsed)) },+ 'aria-label': t.label,+ },+ head,+ body,+ );+ return card;+ });+ if (!ok) {+ cards.unshift(+ h(+ 'div',+ { class: 'wb-flow-warning', role: 'alert' },+ h('strong', { text: 'This workflow cannot run yet' }),+ h('p', { text: errors[0].message }),+ h('button', {+ type: 'button',+ class: 'wb-btn',+ text: 'Fix in Workflows',+ onclick: () => {+ editingId = activeId;+ setView('workflows');+ },+ }),+ ),+ );+ }+ box.replaceChildren(...cards);+ updateRunButton();+}++// ── reference image ────────────────────────────────────────────++function setImage(file) {+ if (!/^image\/(png|jpe?g|webp)$/i.test(file.type)) {+ toast('Use a PNG, JPG or WebP image.', { tone: 'err' });+ return;+ }+ if (file.size > 8 * 1024 * 1024) {+ toast(`That image is ${(file.size / 1048576).toFixed(1)} MB. The limit is 8 MB.`, { tone: 'err' });+ return;+ }+ if (source.preview) URL.revokeObjectURL(source.preview);+ source = { file, preview: URL.createObjectURL(file), url: null, upload: null, error: null };+ startUpload();+ if (app.dataset.view !== 'generate') setView('generate');+ renderNodes();+}++function startUpload() {+ const file = source.file;+ source.error = null;+ source.upload = uploadImage(file)+ .then((url) => {+ if (source.file === file) source.url = url;+ return url;+ })+ .catch((err) => {+ if (source.file === file) source.error = err.message;+ throw err;+ })+ .finally(updateDropStatus);+ source.upload.catch(() => {});+ updateDropStatus();+}++function clearImage() {+ if (source.preview) URL.revokeObjectURL(source.preview);+ source = { file: null, preview: null, url: null, upload: null, error: null };+ renderNodes();+}++function updateDropStatus() {+ const el = $('wb-drop-status');+ if (!el) return;+ if (!source.file) {+ el.hidden = true;+ return;+ }+ el.hidden = false;+ if (source.error) {+ el.dataset.tone = 'err';+ el.textContent = `${source.error} It will retry when you generate.`;+ } else if (!source.url) {+ el.dataset.tone = '';+ el.textContent = `Uploading ${source.file.name}`;+ } else {+ el.dataset.tone = '';+ el.textContent = `${source.file.name} · ready`;+ }+}++async function ensureUploaded() {+ if (source.url) return source.url;+ try {+ return await source.upload;+ } catch {+ startUpload();+ return source.upload;+ }+}++// ── run ────────────────────────────────────────────────────────++function updateRunButton() {+ const btn = $('wb-run');+ const busy = Boolean(run);+ btn.dataset.busy = String(busy);+ $('wb-run-label').textContent = busy ? 'Cancel' : 'Generate 3D Model';+ btn.title = busy ? 'Stop this run' : 'Run the workflow (Ctrl+Enter)';+ btn.disabled = !busy && !validate(activeFlow()).ok;+ for (const id of ['wb-import-btn', 'wb-free', 'wb-flow-select']) $(id).disabled = busy;+ syncModelTools();+}++function setBusy(on, { title = 'Working', text = '', image = null } = {}) {+ $('wb-busy').hidden = !on;+ $('wb-busy-title').textContent = title;+ $('wb-busy-text').textContent = text;+ const img = $('wb-busy-img');+ img.hidden = !image;+ if (image && img.src !== image) img.src = image;+}++async function generate() {+ if (run) {+ run.controller.abort();+ return;+ }+ const flow = activeFlow();+ const check = validate(flow);+ if (!check.ok) {+ toast(check.errors[0].message, { tone: 'err', actions: [{ label: 'Fix in Workflows', run: () => setView('workflows') }] });+ return;+ }+ const text = promptText.trim();+ if (!source.file && !text) {+ toast('Add an image to the Image node, or describe the object in its prompt box.', { tone: 'warn' });+ $('wb-drop')?.querySelector('input')?.focus();+ return;+ }+ if (!source.file && text.length < 3) {+ toast('Describe the object in at least a few words.', { tone: 'warn' });+ return;+ }++ const steps = check.order;+ const total = steps.length;+ let finished = 0;+ const log = $('wb-run-log');+ const items = new Map(+ steps.map((n) => [n.id, h('li', { dataset: { state: 'pending' }, text: NODE_TYPES[n.type].label })]),+ );+ log.replaceChildren(...items.values());+ const progress = $('wb-run-progress');+ progress.style.width = '0%';++ const started = performance.now();+ const controller = new AbortController();+ let stepText = 'Starting';+ const tick = () => setBusy(true, { title: stepText, text: `${clock(performance.now() - started)} elapsed`, image: source.preview });+ run = { controller, timer: setInterval(tick, 1000) };+ updateRunButton();+ tick();++ const name = source.file ? source.file.name : text.slice(0, 48);+ try {+ let src;+ if (source.file) {+ stepText = 'Uploading the image';+ tick();+ src = { url: await ensureUploaded() };+ } else {+ src = { prompt: text };+ }+ const result = await runWorkflow(flow, {+ viewport: vp,+ source: src,+ signal: controller.signal,+ onStep: ({ nodeId, state, text: label }) => {+ const li = items.get(nodeId);+ if (li) {+ li.dataset.state = state;+ li.textContent = label;+ }+ if (state === 'done' || state === 'skipped') {+ finished += 1;+ progress.style.width = `${Math.round((finished / total) * 100)}%`;+ }+ if (state === 'active') {+ stepText = label;+ tick();+ }+ },+ });+ current = { url: result.glbUrl, name };+ editDepth = 0;+ if (settings.spin) setSpin(true);+ syncModelTools();+ const secs = Math.round((performance.now() - started) / 1000);+ const where = result.backend ? ` on ${laneLabel(result.backend)}` : '';+ toast(`Model ready in ${clock(secs * 1000)}${where}.`, {+ tone: 'ok',+ actions: [{ label: 'Download GLB', run: () => exportModel('glb') }],+ });+ if (result.glbUrl) await addHistory({ glbUrl: result.glbUrl, name, flow: flow.name, backend: result.backend, tier: result.tier });+ } catch (err) {+ const active = [...items.values()].find((li) => li.dataset.state === 'active');+ if (active) active.dataset.state = err.kind === 'cancelled' ? 'skipped' : 'error';+ runFailed(err, flow);+ } finally {+ clearInterval(run.timer);+ run = null;+ setBusy(false);+ updateRunButton();+ }+}++function laneLabel(id) {+ return catalog?.backends.find((b) => b.id === id)?.label || id;+}++function generateNode(flow) {+ return flow.nodes.find((n) => n.type === 'generate');+}++function runFailed(err, flow) {+ const again = { label: 'Try again', run: generate };+ switch (err.kind) {+ case 'cancelled':+ toast('Run cancelled.', { tone: 'warn' });+ return;+ case 'hold_required':+ toast(err.message, {+ tone: 'err',+ actions: [+ {+ label: 'Switch to Standard',+ run: () => {+ generateNode(flow).params.tier = 'standard';+ persistFlows();+ renderNodes();+ generate();+ },+ },+ ],+ });+ return;+ case 'busy':+ case 'rate_limited':+ toast(`${err.message}${err.retryAfter ? ` Try again in about ${err.retryAfter}s.` : ''}`, { tone: 'warn', actions: [again] });+ return;+ case 'lane_failed': {+ const next = err.retryBackends?.[0];+ toast(err.message, {+ tone: 'err',+ actions: next+ ? [+ {+ label: `Use ${laneLabel(next)}`,+ run: () => {+ generateNode(flow).params.backend = next;+ persistFlows();+ renderNodes();+ generate();+ },+ },+ ]+ : [again],+ });+ return;+ }+ case 'not_usable': {+ const hasRembg = flow.nodes.some((n) => n.type === 'rembg' && n.enabled !== false);+ toast(`${err.message} A clear photo of one object on a plain background works best.`, {+ tone: 'err',+ actions: hasRembg+ ? []+ : [+ {+ label: 'Add background removal',+ run: () => {+ insertNode(flow, 'rembg');+ persistFlows();+ renderNodes();+ },+ },+ ],+ });+ return;+ }+ case 'needs_key':+ toast(err.message, { tone: 'err', actions: [{ label: 'Open Forge', run: () => (location.href = '/forge') }] });+ return;+ case 'invalid':+ case 'region':+ case 'unconfigured':+ toast(err.message, { tone: 'err' });+ return;+ default:+ toast(err.message || 'The run failed.', { tone: 'err', actions: [again] });+ }+}++// ── history ───────────────────────────────────────────────────++async function thumbnail() {+ const png = await vp.screenshot();+ if (!png) return null;+ const bmp = await createImageBitmap(png);+ const size = 96;+ const c = document.createElement('canvas');+ c.width = c.height = size;+ const s = Math.min(bmp.width, bmp.height);+ c.getContext('2d').drawImage(bmp, (bmp.width - s) / 2, (bmp.height - s) / 2, s, s, 0, 0, size, size);+ bmp.close();+ return c.toDataURL('image/jpeg', 0.72);+}++async function addHistory(entry) {+ let thumb = null;+ try {+ thumb = await thumbnail();+ } catch {+ thumb = null;+ }+ const stats = vp.model ? countScene(vp.model) : null;+ recent = [{ id: crypto.randomUUID(), at: Date.now(), thumb, tris: stats?.tris ?? null, ...entry }, ...recent.filter((e) => e.glbUrl !== entry.glbUrl)].slice(+ 0,+ HISTORY_MAX,+ );+ writeJSON(HISTORY_KEY, recent);+ renderHistory();+}++function renderHistory() {+ const list = $('wb-history-list');+ $('wb-history-clear').disabled = !recent.length;+ if (!recent.length) {+ list.replaceChildren(+ h('li', { class: 'wb-history-empty', text: 'Finished models land here with a thumbnail. Each one is a hosted GLB, so you can reopen it any time from this browser.' }),+ );+ return;+ }+ list.replaceChildren(+ ...recent.map((e) =>+ h(+ 'li',+ {},+ h(+ 'button',+ { type: 'button', title: `Open ${e.name}`, onclick: () => openRemote(e.glbUrl, e.name) },+ e.thumb ? h('img', { src: e.thumb, alt: '' }) : h('img', { alt: '' }),+ h(+ 'span',+ {},+ h('strong', { text: e.name }),+ h('small', {+ text: [e.flow, e.tris ? `${Number(e.tris).toLocaleString()} tri` : null, timeAgo(e.at)].filter(Boolean).join(' · '),+ }),+ ),+ ),+ ),+ ),+ );+}++function toggleHistory(force) {+ const panel = $('wb-history');+ const open = force ?? panel.dataset.open !== 'true';+ panel.dataset.open = String(open);+ $('wb-history-btn').setAttribute('aria-pressed', String(open));+ if (open) {+ renderHistory();+ panel.querySelector('button')?.focus({ preventScroll: true });+ }+}++async function openRemote(url, name) {+ if (run) return;+ toggleHistory(false);+ setBusy(true, { title: 'Loading model', text: name });+ try {+ await vp.loadGLB(url);+ current = { url, name };+ editDepth = 0;+ syncModelTools();+ } catch (err) {+ toast(`That model could not be loaded: ${err.message}`, { tone: 'err' });+ } finally {+ setBusy(false);+ }+}++// ── viewport tools ─────────────────────────────────────────────++function syncModelTools() {+ const busy = Boolean(run);+ for (const id of ['wb-export-btn', 'wb-smooth-btn', 'wb-decimate-btn']) $(id).disabled = !hasModel || busy;+ const link = $('wb-copy-link');+ const linkable = Boolean(current.url) && editDepth === 0;+ link.disabled = !linkable;+ link.title = linkable ? current.url : 'Available for generated or reopened models with no unsaved edits';+ $('wb-empty').hidden = hasModel || busy;+}++function closeMenus(except) {+ for (const wrap of document.querySelectorAll('.wb-menu-wrap')) {+ const btn = wrap.querySelector(':scope > .wb-tool');+ const panel = wrap.querySelector('.wb-menu, .wb-popover');+ if (panel === except) continue;+ panel.dataset.open = 'false';+ btn.setAttribute('aria-expanded', 'false');+ }+}++function wireMenu(btnId, panelId, onOpen) {+ const btn = $(btnId);+ const panel = $(panelId);+ btn.addEventListener('click', (e) => {+ e.stopPropagation();+ const open = panel.dataset.open !== 'true';+ closeMenus(panel);+ panel.dataset.open = String(open);+ btn.setAttribute('aria-expanded', String(open));+ if (open) {+ onOpen?.();+ panel.querySelector('button:not(:disabled), input')?.focus();+ }+ });+ panel.addEventListener('click', (e) => e.stopPropagation());+ panel.addEventListener('keydown', (e) => {+ if (e.key === 'Escape') {+ closeMenus();+ btn.focus();+ return;+ }+ if (panel.classList.contains('wb-menu') && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {+ e.preventDefault();+ const items = [...panel.querySelectorAll('button:not(:disabled)')];+ const i = items.indexOf(document.activeElement);+ const next = items[(i + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length];+ next?.focus();+ }+ });+}++async function exportModel(format) {+ closeMenus();+ if (!vp.model) return;+ if (format === 'link') {+ try {+ await navigator.clipboard.writeText(current.url);+ toast('GLB link copied.', { tone: 'ok' });+ } catch {+ window.prompt('Copy the GLB link', current.url);+ }+ return;+ }+ try {+ const blob = await vp.exportAs(format);+ download(blob, `${safeName(current.name)}.${format}`);+ toast(`Saved ${safeName(current.name)}.${format} (${(blob.size / 1048576).toFixed(1)} MB).`, { tone: 'ok' });+ } catch (err) {+ toast(`Export failed: ${err.message}`, { tone: 'err' });+ }+}++async function applyMutation(label, op) {+ closeMenus();+ try {+ const result = await vp.mutate(op);+ editDepth += 1;+ syncModelTools();+ return result;+ } catch (err) {+ toast(`${label} failed: ${err.message}`, { tone: 'err' });+ return null;+ }+}++function updateDecimateEstimate() {+ const ratio = Number($('wb-decimate-range').value);+ $('wb-decimate-out').textContent = `${Math.round(ratio * 100)}%`;+ const stats = vp?.model ? countScene(vp.model) : null;+ $('wb-decimate-est').textContent = stats+ ? `About ${Math.round(stats.tris * ratio).toLocaleString()} of ${stats.tris.toLocaleString()} triangles. UV seams and borders are kept.`+ : 'Simplifies every mesh with edge collapse.';+}++function setMode(mode) {+ vp.setMode(mode);+ for (const b of document.querySelectorAll('.wb-strip-btn[data-mode]')) b.setAttribute('aria-pressed', String(b.dataset.mode === mode));+}++function setGrid(on) {+ vp.setGrid(on);+ $('wb-grid').setAttribute('aria-pressed', String(on));+}++function setEnv(on) {+ vp.setEnvironment(on);+ $('wb-env').setAttribute('aria-pressed', String(on));+}++function setSpin(on) {+ vp.setAutoRotate(on);+ $('wb-spin').setAttribute('aria-pressed', String(on));+}++function undo() {+ if (run || !vp.undo()) return;+ editDepth -= 1;+ syncModelTools();+}++function redo() {+ if (run || !vp.redo()) return;+ editDepth += 1;+ syncModelTools();+}++async function importModelFile(file) {+ if (run) return;+ setBusy(true, { title: 'Opening model', text: file.name });+ try {+ await vp.loadFile(file);+ current = { url: null, name: file.name };+ editDepth = 0;+ syncModelTools();+ } catch (err) {+ toast(`Could not open ${file.name}: ${err.message}`, { tone: 'err' });+ } finally {+ setBusy(false);+ }+}++const MODEL_EXT = /\.(glb|gltf|obj|stl|ply|fbx)$/i;++function handleDroppedFiles(files) {+ const list = [...files];+ const model = list.find((f) => MODEL_EXT.test(f.name));+ const image = list.find((f) => f.type.startsWith('image/'));+ if (model) importModelFile(model);+ else if (image) {+ setImage(image);+ toast('Image added to the Image node. Press Generate when ready.', { tone: 'ok' });+ } else toast('Drop a GLB, glTF, OBJ, STL, PLY or FBX model, or a PNG, JPG or WebP image.', { tone: 'warn' });+}++function wireViewport() {+ $('wb-undo').addEventListener('click', undo);+ $('wb-redo').addEventListener('click', redo);++ wireMenu('wb-import-btn', 'wb-import-menu');+ for (const b of $('wb-import-menu').querySelectorAll('[data-import]')) {+ b.addEventListener('click', () => {+ closeMenus();+ $(b.dataset.import === 'model' ? 'wb-model-input' : 'wb-image-input').click();+ });+ }+ $('wb-model-input').addEventListener('change', (e) => {+ const f = e.target.files[0];+ e.target.value = '';+ if (f) importModelFile(f);+ });+ $('wb-image-input').addEventListener('change', (e) => {+ const f = e.target.files[0];+ e.target.value = '';+ if (f) setImage(f);+ });++ wireMenu('wb-export-btn', 'wb-export-menu');+ for (const b of $('wb-export-menu').querySelectorAll('[data-export]')) b.addEventListener('click', () => exportModel(b.dataset.export));++ wireMenu('wb-smooth-btn', 'wb-smooth-pop');+ $('wb-smooth-range').addEventListener('input', (e) => ($('wb-smooth-out').textContent = e.target.value));+ $('wb-smooth-apply').addEventListener('click', async () => {+ const passes = Number($('wb-smooth-range').value);+ const ok = await applyMutation('Smoothing', (m) => smoothScene(m, passes));+ if (ok !== null) toast(`Smoothed with ${passes} pass${passes === 1 ? '' : 'es'}. Ctrl+Z to undo.`, { tone: 'ok' });+ });++ wireMenu('wb-decimate-btn', 'wb-decimate-pop', updateDecimateEstimate);+ $('wb-decimate-range').addEventListener('input', updateDecimateEstimate);+ $('wb-decimate-apply').addEventListener('click', async () => {+ const ratio = Number($('wb-decimate-range').value);+ const res = await applyMutation('Decimation', (m) => decimateScene(m, ratio));+ if (res) toast(`Decimated ${res.before.tris.toLocaleString()} to ${res.after.tris.toLocaleString()} triangles. Ctrl+Z to undo.`, { tone: 'ok' });+ });++ $('wb-free').addEventListener('click', () => {+ const before = performance.memory?.usedJSHeapSize;+ vp.free();+ current = { url: null, name: 'model' };+ editDepth = 0;+ syncModelTools();+ const note = before ? ` Heap was ${Math.round(before / 1048576)} MB.` : '';+ toast(`Model unloaded and its GPU buffers released.${note}`, { tone: 'ok' });+ });++ for (const b of document.querySelectorAll('.wb-strip-btn[data-mode]')) b.addEventListener('click', () => setMode(b.dataset.mode));+ $('wb-grid').addEventListener('click', () => setGrid(!vp.gridVisible));+ $('wb-env').addEventListener('click', () => setEnv(!vp.environmentOn));+ $('wb-spin').addEventListener('click', () => setSpin(!vp.autoRotate));+ $('wb-history-btn').addEventListener('click', () => toggleHistory());+ $('wb-history-clear').addEventListener('click', clearHistory);+ $('wb-frame').addEventListener('click', () => vp.frame());+ $('wb-shot').addEventListener('click', screenshot);++ document.addEventListener('click', () => closeMenus());++ // Drag and drop anywhere on the viewport.+ const stage = $('wb-stage');+ const veil = $('wb-dropveil');+ let depth = 0;+ stage.addEventListener('dragenter', (e) => {+ if (!e.dataTransfer?.types?.includes('Files')) return;+ depth += 1;+ veil.dataset.on = 'true';+ });+ stage.addEventListener('dragleave', () => {+ depth = Math.max(0, depth - 1);+ if (!depth) veil.dataset.on = 'false';+ });+ stage.addEventListener('dragover', (e) => e.preventDefault());+ stage.addEventListener('drop', (e) => {+ e.preventDefault();+ depth = 0;+ veil.dataset.on = 'false';+ if (e.dataTransfer?.files?.length) handleDroppedFiles(e.dataTransfer.files);+ });+}++async function screenshot() {+ if (!vp.model) {+ toast('Load or generate a model first.', { tone: 'warn' });+ return;+ }+ const blob = await vp.screenshot();+ if (blob) download(blob, `${safeName(current.name)}.png`);+}++function clearHistory() {+ const prev = recent;+ recent = [];+ writeJSON(HISTORY_KEY, recent);+ renderHistory();+ toast('History cleared.', {+ actions: [+ {+ label: 'Undo',+ run: () => {+ recent = prev;+ writeJSON(HISTORY_KEY, recent);+ renderHistory();+ },+ },+ ],+ });+}++// ── memory meter ───────────────────────────────────────────────++function startMeter() {+ const mem = performance.memory;+ if (!mem || !mem.jsHeapSizeLimit) return;+ const meter = $('wb-meter');+ meter.hidden = false;+ const update = () => {+ const used = performance.memory.usedJSHeapSize;+ const limit = performance.memory.jsHeapSizeLimit;+ $('wb-meter-fill').style.width = `${Math.min(100, (used / limit) * 100).toFixed(1)}%`;+ $('wb-meter-text').textContent = used > 1073741824 ? `${(used / 1073741824).toFixed(2)} GB` : `${Math.round(used / 1048576)} MB`;+ meter.title = `JavaScript heap: ${Math.round(used / 1048576)} MB of ${Math.round(limit / 1048576)} MB available to this tab`;+ };+ update();+ setInterval(update, 2000);+}++// ── workflows view ─────────────────────────────────────────────++function setFlowStatus(result) {+ const el = $('wb-flow-status');+ if (result.hint) {+ el.dataset.tone = '';+ el.textContent = result.hint;+ return;+ }+ el.dataset.tone = result.ok ? 'ok' : 'err';+ el.textContent = result.ok ? `Ready to run · ${result.order.length} steps` : result.errors[0]?.message || 'Invalid workflow';+ $('wb-flow-use').disabled = !result.ok;+}++function renderFlowList() {+ $('wb-flow-list').replaceChildren(+ ...flows.map((f) => {+ const { ok, order } = validate(f);+ const item = h(+ 'button',+ {+ type: 'button',+ class: 'wb-flow-item',+ role: 'option',+ 'aria-selected': String(f.id === editingId),+ 'aria-current': String(f.id === editingId),+ onclick: () => {+ editingId = f.id;+ graph.resetView();+ renderWorkflowsView();+ },+ },+ h('strong', { text: f.name }),+ h('small', { text: ok ? `${order.length} steps${f.id === activeId ? ' · in use' : ''}` : 'Needs fixing' }),+ );+ return item;+ }),+ );+}++function renderWorkflowsView() {+ const flow = editingFlow();+ editingId = flow.id;+ $('wb-flow-name').value = flow.name;+ $('wb-flow-del').disabled = flows.length < 2;+ renderFlowList();+ graph.render(flow);+}++function onFlowsChanged() {+ persistFlows();+ renderFlowList();+ renderFlowSelect();+ if (editingId === activeId) renderNodes();+}++function wireWorkflows() {+ graph = mountGraphEditor($('wb-graph'), { onChange: onFlowsChanged, onStatus: setFlowStatus });++ $('wb-flow-name').addEventListener('input', (e) => {+ editingFlow().name = e.target.value.trim() || 'Untitled workflow';+ onFlowsChanged();+ });+ $('wb-flow-new').addEventListener('click', () => {+ const flow = duplicateWorkflow(TEMPLATES[0], 'Untitled workflow');+ flows.push(flow);+ editingId = flow.id;+ persistFlows();+ renderWorkflowsView();+ renderFlowSelect();+ $('wb-flow-name').select();+ });+ $('wb-flow-dup').addEventListener('click', () => {+ const src = editingFlow();+ const flow = duplicateWorkflow(src, `${src.name} copy`);+ flows.splice(flows.indexOf(src) + 1, 0, flow);+ editingId = flow.id;+ persistFlows();+ renderWorkflowsView();+ renderFlowSelect();+ });+ $('wb-flow-tidy').addEventListener('click', () => {+ tidy(editingFlow());+ graph.resetView();+ graph.render(editingFlow());+ persistFlows();+ });+ $('wb-flow-del').addEventListener('click', () => {+ if (flows.length < 2) return;+ const flow = editingFlow();+ const index = flows.indexOf(flow);+ flows.splice(index, 1);+ const wasActive = activeId === flow.id;+ if (wasActive) {+ activeId = flows[0].id;+ saveActiveId(activeId);+ }+ editingId = flows[Math.min(index, flows.length - 1)].id;+ persistFlows();+ renderWorkflowsView();+ renderFlowSelect();+ renderNodes();+ toast(`Deleted "${flow.name}".`, {+ actions: [+ {+ label: 'Undo',+ run: () => {+ flows.splice(index, 0, flow);+ if (wasActive) {+ activeId = flow.id;+ saveActiveId(activeId);+ }+ editingId = flow.id;+ persistFlows();+ renderFlowSelect();+ renderNodes();+ if (app.dataset.view === 'workflows') renderWorkflowsView();+ },+ },+ ],+ });+ });+ $('wb-flow-use').addEventListener('click', () => {+ activeId = editingId;+ saveActiveId(activeId);+ renderFlowSelect();+ renderNodes();+ setView('generate');+ });++ const palette = $('wb-palette');+ for (const type of PALETTE) {+ const t = NODE_TYPES[type];+ palette.append(+ h('button', {+ type: 'button',+ class: 'wb-btn',+ title: t.blurb,+ html: ICONS.plus,+ onclick: () => {+ insertNode(editingFlow(), type);+ graph.render(editingFlow());+ onFlowsChanged();+ },+ }),+ );+ palette.lastElementChild.append(t.label);+ }+}++// ── extensions view ────────────────────────────────────────────++const HEALTH_TAG = {+ ok: ['Online', 'ok'],+ byok: ['Your API key', 'warn'],+ unconfigured: ['Not configured', 'err'],+ degraded: ['Degraded', 'warn'],+ down: ['Down', 'err'],+};++function laneCard(b) {+ const hs = health?.backends?.[b.id];+ const [hLabel, hTone] = HEALTH_TAG[hs?.status] || (hs ? [hs.status, 'warn'] : ['Status unknown', '']);+ const eta = b.estimates?.image?.find((e) => e.tier === 'standard')?.eta_seconds;+ const tags = [h('span', { class: 'wb-tag', dataset: { tone: hTone }, title: hs?.message || '', text: hLabel })];+ if (b.free) tags.push(h('span', { class: 'wb-tag', dataset: { tone: 'accent' }, text: 'Free' }));+ for (const p of b.paths || []) tags.push(h('span', { class: 'wb-tag', text: p === 'image' ? 'Image to 3D' : p === 'sketch' ? 'Sketch' : 'Geometry' }));+ if (b.poly_control) tags.push(h('span', { class: 'wb-tag', text: 'Face budget' }));+ if (hs?.latency_ms) tags.push(h('span', { class: 'wb-tag', text: `${hs.latency_ms} ms` }));++ const eligible = b.paths?.includes('image') && b.user_images && b.configured && !b.byok;+ let foot;+ if (eligible) {+ foot = h(+ 'label',+ {},+ 'Show in Engine picker',+ h(+ 'span',+ { class: 'wb-switch' },+ h('input', {+ type: 'checkbox',+ checked: !lanesOff.has(b.id),+ 'aria-label': `Show ${b.label} in the Engine picker`,+ onchange: (e) => {+ if (e.target.checked) lanesOff.delete(b.id);+ else lanesOff.add(b.id);+ writeJSON(LANES_OFF_KEY, [...lanesOff]);+ renderNodes();+ },+ }),+ h('span'),+ ),+ );+ } else if (b.byok) {+ foot = h('a', { href: '/forge', text: 'Add your key on Forge' });+ } else if (!b.configured) {+ foot = h('span', { text: 'Not available on this deployment' });+ } else if (!b.user_images) {+ foot = h('span', { text: 'Used by Auto for text prompts' });+ } else {+ foot = h('span', { text: 'Not an image lane' });+ }++ return h(+ 'article',+ { class: 'wb-ext' },+ h('header', {}, h('div', {}, h('h3', { text: b.label }), h('small', { text: b.vendor || '' }))),+ h('p', { text: b.blurb || '' }),+ h('div', { class: 'wb-tags' }, tags),+ h('footer', {}, eta ? h('span', { text: `About ${eta}s at Standard` }) : null, foot),+ );+}++const TOOL_KIND = {+ rembg: 'GPU worker',+ restyle: 'AI materials',+ remesh: 'GPU worker',+ rig: 'GPU worker',+ decimate: 'In browser',+ smooth: 'In browser',+};++function toolCard(type) {+ const t = NODE_TYPES[type];+ return h(+ 'article',+ { class: 'wb-ext' },+ h('header', {}, h('div', {}, h('h3', { text: t.label }), h('small', { text: TOOL_KIND[type] }))),+ h('p', { text: t.blurb }),+ h(+ 'div',+ { class: 'wb-tags' },+ h('span', { class: 'wb-tag', dataset: { tone: 'accent' }, text: `${t.in} → ${t.out}` }),+ t.params.length ? h('span', { class: 'wb-tag', text: `${t.params.length} setting${t.params.length > 1 ? 's' : ''}` }) : null,+ ),+ h(+ 'footer',+ {},+ h('button', {+ type: 'button',+ class: 'wb-btn',+ text: 'Add to current workflow',+ onclick: () => {+ const flow = activeFlow();+ insertNode(flow, type);+ persistFlows();+ renderNodes();+ toast(`${t.label} added to "${flow.name}".`, {+ tone: 'ok',+ actions: [+ {+ label: 'View',+ run: () => {+ editingId = flow.id;+ setView('workflows');+ },+ },+ ],+ });+ },+ }),+ ),+ );+}++async function loadExtensions() {+ const grid = $('wb-ext-lanes');+ grid.setAttribute('aria-busy', 'true');+ if (!catalog) grid.replaceChildren(...Array.from({ length: 6 }, () => h('div', { class: 'wb-skel' })));+ $('wb-ext-tools').replaceChildren(...PALETTE.map(toolCard));+ const [cat, hl] = await Promise.allSettled([fetchCatalog(), fetchHealth()]);+ if (cat.status === 'fulfilled') catalog = cat.value;+ if (hl.status === 'fulfilled') health = hl.value;+ grid.setAttribute('aria-busy', 'false');+ if (!catalog) {+ grid.replaceChildren(+ h(+ 'div',+ { class: 'wb-ext-error', role: 'alert' },+ h('strong', { text: 'The engine list did not load' }),+ h('p', { text: cat.reason?.message || 'The platform did not answer.' }),+ h('button', { type: 'button', class: 'wb-btn', text: 'Try again', onclick: loadExtensions }),+ ),+ );+ return;+ }+ const rank = (b) => (b.configured && !b.byok ? 0 : b.byok ? 1 : 2);+ grid.replaceChildren(...[...catalog.backends].sort((a, b) => rank(a) - rank(b)).map(laneCard));+ renderNodes();+}++// ── settings view ──────────────────────────────────────────────++function apiSnippet() {+ const origin = location.origin;+ const gen = generateNode(activeFlow())?.params || {};+ const body = { path: 'image', tier: gen.tier || 'standard', image_urls: ['$PUBLIC_URL'] };+ if (gen.backend && gen.backend !== 'auto') body.backend = gen.backend;+ if (gen.texture_size) body.texture_size = Number(gen.texture_size);+ if (gen.target_polycount) body.target_polycount = Number(gen.target_polycount);+ return [+ '# 1. Ask for an upload slot, then PUT the image to upload_url',+ `curl -s ${origin}/api/forge-upload -H 'content-type: application/json' \\`,+ ` -d '{"content_type":"image/png","size_bytes":'$(wc -c < photo.png)'}'`,+ `curl -X PUT "$UPLOAD_URL" -H 'content-type: image/png' --data-binary @photo.png`,+ '',+ `# 2. Submit public_url with this workflow's Generate settings`,+ `curl -s ${origin}/api/forge -H 'content-type: application/json' \\`,+ ` -d '${JSON.stringify(body).replace('"$PUBLIC_URL"', `"'"$PUBLIC_URL"'"`)}'`,+ '',+ '# 3. Poll every few seconds until status is "done", then fetch glb_url',+ `curl -s "${origin}/api/forge?job=$JOB_ID"`,+ ].join('\n');+}++function renderSettings() {+ for (const sel of document.querySelectorAll('[data-setting]')) sel.value = settings[sel.dataset.setting] ? '1' : '0';+ $('wb-theme-select').value = window.threeTheme?.get() || 'dark';+ $('wb-theme-select').disabled = window.threeTheme ? !window.threeTheme.supportsLight() : true;+ $('wb-client-id').value = CLIENT_ID;+ $('wb-api-snippet').textContent = apiSnippet();+}++function wireSettings() {+ for (const sel of document.querySelectorAll('[data-setting]')) {+ sel.addEventListener('change', () => {+ const key = sel.dataset.setting;+ settings[key] = sel.value === '1';+ writeJSON(SETTINGS_KEY, settings);+ if (key === 'grid') setGrid(settings.grid);+ if (key === 'env') setEnv(settings.env);+ });+ }+ $('wb-theme-select').addEventListener('change', (e) => window.threeTheme?.set(e.target.value));+ $('wb-clear-history').addEventListener('click', clearHistory);+ $('wb-reset-flows').addEventListener('click', () => {+ const prev = { flows, activeId };+ flows = resetWorkflows();+ activeId = flows[0].id;+ editingId = activeId;+ renderFlowSelect();+ renderNodes();+ toast('Default workflows restored.', {+ actions: [+ {+ label: 'Undo',+ run: () => {+ flows = prev.flows;+ activeId = prev.activeId;+ editingId = activeId;+ persistFlows();+ saveActiveId(activeId);+ renderFlowSelect();+ renderNodes();+ },+ },+ ],+ });+ });+ $('wb-copy-snippet').addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText($('wb-api-snippet').textContent);+ toast('Copied.', { tone: 'ok' });+ } catch {+ toast('Clipboard access was blocked. Select the text and copy it instead.', { tone: 'warn' });+ }+ });+ $('wb-client-id').addEventListener('focus', (e) => e.target.select());+}++// ── keyboard ───────────────────────────────────────────────────++function wireKeyboard() {+ document.addEventListener('keydown', (e) => {+ const mod = e.ctrlKey || e.metaKey;+ const typing = e.target.closest?.('input, textarea, select, [contenteditable="true"]');+ if (mod && e.key === 'Enter' && app.dataset.view === 'generate') {+ e.preventDefault();+ generate();+ return;+ }+ if (e.key === 'Escape') {+ closeMenus();+ toggleHistory(false);+ return;+ }+ if (typing || app.dataset.view !== 'generate' || !vp) return;+ const key = e.key.toLowerCase();+ if (mod && key === 'z') {+ e.preventDefault();+ if (e.shiftKey) redo();+ else undo();+ return;+ }+ if (mod && key === 'y') {+ e.preventDefault();+ redo();+ return;+ }+ if (mod || e.altKey) return;+ const actions = {+ f: () => vp.frame(),+ g: () => setGrid(!vp.gridVisible),+ e: () => setEnv(!vp.environmentOn),+ t: () => setSpin(!vp.autoRotate),+ h: () => toggleHistory(),+ p: screenshot,+ 1: () => setMode('shaded'),+ 2: () => setMode('wireframe'),+ 3: () => setMode('normals'),+ 4: () => setMode('clay'),+ };+ if (actions[key]) {+ e.preventDefault();+ actions[key]();+ }+ });++ document.addEventListener('paste', (e) => {+ if (app.dataset.view !== 'generate' || e.target.closest?.('input, textarea')) return;+ const file = [...(e.clipboardData?.files || [])].find((f) => f.type.startsWith('image/'));+ if (!file) return;+ e.preventDefault();+ setImage(file);+ toast('Pasted image added to the Image node.', { tone: 'ok' });+ });+}++// ── boot ───────────────────────────────────────────────────────++function wireShell() {+ for (const b of document.querySelectorAll('.wb-rail-btn')) b.addEventListener('click', () => setView(b.dataset.nav));+ window.addEventListener('hashchange', () => setView(location.hash.slice(1), { push: false }));+ $('wb-flow-select').addEventListener('change', (e) => {+ activeId = e.target.value;+ saveActiveId(activeId);+ renderNodes();+ });+ $('wb-flow-edit').addEventListener('click', () => {+ editingId = activeId;+ setView('workflows');+ });+ $('wb-run').addEventListener('click', generate);+ $('wb-ext-refresh').addEventListener('click', loadExtensions);+}++async function boot() {+ wireShell();+ renderFlowSelect();+ renderNodes();+ renderHistory();+ wireWorkflows();+ wireSettings();+ wireKeyboard();+ startMeter();+ setView(location.hash.slice(1) || 'generate', { push: false });++ try {+ vp = await mountViewport($('wb-canvas'), {+ onStats: (stats) => {+ hasModel = Boolean(stats);+ $('wb-stats').textContent = stats ? `${stats.tris.toLocaleString()} tri • ${stats.verts.toLocaleString()} verts` : '';+ syncModelTools();+ },+ onHistory: ({ canUndo, canRedo }) => {+ $('wb-undo').disabled = !canUndo;+ $('wb-redo').disabled = !canRedo;+ },+ });+ } catch (err) {+ $('wb-empty').querySelector('h2').textContent = 'The 3D viewport could not start';+ $('wb-empty').querySelector('p').textContent = `${err.message}. The Workbench needs WebGL 2; try an up-to-date Chrome, Edge, Firefox or Safari.`;+ $('wb-run').disabled = true;+ return;+ }+ setGrid(settings.grid);+ setEnv(settings.env);+ wireViewport();+ syncModelTools();++ // Engines feed the Engine picker; load them in the background.+ if (!catalog) {+ fetchCatalog()+ .then((c) => {+ catalog = c;+ renderNodes();+ })+ .catch(() => {+ // The picker keeps Auto, which routes server-side without the catalog.+ });+ }+}++boot();diff --git a/src/workbench/runner.js b/src/workbench/runner.jsnew file mode 100644index 000000000..03005a580--- /dev/null+++ b/src/workbench/runner.js@@ -0,0 +1,166 @@+// Executes a validated Workbench workflow, node by node, against the real+// platform endpoints and the live viewport.+//+// The value flowing down the chain is either an image ({ url } or { prompt })+// or a mesh. A mesh is tracked as { url, loaded, dirty }: remote steps need a+// URL, in-browser steps need it in the viewport, and an in-browser edit marks+// it dirty so the next remote step checkpoints the edited bytes first.++import { NODE_TYPES, validate } from './workflows.js';+import { decimateScene, smoothScene } from './mesh-tools.js';+import { WorkbenchError, generateMesh, removeBackground, remesh, restyle, rig, uploadGlb } from './api.js';++const STATUS_TEXT = {+ queued: 'In line for a GPU',+ running: 'Running',+ processing: 'Running',+};++function generateBody(params, source) {+ const body = { path: 'image', tier: params.tier || 'standard' };+ if (params.backend && params.backend !== 'auto') body.backend = params.backend;+ if (source.url) body.image_urls = [source.url];+ else {+ body.prompt = source.prompt;+ body.aspect_ratio = '1:1';+ }+ if (params.resolution) body.resolution = Number(params.resolution);+ if (params.texture_size) body.texture_size = Number(params.texture_size);+ if (params.target_polycount !== '' && params.target_polycount != null) body.target_polycount = Number(params.target_polycount);+ if (params.output_format && params.output_format !== 'glb') body.output_format = params.output_format;+ if (params.seed !== '' && params.seed != null) body.seed = Number(params.seed);+ return body;+}++/**+ * @param {object} flow workflow to run+ * @param {object} ctx+ * @param {object} ctx.viewport mountViewport() handle+ * @param {{url?:string, prompt?:string}} ctx.source+ * @param {AbortSignal} ctx.signal+ * @param {(e:{nodeId:string,state:'active'|'done'|'error'|'skipped',text:string})=>void} ctx.onStep+ * @returns {Promise<{ glbUrl: string|null, backend: string|null, tier: string|null }>}+ */+export async function runWorkflow(flow, { viewport, source, signal, onStep }) {+ const { ok, order, errors } = validate(flow);+ if (!ok) throw new WorkbenchError(errors[0].message, { kind: 'invalid' });+ if (!source?.url && !source?.prompt) {+ throw new WorkbenchError('Drop an image into the Image node, or describe the object in its prompt box.', { kind: 'invalid' });+ }++ let image = { ...source };+ let mesh = null;+ let meta = { backend: null, tier: null };++ const step = (node, state, text) => onStep?.({ nodeId: node.id, state, text: text || NODE_TYPES[node.type].label });+ const progress = (node) => (s) => step(node, 'active', `${NODE_TYPES[node.type].label}: ${STATUS_TEXT[s.status] || s.status}`);++ async function ensureLoaded() {+ if (!mesh.loaded) {+ await viewport.loadGLB(mesh.url);+ mesh.loaded = true;+ }+ }++ async function ensureRemote(node) {+ if (mesh.url && !mesh.dirty) return mesh.url;+ step(node, 'active', `${NODE_TYPES[node.type].label}: saving the edited mesh`);+ mesh.url = await uploadGlb(await viewport.exportAs('glb'), { signal });+ mesh.dirty = false;+ return mesh.url;+ }++ for (const node of order) {+ if (signal?.aborted) throw new WorkbenchError('Cancelled.', { kind: 'cancelled' });+ const t = NODE_TYPES[node.type];+ if (!t.locked && node.enabled === false) {+ step(node, 'skipped', `${t.label}: off`);+ continue;+ }+ step(node, 'active');+ const p = node.params || {};+ switch (node.type) {+ case 'image':+ step(node, 'done', image.url ? 'Image ready' : 'Prompt ready');+ continue;+ case 'rembg': {+ if (!image.url) {+ step(node, 'skipped', 'Remove Background: skipped for a text prompt');+ continue;+ }+ const out = await removeBackground(image.url, p.model, { signal, onStatus: progress(node) });+ image = { url: out.result_url };+ break;+ }+ case 'generate': {+ const body = generateBody(p, image);+ let out;+ try {+ out = await generateMesh(body, { signal, onStatus: progress(node) });+ } catch (err) {+ // A pinned lane that failed retryably names the lanes that can still+ // serve this request; hop once instead of dead-ending.+ const next = err.retryBackends?.find((b) => b !== body.backend);+ if (!next) throw err;+ step(node, 'active', `Generate Mesh: ${body.backend || 'engine'} failed, retrying on ${next}`);+ out = await generateMesh({ ...body, backend: next }, { signal, onStatus: progress(node) });+ }+ mesh = { url: out.glb_url, loaded: false, dirty: false };+ meta = { backend: out.backend || body.backend || null, tier: out.tier || body.tier };+ break;+ }+ case 'restyle': {+ const url = await ensureRemote(node);+ const out = await restyle(url, String(p.instruction || '').trim() || 'brushed steel', { signal });+ mesh = { url: out.glbUrl, loaded: false, dirty: false };+ break;+ }+ case 'remesh': {+ const url = await ensureRemote(node);+ const faces = Math.min(500000, Math.max(1000, Math.round(Number(p.target_faces) || 20000)));+ const out = await remesh(url, { mode: p.mode, targetFaces: faces }, { signal, onStatus: progress(node) });+ mesh = { url: out.result_url, loaded: false, dirty: false };+ break;+ }+ case 'rig': {+ const url = await ensureRemote(node);+ const out = await rig(url, { signal, onStatus: progress(node) });+ mesh = { url: out.glb_url, loaded: false, dirty: false };+ break;+ }+ case 'decimate': {+ await ensureLoaded();+ const { before, after } = await viewport.mutate((m) => decimateScene(m, Number(p.ratio) || 0.5));+ mesh.dirty = true;+ step(node, 'done', `Decimate: ${before.tris.toLocaleString()} to ${after.tris.toLocaleString()} tris`);+ continue;+ }+ case 'smooth': {+ await ensureLoaded();+ await viewport.mutate((m) => smoothScene(m, Math.round(Number(p.iterations) || 4)));+ mesh.dirty = true;+ break;+ }+ case 'output':+ await ensureLoaded();+ // Checkpoint in-browser edits so the history entry and the share link+ // reopen exactly what is on screen. The model is already in the scene,+ // so a failed save costs only the link.+ if (mesh.dirty) {+ try {+ await ensureRemote(node);+ } catch (err) {+ if (err.kind === 'cancelled') throw err;+ step(node, 'done', 'Added to scene (not saved: the edited mesh could not be uploaded)');+ continue;+ }+ }+ break;+ default:+ throw new WorkbenchError(`Unknown node type ${node.type}.`);+ }+ step(node, 'done');+ }++ return { glbUrl: mesh && !mesh.dirty ? mesh.url : null, ...meta };+}diff --git a/src/workbench/workbench.css b/src/workbench/workbench.cssnew file mode 100644index 000000000..5b7ccb6b3--- /dev/null+++ b/src/workbench/workbench.css@@ -0,0 +1,896 @@+/* Workbench: a desktop-style image-to-3D workspace.+ Built on the shared tokens in public/tokens.css; the --wb-* layer below only+ names the roles this layout needs and maps them onto those tokens. */++:root {+ --wb-bg: #111114;+ --wb-panel: #16161a;+ --wb-panel-2: #1c1c21;+ --wb-viewport-bg: #17171a;+ --wb-field: #101013;+ --wb-line: var(--hairline-strong, rgba(255, 255, 255, 0.09));+ --wb-line-soft: var(--hairline, rgba(255, 255, 255, 0.055));+ --wb-ink: var(--ink, #e8e8e8);+ --wb-ink-dim: var(--ink-dim, #888);+ --wb-ink-faint: #5d5d68;+ --wb-accent: #7c3aed;+ --wb-accent-hi: #8b5cf6;+ --wb-accent-ink: var(--accent-violet, #c4b5fd);+ --wb-accent-soft: rgba(139, 92, 246, 0.16);+ --wb-io-in: #38bdf8;+ --wb-io-out: var(--accent-violet, #c4b5fd);+ --wb-ok: var(--success, #4ade80);+ --wb-err: var(--danger, #f87171);+ --wb-warn: var(--warn, #fbbf24);+ --wb-rail: 48px;+ --wb-side: 276px;+ --wb-bar: 36px;+ --wb-radius: var(--radius-sm, 6px);+ --wb-ease: cubic-bezier(0.2, 0.8, 0.2, 1);+}++:root[data-theme='light'] {+ --wb-bg: #f3f3f6;+ --wb-panel: #fbfbfd;+ --wb-panel-2: #ffffff;+ --wb-viewport-bg: #e9e9ee;+ --wb-field: #ffffff;+ --wb-line: rgba(0, 0, 0, 0.1);+ --wb-line-soft: rgba(0, 0, 0, 0.06);+ --wb-ink: #17171c;+ --wb-ink-dim: #5f5f6b;+ --wb-ink-faint: #9a9aa6;+ --wb-accent-ink: #6d28d9;+ --wb-accent-soft: rgba(124, 58, 237, 0.12);+ --wb-io-in: #0284c7;+ --wb-io-out: #7c3aed;+}++* { box-sizing: border-box; }++html, body {+ height: 100%;+ margin: 0;+ background: var(--wb-bg);+ color: var(--wb-ink);+ font-family: var(--font-body, Inter, system-ui, sans-serif);+ font-size: var(--text-md, 13px);+ overflow: hidden;+}++button, input, select, textarea { font: inherit; color: inherit; }+button { cursor: pointer; }+:focus-visible { outline: 2px solid var(--wb-accent-hi); outline-offset: 2px; }+.wb-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }++/* ── app shell ─────────────────────────────────────────────── */+.wb-app {+ display: grid;+ grid-template-columns: var(--wb-rail) var(--wb-side) 1fr;+ grid-template-rows: var(--wb-bar) 1fr;+ height: 100dvh;+}++.wb-top {+ grid-column: 1 / -1;+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 0 12px 0 14px;+ border-bottom: 1px solid var(--wb-line);+ background: var(--wb-bg);+ min-width: 0;+}+.wb-brand {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ font-weight: var(--weight-semibold, 600);+ color: var(--wb-ink);+ text-decoration: none;+ border-radius: var(--wb-radius);+ padding: 2px 4px;+}+.wb-brand svg { width: 20px; height: 20px; }+.wb-brand small { color: var(--wb-ink-dim); font-weight: 500; }+.wb-brand:hover small { color: var(--wb-ink); }+.wb-top-spacer { flex: 1; }+.wb-meter {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 11px;+ color: var(--wb-ink-dim);+ white-space: nowrap;+}+.wb-meter-bar {+ width: 54px;+ height: 4px;+ border-radius: 2px;+ background: var(--wb-line);+ overflow: hidden;+}+.wb-meter-bar i {+ display: block;+ height: 100%;+ width: 0;+ background: var(--wb-accent-hi);+ transition: width 0.6s var(--wb-ease);+}+.wb-top-link {+ color: var(--wb-ink-dim);+ text-decoration: none;+ font-size: 12px;+ padding: 4px 8px;+ border-radius: var(--wb-radius);+ transition: color 0.15s, background 0.15s;+}+.wb-top-link:hover { color: var(--wb-ink); background: var(--wb-panel-2); }++/* ── icon rail ─────────────────────────────────────────────── */+.wb-rail {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 2px;+ padding: 8px 0;+ border-right: 1px solid var(--wb-line);+ background: var(--wb-bg);+}+.wb-rail-btn {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 3px;+ width: 42px;+ padding: 7px 0 5px;+ border: 0;+ border-radius: 8px;+ background: transparent;+ color: var(--wb-ink-dim);+ font-size: 9.5px;+ transition: color 0.15s, background 0.15s, transform 0.1s;+}+.wb-rail-btn svg { width: 18px; height: 18px; }+.wb-rail-btn:hover { color: var(--wb-ink); background: var(--wb-panel-2); }+.wb-rail-btn:active { transform: scale(0.96); }+.wb-rail-btn[aria-current='page'] { color: var(--wb-accent-ink); background: var(--wb-accent-soft); }++/* ── side panel ────────────────────────────────────────────── */+.wb-side {+ display: flex;+ flex-direction: column;+ min-height: 0;+ border-right: 1px solid var(--wb-line);+ background: var(--wb-panel);+}+.wb-side-scroll {+ flex: 1;+ overflow-y: auto;+ padding: 14px 14px 18px;+ scrollbar-width: thin;+}+.wb-label {+ font-size: 10.5px;+ letter-spacing: 0.09em;+ text-transform: uppercase;+ color: var(--wb-ink-dim);+ font-weight: 600;+ margin: 0 0 8px;+}+.wb-row { display: flex; gap: 6px; align-items: center; }++.wb-select, .wb-input {+ width: 100%;+ min-width: 0;+ height: 30px;+ padding: 0 8px;+ border: 1px solid var(--wb-line);+ border-radius: var(--wb-radius);+ background: var(--wb-field);+ color: var(--wb-ink);+ font-size: 12px;+ transition: border-color 0.15s, background 0.15s;+}+.wb-select:hover, .wb-input:hover { border-color: var(--wb-ink-faint); }+.wb-select:focus, .wb-input:focus { border-color: var(--wb-accent-hi); outline: none; box-shadow: 0 0 0 2px var(--wb-accent-soft); }+textarea.wb-input { height: auto; min-height: 64px; padding: 7px 8px; resize: vertical; line-height: 1.45; }++.wb-icon-btn {+ display: inline-grid;+ place-items: center;+ flex: none;+ width: 30px;+ height: 30px;+ border: 1px solid var(--wb-line);+ border-radius: var(--wb-radius);+ background: var(--wb-field);+ color: var(--wb-ink-dim);+ transition: color 0.15s, border-color 0.15s, background 0.15s;+}+.wb-icon-btn svg { width: 14px; height: 14px; }+.wb-icon-btn:hover { color: var(--wb-ink); border-color: var(--wb-ink-faint); }+.wb-icon-btn:active { background: var(--wb-panel-2); }++/* workflow node cards in the Generate panel */+.wb-node { padding: 14px 0; border-top: 1px solid var(--wb-line-soft); }+.wb-node:first-of-type { border-top: 0; }+.wb-node-head { display: flex; align-items: flex-start; gap: 8px; }+.wb-node-title { flex: 1; min-width: 0; }+.wb-node-title strong { display: block; font-size: 12.5px; font-weight: 600; }+.wb-io { display: inline-flex; gap: 4px; align-items: center; font-size: 10px; margin-top: 2px; }+.wb-io .in { color: var(--wb-io-in); }+.wb-io .out { color: var(--wb-io-out); }+.wb-io .arrow { color: var(--wb-ink-faint); }+.wb-node-body { display: grid; gap: 7px; margin-top: 10px; }+.wb-node[data-off='true'] .wb-node-body { opacity: 0.4; pointer-events: none; }+.wb-node[data-collapsed='true'] .wb-node-body { display: none; }+.wb-param { display: grid; grid-template-columns: 76px 1fr; align-items: center; gap: 8px; }+.wb-param > span {+ font-size: 11px;+ color: var(--wb-ink-dim);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.wb-hint { font-size: 11px; color: var(--wb-ink-dim); line-height: 1.45; margin: 0; }+.wb-hint a { color: var(--wb-accent-ink); }++.wb-chev {+ display: inline-grid;+ place-items: center;+ width: 20px;+ height: 20px;+ border: 0;+ border-radius: 4px;+ background: transparent;+ color: var(--wb-ink-faint);+ transition: transform 0.2s var(--wb-ease), color 0.15s, background 0.15s;+}+.wb-chev:hover { color: var(--wb-ink); background: var(--wb-panel-2); }+.wb-node[data-collapsed='true'] .wb-chev { transform: rotate(180deg); }+.wb-chev svg { width: 12px; height: 12px; }++/* toggle switch */+.wb-switch { position: relative; flex: none; width: 26px; height: 15px; margin-top: 2px; }+.wb-switch input { position: absolute; inset: 0; opacity: 0; margin: 0; cursor: pointer; }+.wb-switch span {+ position: absolute;+ inset: 0;+ border-radius: 999px;+ background: var(--wb-line);+ transition: background 0.2s;+ pointer-events: none;+}+.wb-switch span::after {+ content: '';+ position: absolute;+ top: 2px;+ left: 2px;+ width: 11px;+ height: 11px;+ border-radius: 50%;+ background: #fff;+ transition: transform 0.2s var(--wb-ease);+}+.wb-switch input:checked + span { background: var(--wb-accent-hi); }+.wb-switch input:checked + span::after { transform: translateX(11px); }+.wb-switch input:focus-visible + span { outline: 2px solid var(--wb-accent-hi); outline-offset: 2px; }++/* image drop zone */+.wb-drop {+ position: relative;+ display: grid;+ place-items: center;+ aspect-ratio: 1;+ border: 1px solid var(--wb-line);+ border-radius: 8px;+ background: var(--wb-field);+ color: var(--wb-ink-dim);+ text-align: center;+ overflow: hidden;+ transition: border-color 0.15s, background 0.15s;+}+.wb-drop:hover, .wb-drop.is-over { border-color: var(--wb-accent-hi); background: var(--wb-accent-soft); }+.wb-drop img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; padding: 8px; }+.wb-drop-empty { display: grid; gap: 6px; justify-items: center; padding: 16px; font-size: 11.5px; pointer-events: none; }+.wb-drop-empty svg { width: 22px; height: 22px; color: var(--wb-ink-faint); }+.wb-drop input { position: absolute; inset: 0; opacity: 0; cursor: pointer; }+.wb-drop-status {+ position: absolute;+ left: 6px;+ right: 6px;+ bottom: 6px;+ padding: 4px 7px;+ border-radius: 4px;+ background: rgba(0, 0, 0, 0.66);+ color: #fff;+ font-size: 10.5px;+ text-align: left;+ pointer-events: none;+}+.wb-drop-status[data-tone='err'] { background: rgba(127, 29, 29, 0.9); }+.wb-drop-clear { position: absolute; top: 6px; right: 6px; z-index: 2; width: 24px; height: 24px; }++/* generate footer */+.wb-side-foot { padding: 12px 14px 14px; border-top: 1px solid var(--wb-line-soft); }+.wb-primary {+ position: relative;+ width: 100%;+ height: 38px;+ border: 0;+ border-radius: 8px;+ background: var(--wb-accent);+ color: #fff;+ font-weight: 600;+ font-size: 13px;+ overflow: hidden;+ transition: background 0.15s, transform 0.1s, opacity 0.15s;+}+.wb-primary:hover { background: var(--wb-accent-hi); }+.wb-primary:active { transform: translateY(1px); }+.wb-primary:disabled { opacity: 0.5; cursor: not-allowed; }+.wb-primary[data-busy='true'] { background: var(--wb-panel-2); color: var(--wb-ink); }+.wb-primary .wb-progress {+ position: absolute;+ left: 0;+ bottom: 0;+ height: 2px;+ width: 0;+ background: var(--wb-accent-hi);+ transition: width 0.4s var(--wb-ease);+}+.wb-run-log { margin: 8px 0 0; padding: 0; list-style: none; display: grid; gap: 4px; font-size: 11px; color: var(--wb-ink-dim); }+.wb-run-log li { display: flex; gap: 6px; align-items: center; }+.wb-run-log li::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: var(--wb-ink-faint); flex: none; }+.wb-run-log li[data-state='active']::before { background: var(--wb-accent-hi); animation: wb-pulse 1.1s ease-in-out infinite; }+.wb-run-log li[data-state='done']::before { background: var(--wb-ok); }+.wb-run-log li[data-state='error']::before { background: var(--wb-err); }+.wb-run-log li[data-state='error'] { color: var(--wb-err); }+@keyframes wb-pulse { 50% { opacity: 0.35; } }++/* ── main area ─────────────────────────────────────────────── */+.wb-main { position: relative; display: flex; flex-direction: column; min-width: 0; min-height: 0; background: var(--wb-viewport-bg); }+.wb-toolbar {+ display: flex;+ align-items: center;+ gap: 6px;+ flex-wrap: wrap;+ padding: 6px 10px;+ border-bottom: 1px solid var(--wb-line-soft);+ background: var(--wb-viewport-bg);+ z-index: 3;+}+.wb-sep { width: 1px; height: 18px; background: var(--wb-line); margin: 0 2px; }+.wb-tool {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ height: 28px;+ padding: 0 10px;+ border: 1px solid var(--wb-line);+ border-radius: var(--wb-radius);+ background: var(--wb-panel);+ color: var(--wb-ink);+ font-size: 11.5px;+ white-space: nowrap;+ transition: border-color 0.15s, background 0.15s, color 0.15s, transform 0.1s;+}+.wb-tool svg { width: 13px; height: 13px; color: var(--wb-ink-dim); }+.wb-tool:hover:not(:disabled) { border-color: var(--wb-ink-faint); background: var(--wb-panel-2); }+.wb-tool:active:not(:disabled) { transform: translateY(1px); }+.wb-tool:disabled { opacity: 0.4; cursor: not-allowed; }+.wb-tool.is-square { width: 28px; padding: 0; justify-content: center; }+.wb-tool[aria-pressed='true'] { border-color: var(--wb-accent-hi); color: var(--wb-accent-ink); background: var(--wb-accent-soft); }+.wb-tool .caret { width: 10px; height: 10px; margin-left: -2px; }++.wb-menu-wrap { position: relative; }+.wb-menu {+ position: absolute;+ top: calc(100% + 4px);+ left: 0;+ z-index: 20;+ min-width: 200px;+ padding: 4px;+ border: 1px solid var(--wb-line);+ border-radius: 8px;+ background: var(--wb-panel-2);+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.4);+ opacity: 0;+ transform: translateY(-4px);+ pointer-events: none;+ transition: opacity 0.14s, transform 0.14s var(--wb-ease);+}+.wb-menu[data-open='true'] { opacity: 1; transform: none; pointer-events: auto; }+.wb-menu button {+ display: flex;+ justify-content: space-between;+ gap: 12px;+ width: 100%;+ padding: 7px 9px;+ border: 0;+ border-radius: 5px;+ background: transparent;+ text-align: left;+ font-size: 12px;+}+.wb-menu button:hover, .wb-menu button:focus-visible { background: var(--wb-accent-soft); outline: none; }+.wb-menu button small { color: var(--wb-ink-dim); font-size: 10.5px; }++.wb-popover {+ position: absolute;+ top: calc(100% + 4px);+ left: 0;+ z-index: 20;+ width: 250px;+ padding: 12px;+ border: 1px solid var(--wb-line);+ border-radius: 8px;+ background: var(--wb-panel-2);+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.4);+ display: grid;+ gap: 10px;+ opacity: 0;+ transform: translateY(-4px);+ pointer-events: none;+ transition: opacity 0.14s, transform 0.14s var(--wb-ease);+}+.wb-popover[data-open='true'] { opacity: 1; transform: none; pointer-events: auto; }+.wb-popover input[type='range'] { width: 100%; accent-color: var(--wb-accent-hi); }+.wb-popover .wb-row { justify-content: space-between; font-size: 11.5px; }+.wb-popover output { font-family: var(--font-mono, monospace); color: var(--wb-ink-dim); font-size: 11px; }+.wb-popover .wb-tool { justify-content: center; }++.wb-stage { position: relative; flex: 1; min-height: 0; }+.wb-canvas { position: absolute; inset: 0; }+.wb-canvas canvas { display: block; width: 100%; height: 100%; touch-action: none; }++.wb-strip {+ position: absolute;+ left: 14px;+ top: 50%;+ transform: translateY(-50%);+ z-index: 2;+ display: flex;+ flex-direction: column;+ gap: 3px;+ padding: 4px;+ border: 1px solid var(--wb-line);+ border-radius: 9px;+ background: color-mix(in srgb, var(--wb-panel) 88%, transparent);+ backdrop-filter: blur(8px);+}+.wb-strip hr { width: 70%; border: 0; border-top: 1px solid var(--wb-line); margin: 3px auto; }+.wb-strip-btn {+ position: relative;+ display: grid;+ place-items: center;+ width: 28px;+ height: 28px;+ border: 0;+ border-radius: 6px;+ background: transparent;+ color: var(--wb-ink-dim);+ transition: color 0.15s, background 0.15s;+}+.wb-strip-btn svg { width: 15px; height: 15px; }+.wb-strip-btn:hover { color: var(--wb-ink); background: var(--wb-panel-2); }+.wb-strip-btn[aria-pressed='true'] { background: var(--wb-accent); color: #fff; }+.wb-strip-btn[data-tip]:hover::after,+.wb-strip-btn[data-tip]:focus-visible::after {+ content: attr(data-tip);+ position: absolute;+ left: calc(100% + 8px);+ top: 50%;+ transform: translateY(-50%);+ padding: 4px 7px;+ border-radius: 4px;+ background: #000;+ color: #fff;+ font-size: 11px;+ white-space: nowrap;+ pointer-events: none;+}++.wb-stats {+ position: absolute;+ left: 14px;+ bottom: 10px;+ z-index: 2;+ font-family: var(--font-mono, monospace);+ font-size: 11px;+ color: var(--wb-ink-dim);+ pointer-events: none;+}+/* Centered, because the bottom-right corner belongs to the shared corner stack+ (search hint, language picker). */+.wb-hint-corner {+ position: absolute;+ left: 50%;+ bottom: 10px;+ transform: translateX(-50%);+ white-space: nowrap;+ z-index: 2;+ font-size: 11px;+ color: var(--wb-ink-faint);+ pointer-events: none;+}++.wb-empty {+ position: absolute;+ inset: 0;+ z-index: 1;+ display: grid;+ place-items: center;+ pointer-events: none;+ transition: opacity 0.3s;+}+.wb-empty[hidden] { display: none; }+.wb-empty-card { max-width: 340px; padding: 0 20px; text-align: center; color: var(--wb-ink-dim); }+.wb-empty-card svg { width: 44px; height: 44px; color: var(--wb-ink-faint); margin-bottom: 10px; }+.wb-empty-card h2 { margin: 0 0 6px; font-size: 15px; color: var(--wb-ink); font-weight: 600; }+.wb-empty-card p { margin: 0; font-size: 12.5px; line-height: 1.55; }+.wb-empty-card kbd {+ font-family: var(--font-mono, monospace);+ font-size: 10.5px;+ padding: 1px 5px;+ border: 1px solid var(--wb-line);+ border-radius: 4px;+ background: var(--wb-panel);+}++.wb-busy {+ position: absolute;+ inset: 0;+ z-index: 2;+ display: grid;+ place-items: center;+ pointer-events: none;+}+.wb-busy[hidden] { display: none; }+.wb-busy-card {+ display: grid;+ justify-items: center;+ gap: 10px;+ padding: 18px 22px;+ border: 1px solid var(--wb-line);+ border-radius: 12px;+ background: color-mix(in srgb, var(--wb-panel) 92%, transparent);+ backdrop-filter: blur(10px);+ min-width: 240px;+ text-align: center;+}+.wb-busy-card strong { font-size: 13px; }+.wb-busy-card span { font-size: 11.5px; color: var(--wb-ink-dim); }+.wb-busy-card img { width: 72px; height: 72px; object-fit: contain; border-radius: 6px; background: var(--wb-field); }+.wb-spinner {+ width: 22px;+ height: 22px;+ border-radius: 50%;+ border: 2px solid var(--wb-line);+ border-top-color: var(--wb-accent-hi);+ animation: wb-spin 0.8s linear infinite;+}+@keyframes wb-spin { to { transform: rotate(360deg); } }++.wb-dropveil {+ position: absolute;+ inset: 10px;+ z-index: 5;+ display: grid;+ place-items: center;+ border: 2px dashed var(--wb-accent-hi);+ border-radius: 12px;+ background: var(--wb-accent-soft);+ color: var(--wb-ink);+ font-weight: 600;+ pointer-events: none;+ opacity: 0;+ transition: opacity 0.15s;+}+.wb-dropveil[data-on='true'] { opacity: 1; }++/* history drawer */+.wb-history {+ position: absolute;+ left: 56px;+ top: 50%;+ transform: translate(-6px, -50%);+ z-index: 4;+ width: 260px;+ max-height: min(460px, 80%);+ display: flex;+ flex-direction: column;+ border: 1px solid var(--wb-line);+ border-radius: 10px;+ background: var(--wb-panel-2);+ box-shadow: 0 16px 40px rgba(0, 0, 0, 0.45);+ opacity: 0;+ pointer-events: none;+ transition: opacity 0.15s, transform 0.15s var(--wb-ease);+}+.wb-history[data-open='true'] { opacity: 1; transform: translate(0, -50%); pointer-events: auto; }+.wb-history header { display: flex; justify-content: space-between; align-items: center; padding: 10px 12px; border-bottom: 1px solid var(--wb-line-soft); }+.wb-history header strong { font-size: 12px; }+.wb-history ul { list-style: none; margin: 0; padding: 6px; overflow-y: auto; display: grid; gap: 4px; }+.wb-history li button {+ display: grid;+ grid-template-columns: 40px 1fr;+ gap: 9px;+ align-items: center;+ width: 100%;+ padding: 6px;+ border: 0;+ border-radius: 6px;+ background: transparent;+ text-align: left;+ transition: background 0.15s;+}+.wb-history li button:hover, .wb-history li button:focus-visible { background: var(--wb-accent-soft); outline: none; }+.wb-history li img { width: 40px; height: 40px; border-radius: 5px; object-fit: cover; background: var(--wb-field); }+.wb-history li span { display: grid; gap: 2px; min-width: 0; font-size: 11.5px; }+.wb-history li small { color: var(--wb-ink-dim); font-size: 10.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.wb-history-empty { padding: 18px 14px; color: var(--wb-ink-dim); font-size: 11.5px; line-height: 1.5; }++/* toasts */+.wb-toasts { position: fixed; right: 16px; bottom: 16px; z-index: 50; display: grid; gap: 8px; max-width: min(360px, calc(100vw - 32px)); }+.wb-toast {+ display: flex;+ gap: 10px;+ align-items: flex-start;+ padding: 10px 12px;+ border: 1px solid var(--wb-line);+ border-left: 3px solid var(--wb-accent-hi);+ border-radius: 8px;+ background: var(--wb-panel-2);+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4);+ font-size: 12px;+ line-height: 1.45;+ animation: wb-in 0.2s var(--wb-ease);+}+.wb-toast[data-tone='err'] { border-left-color: var(--wb-err); }+.wb-toast[data-tone='ok'] { border-left-color: var(--wb-ok); }+.wb-toast[data-tone='warn'] { border-left-color: var(--wb-warn); }+.wb-toast p { margin: 0; flex: 1; }+.wb-toast button { border: 0; background: transparent; color: var(--wb-accent-ink); font-weight: 600; padding: 0; white-space: nowrap; }+.wb-toast button:hover { text-decoration: underline; }+@keyframes wb-in { from { opacity: 0; transform: translateY(6px); } }++/* ── full-width views (workflows, extensions, settings) ────── */+.wb-view { display: none; grid-column: 2 / -1; min-width: 0; min-height: 0; background: var(--wb-panel); }+.wb-app[data-view='workflows'] .wb-view[data-view='workflows'],+.wb-app[data-view='extensions'] .wb-view[data-view='extensions'],+.wb-app[data-view='settings'] .wb-view[data-view='settings'] { display: flex; }+.wb-app:not([data-view='generate']) .wb-side,+.wb-app:not([data-view='generate']) .wb-main { display: none; }++.wb-page { flex: 1; overflow-y: auto; padding: 28px clamp(16px, 4vw, 48px) 48px; }+.wb-page-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 16px; flex-wrap: wrap; margin-bottom: 20px; }+.wb-page-head h1 { margin: 0 0 4px; font-size: 20px; font-weight: 600; font-family: var(--font-display, inherit); }+.wb-page-head p { margin: 0; color: var(--wb-ink-dim); max-width: 640px; line-height: 1.55; }+.wb-btn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ height: 32px;+ padding: 0 12px;+ border: 1px solid var(--wb-line);+ border-radius: var(--wb-radius);+ background: var(--wb-panel-2);+ font-size: 12px;+ font-weight: 500;+ text-decoration: none;+ color: var(--wb-ink);+ transition: border-color 0.15s, background 0.15s, transform 0.1s;+}+.wb-btn:hover { border-color: var(--wb-ink-faint); }+.wb-btn:active { transform: translateY(1px); }+.wb-btn.is-accent { background: var(--wb-accent); border-color: transparent; color: #fff; }+.wb-btn.is-accent:hover { background: var(--wb-accent-hi); }+.wb-btn.is-danger:hover { border-color: var(--wb-err); color: var(--wb-err); }+.wb-btn svg { width: 14px; height: 14px; }++/* workflow list + graph editor */+.wb-flows { display: grid; grid-template-columns: 240px 1fr; flex: 1; min-height: 0; }+.wb-flow-list { border-right: 1px solid var(--wb-line); overflow-y: auto; padding: 14px; display: grid; align-content: start; gap: 4px; }+.wb-flow-item {+ display: grid;+ gap: 2px;+ padding: 9px 10px;+ border: 1px solid transparent;+ border-radius: 7px;+ background: transparent;+ text-align: left;+ transition: background 0.15s, border-color 0.15s;+}+.wb-flow-item:hover { background: var(--wb-panel-2); }+.wb-flow-item[aria-current='true'] { border-color: var(--wb-accent-hi); background: var(--wb-accent-soft); }+.wb-flow-item strong { font-size: 12.5px; font-weight: 600; }+.wb-flow-item small { color: var(--wb-ink-dim); font-size: 11px; }+.wb-flow-editor { display: flex; flex-direction: column; min-width: 0; min-height: 0; }+.wb-flow-bar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; padding: 10px 14px; border-bottom: 1px solid var(--wb-line); }+.wb-flow-bar .wb-input { width: 220px; }+.wb-flow-status { font-size: 11.5px; color: var(--wb-ink-dim); margin-left: auto; }+.wb-flow-status[data-tone='err'] { color: var(--wb-err); }+.wb-flow-status[data-tone='ok'] { color: var(--wb-ok); }+.wb-graph {+ position: relative;+ flex: 1;+ min-height: 360px;+ overflow: hidden;+ background-color: var(--wb-viewport-bg);+ background-image: radial-gradient(var(--wb-line) 1px, transparent 1px);+ background-size: 20px 20px;+ touch-action: none;+}+.wb-graph svg.wires { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; overflow: visible; }+.wb-graph svg.wires path { fill: none; stroke: var(--wb-io-out); stroke-width: 2; opacity: 0.8; }+.wb-graph svg.wires path.pending { stroke-dasharray: 5 4; opacity: 0.6; }+.wb-gnode {+ position: absolute;+ width: 196px;+ border: 1px solid var(--wb-line);+ border-radius: 9px;+ background: var(--wb-panel-2);+ box-shadow: 0 6px 18px rgba(0, 0, 0, 0.3);+ user-select: none;+ transition: border-color 0.15s, box-shadow 0.15s;+}+.wb-gnode:hover { border-color: var(--wb-ink-faint); }+.wb-gnode[data-selected='true'] { border-color: var(--wb-accent-hi); box-shadow: 0 0 0 3px var(--wb-accent-soft), 0 6px 18px rgba(0, 0, 0, 0.3); }+.wb-gnode[data-invalid='true'] { border-color: var(--wb-err); }+.wb-gnode header { display: flex; align-items: center; gap: 6px; padding: 8px 10px; border-bottom: 1px solid var(--wb-line-soft); cursor: grab; font-size: 12px; font-weight: 600; }+.wb-gnode header:active { cursor: grabbing; }+.wb-gnode header i { width: 8px; height: 8px; border-radius: 2px; background: var(--wb-accent-hi); flex: none; }+.wb-gnode header button { margin-left: auto; width: 20px; height: 20px; border: 0; border-radius: 4px; background: transparent; color: var(--wb-ink-faint); display: grid; place-items: center; }+.wb-gnode header button:hover { color: var(--wb-err); background: var(--wb-panel); }+.wb-gnode header button svg { width: 11px; height: 11px; }+.wb-gnode .ports { display: flex; justify-content: space-between; padding: 8px 0; font-size: 10.5px; color: var(--wb-ink-dim); }+.wb-gnode .port { position: relative; display: flex; align-items: center; gap: 6px; padding: 2px 10px; }+.wb-gnode .port.out { justify-content: flex-end; }+.wb-gnode .port .dot {+ position: absolute;+ top: 50%;+ width: 12px;+ height: 12px;+ margin-top: -6px;+ border: 2px solid var(--wb-panel-2);+ border-radius: 50%;+ cursor: crosshair;+ transition: transform 0.12s;+}+.wb-gnode .port.in .dot { left: -7px; background: var(--wb-io-in); }+.wb-gnode .port.out .dot { right: -7px; background: var(--wb-io-out); }+.wb-gnode .port .dot:hover { transform: scale(1.3); }+.wb-gnode .sub { padding: 0 10px 9px; font-size: 10.5px; color: var(--wb-ink-dim); }+.wb-palette { display: flex; gap: 6px; flex-wrap: wrap; padding: 10px 14px; border-top: 1px solid var(--wb-line); background: var(--wb-panel); }+.wb-palette span { font-size: 11px; color: var(--wb-ink-dim); align-self: center; margin-right: 4px; }++/* extensions */+.wb-ext-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 12px; }+.wb-ext {+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding: 14px;+ border: 1px solid var(--wb-line);+ border-radius: 10px;+ background: var(--wb-panel-2);+ transition: border-color 0.15s, transform 0.15s var(--wb-ease);+}+.wb-ext:hover { border-color: var(--wb-ink-faint); transform: translateY(-1px); }+.wb-ext header { display: flex; align-items: flex-start; gap: 10px; }+.wb-ext header div { flex: 1; min-width: 0; }+.wb-ext h3 { margin: 0; font-size: 13.5px; }+.wb-ext header small { color: var(--wb-ink-dim); font-size: 11px; }+.wb-ext p { margin: 0; color: var(--wb-ink-dim); font-size: 12px; line-height: 1.5; }+.wb-tags { display: flex; gap: 5px; flex-wrap: wrap; }+.wb-tag { padding: 2px 7px; border-radius: 999px; border: 1px solid var(--wb-line); font-size: 10.5px; color: var(--wb-ink-dim); }+.wb-tag[data-tone='ok'] { color: var(--wb-ok); border-color: color-mix(in srgb, var(--wb-ok) 40%, transparent); }+.wb-tag[data-tone='err'] { color: var(--wb-err); border-color: color-mix(in srgb, var(--wb-err) 40%, transparent); }+.wb-tag[data-tone='warn'] { color: var(--wb-warn); border-color: color-mix(in srgb, var(--wb-warn) 40%, transparent); }+.wb-tag[data-tone='accent'] { color: var(--wb-accent-ink); border-color: color-mix(in srgb, var(--wb-accent-hi) 50%, transparent); }+.wb-ext footer { display: flex; gap: 8px; align-items: center; margin-top: auto; font-size: 11px; color: var(--wb-ink-dim); }+.wb-ext footer label { margin-left: auto; display: inline-flex; gap: 6px; align-items: center; }+.wb-skel { border-radius: 10px; background: linear-gradient(90deg, var(--wb-panel-2), var(--wb-panel) 50%, var(--wb-panel-2)); background-size: 200% 100%; animation: wb-shimmer 1.3s linear infinite; height: 150px; }+@keyframes wb-shimmer { to { background-position: -200% 0; } }++/* settings */+.wb-settings { display: grid; gap: 16px; max-width: 760px; }+.wb-card { padding: 16px; border: 1px solid var(--wb-line); border-radius: 10px; background: var(--wb-panel-2); display: grid; gap: 12px; }+.wb-card h2 { margin: 0; font-size: 14px; }+.wb-card .wb-param { grid-template-columns: 180px 1fr; }+.wb-card .wb-param > span { font-size: 12px; white-space: normal; }+.wb-code {+ position: relative;+ margin: 0;+ padding: 12px 14px;+ border: 1px solid var(--wb-line);+ border-radius: 8px;+ background: var(--wb-field);+ font-family: var(--font-mono, monospace);+ font-size: 11.5px;+ line-height: 1.6;+ overflow-x: auto;+ white-space: pre;+}+.wb-code + .wb-btn { justify-self: start; }++/* ── controller-rendered pieces ────────────────────────────── */+[hidden] { display: none !important; }+.wb-range { display: flex; align-items: center; gap: 8px; min-width: 0; }+.wb-range input { flex: 1; min-width: 0; accent-color: var(--wb-accent-hi); }+.wb-range output { min-width: 34px; text-align: right; font-family: var(--font-mono, ui-monospace, monospace); font-size: 11px; color: var(--wb-ink-dim); }+.wb-row .wb-icon-btn { flex: none; }+.wb-prompt { width: 100%; min-height: 54px; }+.wb-prompt:disabled { opacity: 0.45; cursor: not-allowed; }+.wb-flow-warning {+ display: grid;+ gap: 6px;+ justify-items: start;+ margin: 6px 0 4px;+ padding: 10px 12px;+ border: 1px solid color-mix(in srgb, var(--wb-err) 45%, transparent);+ border-radius: 8px;+ background: color-mix(in srgb, var(--wb-err) 10%, transparent);+ font-size: 11.5px;+}+.wb-flow-warning p { margin: 0; color: var(--wb-ink-dim); line-height: 1.45; }+.wb-run-log li[data-state='pending'] { opacity: 0.6; }+.wb-run-log li[data-state='skipped'] { opacity: 0.45; text-decoration: line-through; }+.wb-toast[data-leaving='true'] { opacity: 0; transform: translateY(6px); transition: opacity 0.2s, transform 0.2s; }+.wb-toast .wb-toast-x { display: inline-grid; place-items: center; width: 18px; height: 18px; color: var(--wb-ink-faint); border-radius: 4px; }+.wb-toast .wb-toast-x:hover { color: var(--wb-ink); background: var(--wb-line-soft); text-decoration: none; }+.wb-toast .wb-toast-x svg { width: 11px; height: 11px; }+.wb-graph { overflow: hidden; cursor: grab; }+.wb-graph.is-panning { cursor: grabbing; }+.wb-graph.is-wiring, .wb-graph.is-wiring * { cursor: crosshair; }+.wb-graph-layer { position: absolute; inset: 0; will-change: transform; }+.wb-palette .wb-btn { display: inline-flex; align-items: center; gap: 5px; }+.wb-palette .wb-btn svg { width: 12px; height: 12px; }+.wb-ext footer a { margin-left: auto; color: var(--wb-accent-ink); font-weight: 600; text-decoration: none; }+.wb-ext footer a:hover { text-decoration: underline; }+.wb-ext footer > span:last-child:not(:first-child) { margin-left: auto; }+.wb-ext-error { grid-column: 1 / -1; display: grid; gap: 8px; justify-items: start; padding: 20px; border: 1px dashed var(--wb-line); border-radius: 10px; }+.wb-ext-error p { margin: 0; color: var(--wb-ink-dim); }+.wb-primary:focus-visible { outline: 2px solid var(--wb-accent-hi); outline-offset: 2px; }++@media (prefers-reduced-motion: reduce) {+ *, *::before, *::after { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; }+}++/* ── responsive ────────────────────────────────────────────── */+@media (max-width: 900px) {+ :root { --wb-side: 248px; }+ .wb-meter { display: none; }+}++@media (max-width: 720px) {+ html, body { overflow: auto; }+ .wb-app {+ grid-template-columns: 1fr;+ grid-template-rows: var(--wb-bar) auto minmax(58vh, 1fr) auto;+ height: auto;+ min-height: 100dvh;+ }+ .wb-rail {+ grid-row: 4;+ flex-direction: row;+ justify-content: space-around;+ position: sticky;+ bottom: 0;+ z-index: 10;+ border-right: 0;+ border-top: 1px solid var(--wb-line);+ padding: 4px 8px calc(4px + env(safe-area-inset-bottom));+ }+ .wb-main { grid-row: 2; min-height: 58vh; }+ .wb-side { grid-row: 3; border-right: 0; border-top: 1px solid var(--wb-line); }+ .wb-view { grid-column: 1; grid-row: 2 / 4; }+ .wb-flows { grid-template-columns: 1fr; }+ .wb-flow-list { border-right: 0; border-bottom: 1px solid var(--wb-line); grid-auto-flow: column; grid-auto-columns: max-content; overflow-x: auto; }+ .wb-card .wb-param { grid-template-columns: 1fr; }+ .wb-top-link.hide-sm { display: none; }+ .wb-hint-corner { display: none; }+}diff --git a/src/workbench/workflows.js b/src/workbench/workflows.jsnew file mode 100644index 000000000..47b61ce8a--- /dev/null+++ b/src/workbench/workflows.js@@ -0,0 +1,373 @@+// Workflow model for the Workbench: node types, the built-in templates, chain+// validation, and per-browser persistence.+//+// A workflow is a typed chain. Every node has at most one input and one output+// port, typed `image` or `mesh`, so a valid workflow is a single path from the+// Image source to Add to Scene in which every wire joins matching types.++export const NODE_TYPES = {+ image: {+ label: 'Image',+ in: null,+ out: 'image',+ locked: true,+ blurb: 'The photo to reconstruct, or a text prompt the server turns into a reference image.',+ params: [],+ },+ rembg: {+ label: 'Remove Background',+ in: 'image',+ out: 'image',+ blurb: 'Cuts the subject out on a GPU worker before reconstruction.',+ params: [+ {+ key: 'model',+ label: 'Model',+ type: 'select',+ default: 'birefnet',+ options: [+ ['birefnet', 'BiRefNet'],+ ['isnet', 'ISNet'],+ ['u2net', 'U2-Net'],+ ['u2net_human_seg', 'U2-Net human'],+ ],+ },+ ],+ },+ generate: {+ label: 'Generate Mesh',+ in: 'image',+ out: 'mesh',+ locked: true,+ blurb: 'Reconstructs a textured GLB on the platform GPU lanes.',+ params: [+ { key: 'backend', label: 'Engine', type: 'lane', default: 'auto' },+ {+ key: 'tier',+ label: 'Quality',+ type: 'select',+ default: 'standard',+ options: [+ ['draft', 'Draft (fast)'],+ ['standard', 'Standard'],+ ['high', 'High ($THREE holders)'],+ ],+ },+ {+ key: 'resolution',+ label: 'Resolution',+ type: 'select',+ default: '',+ hint: 'TRELLIS.2 voxel grid',+ options: [+ ['', 'Auto'],+ ['512', '512'],+ ['1024', '1024'],+ ['1536', '1536'],+ ],+ },+ { key: 'target_polycount', label: 'Face budget', type: 'number', default: '', min: 100, max: 500000, step: 1000, placeholder: 'Auto' },+ {+ key: 'texture_size',+ label: 'Texture',+ type: 'select',+ default: '',+ options: [+ ['', 'Auto'],+ ['512', '512 px'],+ ['1024', '1024 px'],+ ['2048', '2048 px'],+ ['4096', '4096 px'],+ ],+ },+ {+ key: 'output_format',+ label: 'Compression',+ type: 'select',+ default: 'glb',+ options: [+ ['glb', 'None'],+ ['glb-meshopt', 'Meshopt'],+ ['glb-draco', 'Draco'],+ ],+ },+ { key: 'seed', label: 'Seed', type: 'seed', default: '' },+ ],+ },+ restyle: {+ label: 'Restyle Materials',+ in: 'mesh',+ out: 'mesh',+ blurb: 'Rewrites the PBR materials from a plain-language instruction.',+ params: [{ key: 'instruction', label: 'Look', type: 'text', default: 'brushed steel', maxLength: 300 }],+ },+ remesh: {+ label: 'Remesh',+ in: 'mesh',+ out: 'mesh',+ blurb: 'Server-side retopology to a clean triangle, quad or low-poly mesh.',+ params: [+ {+ key: 'mode',+ label: 'Topology',+ type: 'select',+ default: 'triangle',+ options: [+ ['triangle', 'Triangles'],+ ['quad', 'Quads'],+ ['lowpoly', 'Low poly'],+ ],+ },+ { key: 'target_faces', label: 'Faces', type: 'number', default: 20000, min: 1000, max: 500000, step: 1000 },+ ],+ },+ decimate: {+ label: 'Decimate',+ in: 'mesh',+ out: 'mesh',+ blurb: 'In-browser edge-collapse simplification. Instant, undoable.',+ params: [{ key: 'ratio', label: 'Keep', type: 'range', default: 0.5, min: 0.05, max: 0.95, step: 0.05, format: 'percent' }],+ },+ smooth: {+ label: 'Smooth',+ in: 'mesh',+ out: 'mesh',+ blurb: 'In-browser Taubin smoothing that does not shrink the mesh.',+ params: [{ key: 'iterations', label: 'Passes', type: 'range', default: 4, min: 1, max: 20, step: 1 }],+ },+ rig: {+ label: 'Auto-Rig',+ in: 'mesh',+ out: 'mesh',+ blurb: 'Adds a skeleton and skin weights so the model can animate.',+ params: [],+ },+ output: {+ label: 'Add to Scene',+ in: 'mesh',+ out: null,+ locked: true,+ blurb: 'Loads the result into the viewport and the history.',+ params: [],+ },+};++/** Node types offered in the editor palette, in display order. */+export const PALETTE = ['rembg', 'restyle', 'remesh', 'decimate', 'smooth', 'rig'];++export function defaultParams(type) {+ return Object.fromEntries(NODE_TYPES[type].params.map((p) => [p.key, p.default]));+}++let seq = 0;+export function newNodeId() {+ seq += 1;+ return `n${Date.now().toString(36)}${seq}`;+}++function chain(name, types, overrides = {}) {+ const nodes = types.map((type, i) => ({+ id: `${type}-${i}`,+ type,+ x: 40 + i * 236,+ y: 90 + (i % 2) * 44,+ enabled: true,+ collapsed: false,+ params: { ...defaultParams(type), ...(overrides[type] || {}) },+ }));+ const edges = nodes.slice(1).map((n, i) => ({ from: nodes[i].id, to: n.id }));+ return { name, nodes, edges };+}++export const TEMPLATES = [+ { id: 'image-to-3d', ...chain('Image to 3D', ['image', 'generate', 'output']) },+ {+ id: 'game-ready',+ ...chain('Game-ready prop', ['image', 'generate', 'decimate', 'smooth', 'output'], {+ generate: { tier: 'draft', output_format: 'glb-meshopt' },+ decimate: { ratio: 0.35 },+ smooth: { iterations: 2 },+ }),+ },+ { id: 'rigged-character', ...chain('Rigged character', ['image', 'rembg', 'generate', 'rig', 'output']) },+ { id: 'retopo', ...chain('Clean quad retopo', ['image', 'generate', 'remesh', 'output'], { remesh: { mode: 'quad', target_faces: 12000 } }) },+ { id: 'restyled', ...chain('Restyled prop', ['image', 'generate', 'restyle', 'output'], { restyle: { instruction: 'polished gold' } }) },+];++/**+ * Validate a workflow and resolve its run order.+ * @returns {{ ok: boolean, order: object[], errors: {nodeId?: string, message: string}[] }}+ */+export function validate(flow) {+ const errors = [];+ const byId = new Map(flow.nodes.map((n) => [n.id, n]));+ const outgoing = new Map();+ const incoming = new Map();+ for (const e of flow.edges) {+ const a = byId.get(e.from);+ const b = byId.get(e.to);+ if (!a || !b) continue;+ if (outgoing.has(a.id)) errors.push({ nodeId: a.id, message: `${NODE_TYPES[a.type].label} feeds more than one node.` });+ if (incoming.has(b.id)) errors.push({ nodeId: b.id, message: `${NODE_TYPES[b.type].label} has more than one input.` });+ outgoing.set(a.id, b);+ incoming.set(b.id, a);+ const outT = NODE_TYPES[a.type].out;+ const inT = NODE_TYPES[b.type].in;+ if (outT !== inT) {+ errors.push({+ nodeId: b.id,+ message: `${NODE_TYPES[b.type].label} takes ${inT || 'no input'}, but ${NODE_TYPES[a.type].label} outputs ${outT}.`,+ });+ }+ }+ const sources = flow.nodes.filter((n) => n.type === 'image');+ const sinks = flow.nodes.filter((n) => n.type === 'output');+ if (sources.length !== 1) errors.push({ message: sources.length ? 'Use exactly one Image node.' : 'Add an Image node as the source.' });+ if (sinks.length !== 1) errors.push({ message: sinks.length ? 'Use exactly one Add to Scene node.' : 'Add an Add to Scene node as the output.' });+ if (!flow.nodes.some((n) => n.type === 'generate')) errors.push({ message: 'Add a Generate Mesh node to turn the image into a mesh.' });++ const order = [];+ if (sources.length === 1) {+ const seen = new Set();+ let cur = sources[0];+ while (cur && !seen.has(cur.id)) {+ seen.add(cur.id);+ order.push(cur);+ cur = outgoing.get(cur.id);+ }+ if (cur) errors.push({ nodeId: cur.id, message: 'The chain loops back on itself.' });+ if (sinks.length === 1 && !seen.has(sinks[0].id)) {+ errors.push({ nodeId: sinks[0].id, message: 'Add to Scene is not connected to the Image chain.' });+ }+ for (const n of flow.nodes) {+ if (!seen.has(n.id) && n.type !== 'output') {+ errors.push({ nodeId: n.id, message: `${NODE_TYPES[n.type].label} is not connected.` });+ }+ }+ }+ return { ok: errors.length === 0, order, errors };+}++/** Insert a new node into a valid chain just before Add to Scene, type permitting. */+export function insertNode(flow, type, at) {+ const node = { id: newNodeId(), type, x: at?.x ?? 60, y: at?.y ?? 260, enabled: true, collapsed: false, params: defaultParams(type) };+ flow.nodes.push(node);+ const { ok, order } = validate({ ...flow, nodes: flow.nodes.filter((n) => n !== node) });+ if (!ok) return node;+ const t = NODE_TYPES[type];+ for (let i = order.length - 1; i > 0; i--) {+ const prev = order[i - 1];+ const next = order[i];+ if (NODE_TYPES[prev.type].out === t.in && t.out === NODE_TYPES[next.type].in) {+ flow.edges = flow.edges.filter((e) => !(e.from === prev.id && e.to === next.id));+ flow.edges.push({ from: prev.id, to: node.id }, { from: node.id, to: next.id });+ if (at == null) {+ node.x = next.x;+ node.y = next.y + 150;+ }+ break;+ }+ }+ return node;+}++/** Remove a node and stitch its neighbours together when the types allow it. */+export function removeNode(flow, nodeId) {+ const into = flow.edges.find((e) => e.to === nodeId);+ const outOf = flow.edges.find((e) => e.from === nodeId);+ flow.nodes = flow.nodes.filter((n) => n.id !== nodeId);+ flow.edges = flow.edges.filter((e) => e.from !== nodeId && e.to !== nodeId);+ if (into && outOf) {+ const a = flow.nodes.find((n) => n.id === into.from);+ const b = flow.nodes.find((n) => n.id === outOf.to);+ if (a && b && NODE_TYPES[a.type].out === NODE_TYPES[b.type].in) flow.edges.push({ from: a.id, to: b.id });+ }+}++/** Lay a valid chain out left to right. */+export function tidy(flow) {+ const { order } = validate(flow);+ const placed = new Set();+ order.forEach((n, i) => {+ n.x = 40 + i * 236;+ n.y = 90 + (i % 2) * 44;+ placed.add(n.id);+ });+ flow.nodes+ .filter((n) => !placed.has(n.id))+ .forEach((n, i) => {+ n.x = 40 + i * 236;+ n.y = 300;+ });+}++const STORE_KEY = 'wb:workflows';+const ACTIVE_KEY = 'wb:active-workflow';++function clone(v) {+ return JSON.parse(JSON.stringify(v));+}++/** Fill params added in later releases so an older saved workflow still runs. */+function migrate(flow) {+ for (const n of flow.nodes) {+ if (!NODE_TYPES[n.type]) continue;+ n.params = { ...defaultParams(n.type), ...(n.params || {}) };+ n.enabled = n.enabled !== false;+ }+ flow.nodes = flow.nodes.filter((n) => NODE_TYPES[n.type]);+ return flow;+}++export function loadWorkflows() {+ try {+ const saved = JSON.parse(localStorage.getItem(STORE_KEY) || 'null');+ if (Array.isArray(saved) && saved.length) return saved.map(migrate);+ } catch {+ // Unreadable storage falls through to the templates.+ }+ return TEMPLATES.map(clone);+}++export function saveWorkflows(flows) {+ try {+ localStorage.setItem(STORE_KEY, JSON.stringify(flows));+ } catch {+ // Storage full or blocked: the session keeps working from memory.+ }+}++export function loadActiveId(flows) {+ let id = null;+ try {+ id = localStorage.getItem(ACTIVE_KEY);+ } catch {+ id = null;+ }+ return flows.some((f) => f.id === id) ? id : flows[0].id;+}++export function saveActiveId(id) {+ try {+ localStorage.setItem(ACTIVE_KEY, id);+ } catch {+ // Non-persistent session; selection still applies.+ }+}++export function resetWorkflows() {+ try {+ localStorage.removeItem(STORE_KEY);+ localStorage.removeItem(ACTIVE_KEY);+ } catch {+ // Nothing persisted to clear.+ }+ return TEMPLATES.map(clone);+}++export function duplicateWorkflow(flow, name) {+ const copy = clone(flow);+ copy.id = `wf-${Date.now().toString(36)}`;+ copy.name = name;+ return copy;+}