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(forge-desktop): import the MIT-licensed Modly desktop app as the base for a local image-to-3D client
nirholascd1f3d74ef56
diff --git a/apps/forge-desktop/.gitignore b/apps/forge-desktop/.gitignorenew file mode 100644index 000000000..0afebef0f--- /dev/null+++ b/apps/forge-desktop/.gitignore@@ -0,0 +1,45 @@+node_modules/+out/+dist/+install.bat+launch.bat++# Generated at build time by scripts/download-python-embed.js+resources/python-embed/+resources/get-pip.py++# Python+api/__pycache__/+api/**/__pycache__/+api/*.pyc+api/**/*.pyc+api/.venv/+api/venv/+tools/modly-cli/__pycache__/+.hermes-e2e/++# Models (heavy, downloaded at runtime)+/models/++# Logs+*.log+npm-debug.log*++# OS+.DS_Store+Thumbs.db++# IDE+.vscode/+.idea/++# Env+.env+.env.local++# TypeScript incremental build output+*.tsbuildinfo++# Local dev helpers+install.bat+launch.batdiff --git a/apps/forge-desktop/CONTRIBUTING.md b/apps/forge-desktop/CONTRIBUTING.mdnew file mode 100644index 000000000..20f6137f6--- /dev/null+++ b/apps/forge-desktop/CONTRIBUTING.md@@ -0,0 +1,48 @@+# Contributing to Modly++Thanks for wanting to help out! You don't need write access to the repository to+pick up a ticket, work on it, and ship a fix — here's how the flow works.++## Finding something to work on++- Browse [open issues](https://github.com/lightningpixel/modly/issues) or the+ [project board](https://github.com/users/lightningpixel/projects/1).+- Issues labeled `good first issue` are a good place to start if you're new to+ the codebase. See [`CLAUDE.md`](./CLAUDE.md) for an architecture overview.++## Claiming a ticket++Comment **`/assign`** on the issue you want to work on. A bot will assign it to+you automatically — no repo permissions required.++- Only one person can be assigned to an issue at a time. If it's already+ assigned, ask the assignee first or wait for them to release it.+- No longer working on it? Comment **`/unassign`** to free it up for someone+ else.++This keeps the [project board](https://github.com/users/lightningpixel/projects/1)+honest: an assigned issue moves to **In progress** automatically, so anyone+looking at the board can see what's actively being worked on.++## Submitting your work++1. **Fork** the repository and create a branch for your change.+2. Make your change. Keep it focused — one issue, one PR.+3. Run the checks locally before opening a PR:+ ```bash+ npm run lint+ npm run test+ ```+4. Open a **pull request** against `dev`. Include `Closes #<issue-number>` in+ the PR description so it's linked to the ticket and closes it automatically+ on merge.++Opening a PR from your fork moves the linked issue to **Ready to review** on+the board. Once a maintainer approves the review, it moves to **Ready to+test**; once merged, it moves to **Done**.++## Getting help++If something in an issue is unclear, ask in a comment on the issue itself+before starting — it's cheaper to clarify scope up front than to redo work+later.diff --git a/apps/forge-desktop/LICENSE b/apps/forge-desktop/LICENSEnew file mode 100644index 000000000..0b99c1304--- /dev/null+++ b/apps/forge-desktop/LICENSE@@ -0,0 +1,29 @@+MIT License++Copyright (c) 2026 Lightning Pixel++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.++---++If you fork this project and build your own application from it, you must+credit the original project and its creator in your app's UI or documentation:++ Based on Modly (https://github.com/lightningpixel/modly)+ by Lightning Pixel (https://github.com/lightningpixel)diff --git a/apps/forge-desktop/README.md b/apps/forge-desktop/README.mdnew file mode 100644index 000000000..04eb14ea1--- /dev/null+++ b/apps/forge-desktop/README.md@@ -0,0 +1,358 @@+<p align="center">+ <img src="resources/icons/icon.png" width="96" alt="Modly logo" />+</p>++# Modly++**Local, open source, AI-powered image-to-3D mesh generation.**+Turn any photo into a 3D model using open source AI models running entirely on your GPU.+Modly is a desktop application for Windows, Linux, and Apple Silicon macOS.++> Created by [Lightning Pixel](https://github.com/lightningpixel)++<p align="center">+ <img src="docs/app-screenshot.png" alt="Modly screenshot" />+</p>++---+++## Download++Head to the [Releases](../../releases/latest) page to download the latest installer for Windows, Linux, or Apple Silicon macOS.++Alternatively, you can clone the repository and run the app directly without installing:++```bash+# Windows+launch.bat++# Linux / macOS+./launch.sh+```++---++++## Getting started++### 1. Install JS dependencies++```bash+npm install+```++### 2. Set up Python backend++```bash+cd api+python -m venv .venv+.venv\Scripts\activate # Windows+source .venv/bin/activate # Linux / macOS+pip install -r requirements.txt+```++### 3. Run in development++```bash+npm run dev+```++### 4. Test++```bash+npm test+./node_modules/.bin/tsc --noEmit -p tsconfig.node.json+npm run build+```++## Platform notes++- AMD GPUs are supported through ROCm on Linux and Windows: a Radeon card is detected+ automatically and extensions are steered to ROCm PyTorch wheels, with no ROCm install+ required. See [docs/running-on-amd-rocm.md](docs/running-on-amd-rocm.md).+- macOS support targets Apple Silicon only.+- macOS uses native window controls. Windows and Linux keep the existing custom controls.+- The top bar includes a live RAM indicator sourced from the main process.+- Workflow wiring is validated before run; invalid graphs stay in place and surface inline/toast warnings instead of dropping the current mesh view.+- Package Apple Silicon macOS with `npm run package:mac`.+- Imported meshes can be smoothed and decimated in-app; optimized results are written back into the workspace.++---++## Extension system++Modly supports external model and process extensions. Each extension is a GitHub repository containing a `manifest.json` plus the runtime entry files required by its type.++### Official extensions++| Extension | Model | URL |+|-----------|-------|-----|+| [modly-hunyuan3d-mini-extension](https://github.com/lightningpixel/modly-hunyuan3d-mini-extension) | Hunyuan3D 2 Mini | https://github.com/lightningpixel/modly-hunyuan3d-mini-extension |+| [modly-hunyuan3d-mini-turbo-extension](https://github.com/lightningpixel/modly-hunyuan3d-mini-turbo-extension) | Hunyuan3D 2 Mini Turbo | https://github.com/lightningpixel/modly-hunyuan3d-mini-turbo-extension |+| [modly-hunyuan3d-mini-fast-extension](https://github.com/lightningpixel/modly-hunyuan3d-mini-fast-extension) | Hunyuan3D 2 Mini Fast | https://github.com/lightningpixel/modly-hunyuan3d-mini-fast-extension |+| [modly-triposg-extension](https://github.com/lightningpixel/modly-triposg-extension) | TripoSG | https://github.com/lightningpixel/modly-triposg-extension |+| [modly-trellis2-gguf-extension](https://github.com/lightningpixel/modly-trellis2-gguf-extension) | Trellis2 GGUF | https://github.com/lightningpixel/modly-trellis2-gguf-extension |++### How to install an extension++**1.** Go to the **Models** page and click **Install from GitHub**.++++**2.** Enter the HTTPS URL of the extension repository and confirm.++++**3.** If the extension exposes model nodes, download the model or one of its variants. Process extensions are ready once installation and setup complete.++++### Multiple Hugging Face repositories per model node++A model node whose weights are split across repositories can declare+`model_sources`. Modly validates every source, downloads them sequentially in+one Models-page action, and considers the node installed only when every+declared check exists.++```json+{+ "id": "generate",+ "model_sources": [+ {+ "id": "primary",+ "provider": "huggingface",+ "repo_id": "org/main-model",+ "destination": ".",+ "checks": ["model.safetensors"]+ },+ {+ "id": "encoder",+ "provider": "huggingface",+ "repo_id": "org/encoder",+ "revision": "v1.0",+ "destination": "auxiliary/encoder",+ "include_prefixes": ["config.json", "model.safetensors"],+ "checks": ["config.json", "model.safetensors"]+ }+ ]+}+```++`destination`, filters, and checks use safe POSIX paths relative to the node's+model directory. Every check must name a regular, non-empty file included by+that source's filters; invalid plans fail before any file is downloaded. Pin a+tag or commit in `revision` when reproducible weights are required. The only+supported provider is `huggingface`. Existing nodes that use `hf_repo`,+`download_check`, `hf_include_prefixes`, and `hf_skip_prefixes` keep their+original behavior.++### Shared weights inside one model extension++Multi-node model extensions can declare extension-scoped `weight_groups` and+reference them from any sibling node. Shared files are downloaded once under+`<models-dir>/<extension-id>/_shared/<group-id>`, while node-specific+`model_sources` stay under the node's existing model directory.++```json+{+ "id": "pixal3d",+ "type": "model",+ "weight_groups": [+ {+ "id": "pixal3d-base",+ "model_sources": [+ {+ "id": "base",+ "provider": "huggingface",+ "repo_id": "TencentARC/Pixal3D",+ "revision": "<pinned-revision>",+ "destination": ".",+ "checks": ["pipeline.json"]+ }+ ]+ }+ ],+ "nodes": [+ {+ "id": "generate",+ "weight_groups": ["pixal3d-base"]+ },+ {+ "id": "worldsculpt",+ "weight_groups": ["pixal3d-base"],+ "model_sources": [+ {+ "id": "adapter",+ "provider": "huggingface",+ "repo_id": "AlayaLab/WorldSculpt",+ "revision": "<pinned-revision>",+ "destination": ".",+ "checks": ["model.safetensors"]+ }+ ]+ }+ ]+}+```++At runtime, `MODEL_DIR` remains the selected node's private directory.+Subprocess extensions also receive `MODEL_ID`, `MODEL_NODE_ID`, and a JSON+`SHARED_MODEL_DIRS` map in their environment. Both direct and subprocess generator+instances receive `MODEL_ID`, `MODEL_NODE_ID`, and the resolved mapping in+`shared_model_dirs` before `load()`. Direct generators use these instance attributes,+not process-global environment variables, to distinguish sibling nodes.+Shared groups are installed through their dependent nodes; the drawer exposes+shared-group status and explicit removal. Removing private node data never removes a shared group;+shared-group removal is a separate action that identifies every affected node.++### Separately installable weight variants++A model node that publishes the same weights in several variants (quantizations,+precisions…) can declare `weight_variants` next to `hf_repo`. The Extensions page+lists every variant under the node, and each one is downloaded or deleted on its own.++```json+{+ "id": "generate",+ "hf_repo": "org/model-gguf",+ "download_check": "pipeline.json",+ "hf_include_prefixes": ["pipeline.json", "encoder/", "dit/"],+ "params_schema": [+ {+ "id": "quant",+ "label": "Quantization",+ "type": "select",+ "default": "Q5_K_M",+ "options": [+ { "value": "Q4_K_M", "label": "Q4_K_M" },+ { "value": "Q5_K_M", "label": "Q5_K_M" }+ ]+ }+ ],+ "weight_variants": {+ "param": "quant",+ "default": "Q5_K_M",+ "options": [+ {+ "id": "Q4_K_M",+ "label": "Q4_K_M",+ "size_gb": 2.4,+ "vram_gb": 6,+ "include_prefixes": ["dit/model_Q4_K_M.gguf"],+ "checks": ["dit/model_Q4_K_M.gguf"]+ },+ {+ "id": "Q5_K_M",+ "include_prefixes": ["dit/model_Q5_K_M.gguf"],+ "checks": ["dit/model_Q5_K_M.gguf"]+ }+ ]+ }+}+```++- `param` names the `params_schema` select whose values are the variant ids. That+ param must exist on the node (or on the extension, as its fallback), and when it+ declares `options` they must cover every variant id.+- `size_gb` (download size) and `vram_gb` (approximate VRAM the variant needs) are+ optional positive numbers, shown next to the variant when present.+- Every install downloads the shared files (`hf_include_prefixes`, with every+ variant's files excluded automatically) plus one variant: the one asked for, or the+ `default` one — the first option when `default` is omitted. Files already complete+ on disk are skipped, so adding a second variant only fetches that variant.+ Only declared variants are excluded from the shared pass: keep+ `hf_include_prefixes` narrow enough that a variant the repository publishes but+ the manifest does not declare (e.g. an extra `dit/model_Q8_0.gguf`) is not+ downloaded with every install.+- A variant is installed when all of its `checks` exist; the node is installed once+ its `download_check` and at least one variant are present.+- Generation fails with an explicit message when the selected variant is not+ installed, and the node's selector labels those options `(not installed)`.+- `include_prefixes` and `checks` are safe POSIX paths relative to the node's model+ directory. Prefixes of two variants cannot overlap, `download_check` stays outside+ every variant, and `weight_variants` cannot be combined with `model_sources`.++---++## Workflows+Start with a basic workflow first. For example, on the "Workflows" tab, try: Image -> Generate Mesh -> Add to Scene. Make sure there is a connection between each of the steps. Go to the "Generate" tab, make sure the workflow is selected, then click on "Generate 3D Model". Click on "Settings/Logs/Errors" to see any issues.++Model extensions may also declare `scene` as a node input or output. A scene is+a workspace directory containing `scene-manifest.json` with schema+`modly.scene-manifest.v1`; it is not an arbitrary JSON file. Use the **Load+Scene** workflow node to select and validate an existing scene directory.+Scene-capable generators implement `generate_artifact(input_kind,+artifact_path, ...)`; legacy image generators and `POST /generate/from-image`+remain unchanged. The generic `POST /generate/from-artifact` boundary currently+accepts only `scene`, leaving future artifact kinds to separate reviewed changes.+For this first contract, `scene` is model-only and must be declared as the single+`input` value (not inside `inputs`); process and mixed-input scene nodes are rejected.+Model nodes may still accept multiple images and produce a scene.+++## Modly CLI++Agents and scripts can call a running Modly desktop app without using the UI via the stdlib-only CLI. The CLI is a thin helper over Modly's canonical automation concepts and keeps final machine-readable JSON on stdout:++```bash+python tools/modly-cli/agent.py health+python tools/modly-cli/agent.py model list+python tools/modly-cli/agent.py workflow-run status <run_id>+python tools/modly-cli/agent.py generate --image ./input.png --output ./export.glb+```++Canonical commands are `health`, `model`, `workflow-run`, `capability`, and `process-run`. The friendly `generate` command starts `POST /workflow-runs/from-image`, polls the returned run, exports the final mesh when requested, and includes recovery metadata such as `workflow-run status ...` and `workflow-run cancel ...` in the JSON response.++Compatibility and helper surfaces are intentionally separated: `legacy` wraps old `/generate/*` job endpoints, `dev serve-api` / `dev ensure-server` start only the FastAPI backend and do not prove Electron/Desktop bridge readiness, and `experimental comfy-image` / `experimental generate-from-workflow` are external ComfyUI orchestration helpers rather than the canonical Modly agent contract. Hidden helper aliases such as `status`, `export`, and `batch` remain parseable for scripts, but they are not presented as canonical root commands.++`experimental generate-from-workflow --workflow <name> --output <path>` treats `--output` as the final artifact location. When the ComfyUI workflow produces a downloadable 3D asset, the CLI downloads it directly; image-only workflows remain a compatibility path through Modly image-to-3D generation.++See `tools/modly-cli/SKILL.md` for the agent workflow and output contract.++---++### Community++Join the [Discord server](https://discord.gg/BvjDCvS3yr) to stay up to date with the latest news, report bugs, and share feedback.++---++## Sponsors++<p align="center">+ Thanks to our early sponsors for believing in Modly and helping make local AI 3D generation more accessible.+</p>++<p align="center">+ <kbd>+ <img src="https://images.weserv.nl/?url=github.com/DrHepa.png&w=96&h=96&fit=cover&mask=circle" width="40" height="40" alt="DrHepa" />+ <br />+ <sub><a href="https://github.com/DrHepa">DrHepa</a></sub>+ </kbd>+ + <kbd>+ <img src="https://images.weserv.nl/?url=github.com/benjapenjamin.png&w=96&h=96&fit=cover&mask=circle" width="40" height="40" alt="benjapenjamin" />+ <br />+ <sub><a href="https://github.com/benjapenjamin">benjapenjamin</a></sub>+ </kbd>+ + <kbd>+ <img src="https://images.weserv.nl/?url=github.com/iammojogo-sudo.png&w=96&h=96&fit=cover&mask=circle" width="40" height="40" alt="iammojogo-sudo" />+ <br />+ <sub><a href="https://github.com/iammojogo-sudo">iammojogo-sudo</a></sub>+ </kbd>+</p>++---++## License++MIT License — see [LICENSE](LICENSE) for details.++**If you fork this project and build your own app from it, you must credit the original project and its creator:**++> Based on [Modly](https://github.com/lightningpixel/modly) by [Lightning Pixel](https://github.com/lightningpixel)++This is a requirement of the MIT license attribution clause. Please keep this credit visible in your app's UI or documentation.diff --git a/apps/forge-desktop/api/README.md b/apps/forge-desktop/api/README.mdnew file mode 100644index 000000000..cdcd4d6b0--- /dev/null+++ b/apps/forge-desktop/api/README.md@@ -0,0 +1,39 @@+# Modly — FastAPI Backend++Local Python server started and managed by Electron.++## Setup++```bash+cd api+python -m venv .venv+# Windows+.venv\Scripts\activate+# macOS/Linux+source .venv/bin/activate++pip install -r requirements.txt+```++## Run (development)++```bash+uvicorn main:app --host 127.0.0.1 --port 8765 --reload+```++## Key endpoints++| Method | Path | Description |+|--------|------|-------------|+| GET | `/health` | Health check (used by Electron to detect readiness) |+| GET | `/model/status` | Model download / load status |+| GET | `/model/download` | SSE stream of download progress |+| POST | `/generate/from-image` | Start image-to-3D job |+| POST | `/generate/from-artifact` | Start a typed-artifact model job (`scene` only) |+| GET | `/generate/status/{job_id}` | Poll job status |++## Model++Default: **TripoSR** (`stabilityai/TripoSR`, ~2.4 GB)+Downloaded on first launch to `~/.modly/models/TripoSR/`.+To change model: edit `services/model_manager.py`.diff --git a/apps/forge-desktop/api/main.py b/apps/forge-desktop/api/main.pynew file mode 100644index 000000000..958ba2a02--- /dev/null+++ b/apps/forge-desktop/api/main.py@@ -0,0 +1,71 @@+"""+Modly FastAPI backend.+Runs locally within the Electron app to provide AI inference endpoints.+"""+import logging+from contextlib import asynccontextmanager+from fastapi import FastAPI+from fastapi.middleware.cors import CORSMiddleware+from fastapi.responses import FileResponse+from fastapi import HTTPException++from services.stdio_utf8 import ensure_utf8_stdio+ensure_utf8_stdio() # must run before any print/logging hits the pipe++from routers import generation, model, optimize, status, settings, extensions, export, workflow_runs, agent, llm+++@asynccontextmanager+async def lifespan(app: FastAPI):+ # Startup: initialize the registry (instantiates all adapters)+ from services.generator_registry import generator_registry+ generator_registry.initialize()+ yield+ # Shutdown: unload all models and stop the local LLM server+ generator_registry.unload_all()+ from services.llm_server import llama_pool+ llama_pool.unload_all(force=True)+++class _StatusFilter(logging.Filter):+ def filter(self, record):+ return "/generate/status/" not in record.getMessage()++logging.getLogger("uvicorn.access").addFilter(_StatusFilter())+++app = FastAPI(+ title="Modly API",+ version="0.4.3",+ lifespan=lifespan,+)++app.add_middleware(+ CORSMiddleware,+ allow_origins=["*"],+ allow_methods=["*"],+ allow_headers=["*"],+ # drei's SplatLoader reads Content-Length to size its buffers; cross-origin+ # JS can only see it when the server explicitly exposes the header.+ expose_headers=["Content-Length"],+)++app.include_router(status.router)+app.include_router(settings.router)+app.include_router(model.router, prefix="/model")+app.include_router(generation.router, prefix="/generate")+app.include_router(optimize.router, prefix="/optimize")+app.include_router(extensions.router, prefix="/extensions")+app.include_router(export.router, prefix="/export")+app.include_router(workflow_runs.router, prefix="/workflow-runs")+app.include_router(agent.router)+app.include_router(llm.router, prefix="/llm")++# Serve generated files from workspace — dynamic so path changes take effect immediately[email protected]("/workspace/{full_path:path}")+async def serve_workspace_file(full_path: str):+ import services.generator_registry as reg+ file_path = reg.WORKSPACE_DIR / full_path+ if not file_path.exists() or not file_path.is_file():+ raise HTTPException(status_code=404, detail="File not found")+ return FileResponse(str(file_path))diff --git a/apps/forge-desktop/api/mcp_server.py b/apps/forge-desktop/api/mcp_server.pynew file mode 100644index 000000000..fa9127cf2--- /dev/null+++ b/apps/forge-desktop/api/mcp_server.py@@ -0,0 +1,265 @@+"""+Modly MCP Server+Exposes Modly's capabilities as MCP tools for external agents (Claude Desktop, Codex CLI, etc.).++Usage:+ python mcp_server.py++Configuration in Claude Desktop (~/.config/claude/claude_desktop_config.json):+ {+ "mcpServers": {+ "modly": {+ "command": "python",+ "args": ["C:/path/to/modly/desktop/api/mcp_server.py"]+ }+ }+ }++Requires Modly's FastAPI backend to be running on http://localhost:8765.+"""++import asyncio+import mimetypes+import httpx+from mcp.server import Server+from mcp.server.stdio import stdio_server+from mcp.types import Tool, TextContent++API_BASE = "http://localhost:8765"++server = Server("modly")++[email protected]_tools()+async def list_tools() -> list[Tool]:+ return [+ Tool(+ name="modly_list_models",+ description="List all 3D generation models available in Modly (downloaded and ready to use).",+ inputSchema={"type": "object", "properties": {}},+ ),+ Tool(+ name="modly_switch_model",+ description="Switch the active 3D generation model in Modly.",+ inputSchema={+ "type": "object",+ "properties": {+ "model_id": {"type": "string", "description": "The model ID to activate."},+ },+ "required": ["model_id"],+ },+ ),+ Tool(+ name="modly_generate_from_image",+ description="Generate a 3D mesh from a 2D image file. Returns a job_id to track progress.",+ inputSchema={+ "type": "object",+ "properties": {+ "image_path": {+ "type": "string",+ "description": "Absolute path to the image file on disk.",+ },+ "model_id": {+ "type": "string",+ "description": "Which model to use. If omitted, uses the currently active model.",+ },+ "remesh": {+ "type": "string",+ "enum": ["quad", "triangle", "none"],+ "description": "Remesh strategy after generation. Default: quad.",+ },+ },+ "required": ["image_path"],+ },+ ),+ Tool(+ name="modly_get_generation_status",+ description="Poll the status of a 3D generation job. Call repeatedly until status is 'done' or 'error'.",+ inputSchema={+ "type": "object",+ "properties": {+ "job_id": {"type": "string", "description": "Job ID returned by modly_generate_from_image."},+ },+ "required": ["job_id"],+ },+ ),+ Tool(+ name="modly_decimate_mesh",+ description="Reduce the polygon count of a mesh using quadric edge collapse decimation.",+ inputSchema={+ "type": "object",+ "properties": {+ "path": {+ "type": "string",+ "description": "Workspace-relative path to the mesh (e.g. 'Default/mesh.glb').",+ },+ "target_faces": {+ "type": "integer",+ "description": "Target number of faces after decimation (minimum 100).",+ },+ },+ "required": ["path", "target_faces"],+ },+ ),+ Tool(+ name="modly_smooth_mesh",+ description="Apply Laplacian smoothing to a mesh. More iterations = smoother surface but less detail.",+ inputSchema={+ "type": "object",+ "properties": {+ "path": {+ "type": "string",+ "description": "Workspace-relative path to the mesh (e.g. 'Default/mesh.glb').",+ },+ "iterations": {+ "type": "integer",+ "description": "Number of smoothing iterations (1–20).",+ },+ },+ "required": ["path", "iterations"],+ },+ ),+ Tool(+ name="modly_import_mesh",+ description="Import a mesh file from disk into Modly's workspace (.glb, .obj, .stl, .ply).",+ inputSchema={+ "type": "object",+ "properties": {+ "path": {+ "type": "string",+ "description": "Absolute path to the mesh file on disk.",+ },+ },+ "required": ["path"],+ },+ ),+ Tool(+ name="modly_unload_models",+ description="Unload all 3D generation models from GPU VRAM. Useful before running VRAM-intensive tasks.",+ inputSchema={"type": "object", "properties": {}},+ ),+ Tool(+ name="modly_get_settings",+ description="Get the current Modly settings (models directory, workspace directory).",+ inputSchema={"type": "object", "properties": {}},+ ),+ ]++[email protected]_tool()+async def call_tool(name: str, arguments: dict) -> list[TextContent]:+ async with httpx.AsyncClient(timeout=60.0) as client:+ try:+ result = await _dispatch(client, name, arguments)+ except httpx.ConnectError:+ result = (+ "Cannot connect to Modly API at http://localhost:8765. "+ "Make sure Modly is running."+ )+ except httpx.HTTPStatusError as e:+ result = f"Modly API error {e.response.status_code}: {e.response.text[:300]}"+ except Exception as e:+ result = f"Error: {e}"++ return [TextContent(type="text", text=result)]+++async def _dispatch(client: httpx.AsyncClient, name: str, args: dict) -> str:+ if name == "modly_list_models":+ r = await client.get(f"{API_BASE}/model/all")+ r.raise_for_status()+ models = [m for m in r.json() if m.get("downloaded")]+ if not models:+ return "No models downloaded yet. Download one from the Models tab in Modly."+ return "\n".join(f"- {m['id']}: {m.get('name', m['id'])}" for m in models)++ elif name == "modly_switch_model":+ r = await client.post(f"{API_BASE}/model/switch", params={"model_id": args["model_id"]})+ r.raise_for_status()+ return f"Switched active model to: {args['model_id']}"++ elif name == "modly_generate_from_image":+ image_path: str = args["image_path"]+ with open(image_path, "rb") as f:+ img_bytes = f.read()+ mime = mimetypes.guess_type(image_path)[0] or "image/png"+ filename = image_path.replace("\\", "/").split("/")[-1]++ form_data = {+ "remesh": args.get("remesh", "quad"),+ }+ if args.get("model_id"):+ form_data["model_id"] = args["model_id"]++ r = await client.post(+ f"{API_BASE}/generate/from-image",+ files={"image": (filename, img_bytes, mime)},+ data=form_data,+ timeout=30.0,+ )+ r.raise_for_status()+ job_id = r.json()["job_id"]+ return (+ f"Generation started. Job ID: {job_id}\n"+ f"Use modly_get_generation_status with this ID to track progress."+ )++ elif name == "modly_get_generation_status":+ r = await client.get(f"{API_BASE}/generate/status/{args['job_id']}")+ r.raise_for_status()+ s = r.json()+ parts = [f"Status: {s['status']}", f"Progress: {s.get('progress', 0)}%"]+ if s.get("step"):+ parts.append(f"Step: {s['step']}")+ if s.get("output_url"):+ parts.append(f"Output: {s['output_url']}")+ if s.get("error"):+ parts.append(f"Error: {s['error']}")+ return " | ".join(parts)++ elif name == "modly_decimate_mesh":+ r = await client.post(+ f"{API_BASE}/optimize/mesh",+ json={"path": args["path"], "target_faces": args["target_faces"]},+ )+ r.raise_for_status()+ data = r.json()+ return f"Decimated mesh to {data.get('face_count', '?')} faces. New file: {data.get('url', '')}"++ elif name == "modly_smooth_mesh":+ r = await client.post(+ f"{API_BASE}/optimize/smooth",+ json={"path": args["path"], "iterations": args["iterations"]},+ )+ r.raise_for_status()+ data = r.json()+ return f"Smoothed mesh ({args['iterations']} iterations). New file: {data.get('url', '')}"++ elif name == "modly_import_mesh":+ r = await client.post(f"{API_BASE}/optimize/import-by-path", json={"path": args["path"]})+ r.raise_for_status()+ data = r.json()+ return f"Mesh imported. URL: {data.get('url', '')}"++ elif name == "modly_unload_models":+ r = await client.post(f"{API_BASE}/model/unload-all")+ r.raise_for_status()+ return "All 3D generation models unloaded from VRAM."++ elif name == "modly_get_settings":+ r = await client.get(f"{API_BASE}/settings/paths")+ r.raise_for_status()+ data = r.json()+ return f"Models directory: {data.get('models_dir')}\nWorkspace directory: {data.get('workspace_dir')}"++ else:+ return f"Unknown tool: {name}"+++async def main():+ async with stdio_server() as (read_stream, write_stream):+ await server.run(read_stream, write_stream, server.create_initialization_options())+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/apps/forge-desktop/api/requirements.txt b/apps/forge-desktop/api/requirements.txtnew file mode 100644index 000000000..975f19ca3--- /dev/null+++ b/apps/forge-desktop/api/requirements.txt@@ -0,0 +1,19 @@+# Web server+fastapi>=0.115.6+uvicorn[standard]==0.34.0+python-multipart==0.0.20++# Agent & MCP+httpx>=0.27.0+mcp>=1.0.0++# Mesh processing (optimize + export endpoints)+trimesh>=4.5.0+pymeshlab>=2023.12++# Model downloads (HuggingFace)+huggingface_hub>=0.27.0+hf_xet>=0.1.0++cryptography>=42.0.0+certifi>=2024.0.0diff --git a/apps/forge-desktop/api/resources/llm_catalog.json b/apps/forge-desktop/api/resources/llm_catalog.jsonnew file mode 100644index 000000000..928f4a2a3--- /dev/null+++ b/apps/forge-desktop/api/resources/llm_catalog.json@@ -0,0 +1,169 @@+[+ {+ "id": "qwen3.5-4b",+ "name": "Qwen 3.5 4B",+ "description": "Newest small Qwen. Tops independent tool-calling tests for its size and stays fast on modest GPUs.",+ "hf_repo": "unsloth/Qwen3.5-4B-GGUF",+ "hf_filename": "Qwen3.5-4B-Q4_K_M.gguf",+ "size_bytes": 2740937888,+ "quant": "Q4_K_M",+ "ctx": 16384,+ "vram_estimate_mb": 4600,+ "ngl_suggestion": 99,+ "tags": [+ "fast",+ "4b"+ ],+ "sampling": {+ "temperature": 0.7,+ "top_p": 0.8,+ "top_k": 20,+ "presence_penalty": 1.5+ }+ },+ {+ "id": "qwen3.5-9b",+ "name": "Qwen 3.5 9B",+ "description": "Best balance of reliability and speed on an 8 GB+ GPU. Noticeably steadier than 4B over long conversations.",+ "hf_repo": "unsloth/Qwen3.5-9B-GGUF",+ "hf_filename": "Qwen3.5-9B-Q4_K_M.gguf",+ "size_bytes": 5680522464,+ "quant": "Q4_K_M",+ "ctx": 16384,+ "vram_estimate_mb": 7600,+ "ngl_suggestion": 99,+ "tags": [+ "balanced",+ "9b"+ ],+ "sampling": {+ "temperature": 0.7,+ "top_p": 0.8,+ "top_k": 20,+ "presence_penalty": 1.5+ }+ },+ {+ "id": "qwen3-4b",+ "name": "Qwen 3 4B Instruct",+ "description": "Latest Qwen generation. Fast, excellent tool-calling for its size — the recommended starting point.",+ "hf_repo": "unsloth/Qwen3-4B-Instruct-2507-GGUF",+ "hf_filename": "Qwen3-4B-Instruct-2507-Q4_K_M.gguf",+ "size_bytes": 2497281120,+ "quant": "Q4_K_M",+ "ctx": 16384,+ "vram_estimate_mb": 4200,+ "ngl_suggestion": 99,+ "tags": [+ "fast",+ "4b",+ "default"+ ]+ },+ {+ "id": "qwen3-8b",+ "name": "Qwen 3 8B",+ "description": "Great quality/speed balance with hybrid thinking. Fits in 8 GB VRAM.",+ "hf_repo": "unsloth/Qwen3-8B-GGUF",+ "hf_filename": "Qwen3-8B-Q4_K_M.gguf",+ "size_bytes": 5027784512,+ "quant": "Q4_K_M",+ "ctx": 16384,+ "vram_estimate_mb": 7000,+ "ngl_suggestion": 99,+ "tags": [+ "balanced",+ "8b",+ "thinking"+ ]+ },+ {+ "id": "qwen3-14b",+ "name": "Qwen 3 14B",+ "description": "High quality with hybrid thinking (reasons before answering when useful). Needs ~11 GB VRAM.",+ "hf_repo": "unsloth/Qwen3-14B-GGUF",+ "hf_filename": "Qwen3-14B-Q4_K_M.gguf",+ "size_bytes": 9001753984,+ "quant": "Q4_K_M",+ "ctx": 16384,+ "vram_estimate_mb": 11000,+ "ngl_suggestion": 99,+ "tags": [+ "quality",+ "14b",+ "thinking"+ ]+ },+ {+ "id": "gpt-oss-20b",+ "name": "GPT-OSS 20B (OpenAI)",+ "description": "OpenAI's open-weight MoE (3.6B active params — fast for its size). Top-tier tool calling and reasoning. Best with 16 GB VRAM.",+ "hf_repo": "ggml-org/gpt-oss-20b-GGUF",+ "hf_filename": "gpt-oss-20b-MXFP4.gguf",+ "size_bytes": 12109566624,+ "quant": "MXFP4",+ "ctx": 16384,+ "vram_estimate_mb": 13500,+ "ngl_suggestion": 99,+ "tags": [+ "quality",+ "20b",+ "thinking",+ "moe"+ ]+ },+ {+ "id": "qwen3-vl-4b",+ "name": "Qwen 3 VL 4B (vision, light)",+ "description": "Small vision model — sees attached images while fitting in ~5 GB VRAM. Pick this over the 8B on smaller GPUs.",+ "hf_repo": "unsloth/Qwen3-VL-4B-Instruct-GGUF",+ "hf_filename": "Qwen3-VL-4B-Instruct-Q4_K_M.gguf",+ "hf_mmproj_filename": "mmproj-F16.gguf",+ "mmproj_size_bytes": 836180640,+ "size_bytes": 2497282336,+ "quant": "Q4_K_M",+ "ctx": 16384,+ "vram_estimate_mb": 4600,+ "ngl_suggestion": 99,+ "tags": [+ "vision",+ "4b",+ "fast"+ ]+ },+ {+ "id": "qwen3-vl-8b",+ "name": "Qwen 3 VL 8B (vision)",+ "description": "Sees images — the agent can look at attached pictures before picking a workflow. Needs ~8 GB VRAM.",+ "hf_repo": "unsloth/Qwen3-VL-8B-Instruct-GGUF",+ "hf_filename": "Qwen3-VL-8B-Instruct-Q4_K_M.gguf",+ "hf_mmproj_filename": "mmproj-F16.gguf",+ "mmproj_size_bytes": 1159030336,+ "size_bytes": 5027785568,+ "quant": "Q4_K_M",+ "ctx": 16384,+ "vram_estimate_mb": 7800,+ "ngl_suggestion": 99,+ "tags": [+ "vision",+ "8b"+ ]+ },+ {+ "id": "cadquery-coder-7b",+ "name": "CadQuery Coder 7B (CAD-specialized)",+ "description": "Qwen2.5-Coder-7B fine-tuned on CadQuery generation — best pick for the Text to CAD node. Community model, CC-BY-NC-SA license.",+ "hf_repo": "yuvit-batra/qwen2.5-coder-7b-cadquery-gguf",+ "hf_filename": "qwen2.5-coder-7b-cadquery-Q4_K_M.gguf",+ "size_bytes": 4680000000,+ "quant": "Q4_K_M",+ "ctx": 16384,+ "vram_estimate_mb": 6200,+ "ngl_suggestion": 99,+ "tags": [+ "code",+ "cad",+ "7b"+ ]+ }+]\ No newline at end of filediff --git a/apps/forge-desktop/api/routers/__init__.py b/apps/forge-desktop/api/routers/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/apps/forge-desktop/api/routers/agent.py b/apps/forge-desktop/api/routers/agent.pynew file mode 100644index 000000000..1fb389eb6--- /dev/null+++ b/apps/forge-desktop/api/routers/agent.py@@ -0,0 +1,641 @@+"""+Agent chat endpoint — runs a tool-use loop against Modly's API, on the managed+local llama.cpp server or any OpenAI-compatible provider.+"""+import asyncio+import json+import re+import uuid+from typing import Optional++import httpx+from fastapi import APIRouter+from pydantic import BaseModel, Field++from services import llm_server+from services.llm_server import llama_pool++router = APIRouter(prefix="/agent", tags=["agent"])++MODLY_API = "http://localhost:8765"++SYSTEM_PROMPT = """\+You are Modly's built-in AI assistant, specialized in 3D modeling and workflow automation.+You help users generate 3D models from images, optimize meshes, and manage workflows directly inside the Modly application.++## Available tools++- **list_models** — List all downloaded 3D generation models ready to use.+- **unload_models** — Unload all 3D generation models from GPU VRAM to free memory.+- **get_mesh_info** — Get info about the current mesh in the 3D viewer (path, triangle count).+- **decimate_mesh(path, target_faces)** — Reduce the polygon count of a mesh.+- **smooth_mesh(path, iterations)** — Apply Laplacian smoothing to a mesh.+- **get_generation_status(job_id)** — Poll the status of an ongoing 3D generation job.+- **list_workflows** — List all available workflows in Modly.+- **run_workflow(workflow_id)** — Execute a workflow in Modly by its ID. If the user attached an image in their message, it will automatically be used as the workflow's input image.+- **create_workflow(name, input_type, steps, description?)** — Create a new workflow from an ordered list of processing steps. Each step references an extension by its exact `id` and may override its params. The steps run in sequence, the output of one feeding the next. The input source is one of exactly three nodes — `image` (Image), `text` (Text), or `mesh` (Load 3D Mesh) — and an Add-to-Scene output node is appended automatically.++## Rules++- Always use tools to act on the scene — never just describe what you would do.+- If you need the current mesh path, call get_mesh_info first.+- If you need to run a workflow but don't know the ID, call list_workflows first.+- To create a workflow, ONLY use extension ids listed under "Available extensions" in the context. Never invent an id. Chain steps so each step's input type matches the previous step's output type.+- For a workflow's input, `input_type` MUST be exactly one of: `image`, `text`, or `mesh`. These map to the Image, Text, and Load 3D Mesh nodes. Never invent another input. Pick the one matching the first step's expected input.+- After each tool call, give a short one-sentence summary of what was done.+- Always reply in the same language the user is writing in.+- Be concise. No unnecessary explanations.\+"""++TOOLS = [+ {+ "type": "function",+ "function": {+ "name": "list_models",+ "description": "List all available 3D generation models that are downloaded and ready.",+ "parameters": {"type": "object", "properties": {}},+ },+ },+ {+ "type": "function",+ "function": {+ "name": "unload_models",+ "description": "Unload all 3D generation models from VRAM to free GPU memory.",+ "parameters": {"type": "object", "properties": {}},+ },+ },+ {+ "type": "function",+ "function": {+ "name": "get_mesh_info",+ "description": "Get information about the current mesh loaded in the 3D viewer (triangle count, path, etc.).",+ "parameters": {"type": "object", "properties": {}},+ },+ },+ {+ "type": "function",+ "function": {+ "name": "decimate_mesh",+ "description": "Reduce the polygon count of the current mesh using quadric edge collapse.",+ "parameters": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string",+ "description": "Workspace-relative path to the mesh file (e.g. 'Default/mesh.glb'). Use get_mesh_info to obtain it.",+ },+ "target_faces": {+ "type": "integer",+ "description": "Target number of faces after decimation.",+ },+ },+ "required": ["path", "target_faces"],+ },+ },+ },+ {+ "type": "function",+ "function": {+ "name": "smooth_mesh",+ "description": "Apply Laplacian smoothing to the current mesh.",+ "parameters": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string",+ "description": "Workspace-relative path to the mesh file. Use get_mesh_info to obtain it.",+ },+ "iterations": {+ "type": "integer",+ "description": "Number of smoothing iterations (1–20). More = smoother but loses detail.",+ },+ },+ "required": ["path", "iterations"],+ },+ },+ },+ {+ "type": "function",+ "function": {+ "name": "get_generation_status",+ "description": "Poll the status of an ongoing 3D generation job.",+ "parameters": {+ "type": "object",+ "properties": {+ "job_id": {"type": "string", "description": "Job ID returned by a previous generation call."},+ },+ "required": ["job_id"],+ },+ },+ },+ {+ "type": "function",+ "function": {+ "name": "list_workflows",+ "description": "List all workflows available in Modly.",+ "parameters": {"type": "object", "properties": {}},+ },+ },+ {+ "type": "function",+ "function": {+ "name": "run_workflow",+ "description": "Execute a Modly workflow by its ID. The workflow runs in the background; progress is shown in the app.",+ "parameters": {+ "type": "object",+ "properties": {+ "workflow_id": {"type": "string", "description": "The workflow ID to execute. Use list_workflows to get available IDs."},+ },+ "required": ["workflow_id"],+ },+ },+ },+ {+ "type": "function",+ "function": {+ "name": "create_workflow",+ "description": (+ "Create a new Modly workflow from an ordered list of steps. "+ "Each step references an extension by its exact id (see 'Available extensions' in context). "+ "Steps run in sequence; do not include the input itself as a step."+ ),+ "parameters": {+ "type": "object",+ "properties": {+ "name": {"type": "string", "description": "Short human-readable name for the workflow."},+ "description": {"type": "string", "description": "Optional one-line description of what the workflow does."},+ "input_type": {+ "type": "string",+ "enum": ["image", "text", "mesh"],+ "description": (+ "The workflow's input source node. Exactly one of: "+ "'image' (Image node), 'text' (Text node), "+ "'mesh' (Load 3D Mesh node, uses the current scene mesh). "+ "Never use any other value."+ ),+ },+ "steps": {+ "type": "array",+ "description": "Ordered processing steps. Each runs after the previous one.",+ "items": {+ "type": "object",+ "properties": {+ "extension_id": {+ "type": "string",+ "description": "Exact extension id from 'Available extensions' (e.g. 'mesh-optimizer/optimize').",+ },+ "params": {+ "type": "object",+ "description": "Optional param overrides, keyed by param id. Omit to use defaults.",+ },+ },+ "required": ["extension_id"],+ },+ },+ },+ "required": ["name", "input_type", "steps"],+ },+ },+ },+]+++# Input kinds the agent may pick, mapped to the real Modly source-node types.+# Keep this in sync with the node palette in WorkflowsPage.tsx.+INPUT_NODES = {+ "image": {"type": "imageNode", "data": {"enabled": True, "params": {}, "showInGenerate": True}},+ "text": {"type": "textNode", "data": {"enabled": True, "params": {}}},+ "mesh": {"type": "meshNode", "data": {"enabled": True, "params": {"source": "current"}}},+}+++def _build_workflow_graph(name: str, description: str, input_type: str, steps: list[dict]) -> dict:+ """Assemble a Modly workflow graph (nodes + edges) from a simplified step spec.++ Layout: one source node (Image / Text / Load 3D Mesh), one extensionNode per+ step, then an Add-to-Scene output node, all wired in a single linear chain with+ workflowEdge edges. id/timestamps are left for the frontend to stamp+ (crypto.randomUUID + ISO date), matching how the Workflows tab creates workflows.+ """+ spec = INPUT_NODES.get(input_type, INPUT_NODES["image"])+ input_node = {+ "id": uuid.uuid4().hex[:8],+ "type": spec["type"],+ "position": {"x": 250, "y": 50},+ "data": {**spec["data"]},+ }++ ext_nodes = []+ for i, step in enumerate(steps):+ ext_nodes.append({+ "id": uuid.uuid4().hex[:8],+ "type": "extensionNode",+ "position": {"x": 250, "y": 150 + i * 200},+ "data": {+ "extensionId": step["extension_id"],+ "enabled": True,+ "params": step.get("params") or {},+ },+ })++ output_node = {+ "id": uuid.uuid4().hex[:8],+ "type": "outputNode",+ "position": {"x": 250, "y": 150 + len(steps) * 200},+ "data": {"enabled": True, "params": {}},+ }++ all_nodes = [input_node, *ext_nodes, output_node]+ edges = [+ {+ "id": f"e-{all_nodes[i]['id']}-{all_nodes[i + 1]['id']}",+ "source": all_nodes[i]["id"],+ "target": all_nodes[i + 1]["id"],+ "type": "workflowEdge",+ }+ for i in range(len(all_nodes) - 1)+ ]++ return {"name": name, "description": description, "nodes": all_nodes, "edges": edges}+++async def execute_tool(name: str, arguments: dict, context: dict) -> tuple[str, dict | None]:+ """Execute a tool and return (result_text, action_payload).+ action_payload carries data the frontend needs to react (e.g. new mesh URL).+ """+ async with httpx.AsyncClient(timeout=60.0) as client:+ try:+ if name == "list_models":+ r = await client.get(f"{MODLY_API}/model/all")+ r.raise_for_status()+ models = [m for m in r.json() if m.get("downloaded")]+ if not models:+ return "No models downloaded yet.", None+ lines = "\n".join(f"- {m['id']}: {m.get('name', m['id'])}" for m in models)+ return f"Available models:\n{lines}", None++ elif name == "unload_models":+ r = await client.post(f"{MODLY_API}/model/unload-all")+ r.raise_for_status()+ return "All 3D generation models have been unloaded from VRAM.", None++ elif name == "get_mesh_info":+ mesh_path = context.get("currentMeshPath")+ mesh_triangles = context.get("meshTriangles")+ if not mesh_path:+ return "No mesh currently loaded in the viewer.", None+ info = f"Current mesh: {mesh_path}"+ if mesh_triangles:+ info += f" ({mesh_triangles:,} triangles)"+ return info, None++ elif name == "decimate_mesh":+ r = await client.post(+ f"{MODLY_API}/optimize/mesh",+ json={"path": arguments["path"], "target_faces": arguments["target_faces"]},+ )+ r.raise_for_status()+ data = r.json()+ payload = {"type": "mesh_update", "url": data["url"], "face_count": data.get("face_count")}+ return f"Decimated to {data.get('face_count', '?')} faces.", payload++ elif name == "smooth_mesh":+ r = await client.post(+ f"{MODLY_API}/optimize/smooth",+ json={"path": arguments["path"], "iterations": arguments["iterations"]},+ )+ r.raise_for_status()+ data = r.json()+ payload = {"type": "mesh_update", "url": data["url"]}+ return f"Smoothed mesh ({arguments['iterations']} iterations).", payload++ elif name == "get_generation_status":+ r = await client.get(f"{MODLY_API}/generate/status/{arguments['job_id']}")+ r.raise_for_status()+ s = r.json()+ text = f"Status: {s['status']}, Progress: {s.get('progress', 0)}%"+ if s.get("step"):+ text += f", Step: {s['step']}"+ if s.get("output_url"):+ text += f", Output: {s['output_url']}"+ return text, None++ elif name == "list_workflows":+ workflows = context.get("workflows", [])+ if not workflows:+ return "No workflows found. Create one in the Workflows tab.", None+ lines = "\n".join(f"- {w['id']}: {w['name']}" for w in workflows)+ return f"Available workflows:\n{lines}", None++ elif name == "run_workflow":+ workflow_id = arguments["workflow_id"]+ workflows = context.get("workflows", [])+ match = next((w for w in workflows if w["id"] == workflow_id), None)+ if not match:+ return f"Workflow '{workflow_id}' not found. Use list_workflows to see available workflows.", None+ payload = {"type": "run_workflow", "workflow_id": workflow_id, "workflow_name": match["name"]}+ return f"Executing workflow '{match['name']}'…", payload++ elif name == "create_workflow":+ steps = arguments.get("steps") or []+ if not steps:+ return "A workflow needs at least one step. Specify the extensions to chain.", None++ input_type = arguments.get("input_type") or "image"+ if input_type not in INPUT_NODES:+ return (+ f"Invalid input_type '{input_type}'. Use exactly one of: "+ f"image (Image node), text (Text node), mesh (Load 3D Mesh node).",+ None,+ )++ extensions = context.get("extensions", [])+ valid_ids = {e["id"] for e in extensions}+ if valid_ids:+ unknown = [s.get("extension_id") for s in steps if s.get("extension_id") not in valid_ids]+ if unknown:+ avail = ", ".join(sorted(valid_ids)) or "(none installed)"+ return (+ f"Unknown extension id(s): {', '.join(map(str, unknown))}. "+ f"Use only these: {avail}.",+ None,+ )++ wf = _build_workflow_graph(+ name=arguments.get("name") or "New Workflow",+ description=arguments.get("description") or "",+ input_type=input_type,+ steps=steps,+ )+ payload = {"type": "create_workflow", "workflow": wf}+ return f"Created workflow '{wf['name']}' with {len(steps)} step(s).", payload++ else:+ return f"Unknown tool: {name}", None++ except httpx.HTTPStatusError as e:+ return f"API error {e.response.status_code}: {e.response.text[:200]}", None+ except Exception as e:+ return f"Error: {e}", None+++class ChatMessage(BaseModel):+ role: str+ content: str+ images: list[str] = [] # data URLs+++class ProviderConfig(BaseModel):+ type: str = "local" # "local" | "external"+ base_url: Optional[str] = None # external only, e.g. https://api.openai.com/v1+ api_key: Optional[str] = None+++class AgentChatRequest(BaseModel):+ messages: list[ChatMessage]+ model: str = Field(default_factory=llm_server.default_model_id) # local: catalog/custom id — external: provider model name+ provider: ProviderConfig = ProviderConfig()+ context: dict = {}+ thinking: str = "auto" # "auto" | "on" | "off"+++class ActionDone(BaseModel):+ tool: str+ result: str+ payload: dict | None = None+++class AgentChatResponse(BaseModel):+ message: str+ actions: list[ActionDone] = []+ thinking: str | None = None+++def _extract_thinking(msg: dict) -> tuple[str, str | None]:+ """Return (clean_content, thinking_text). Handles llama-server's+ reasoning_content field and inline <think> tags."""+ content = msg.get("content") or ""+ thinking = msg.get("reasoning_content") or None+ if not thinking:+ match = re.search(r"<think>(.*?)</think>", content, re.DOTALL)+ if match:+ thinking = match.group(1).strip()+ content = (content[: match.start()] + content[match.end() :]).strip()+ return content, thinking+++def _auth_headers(base_url: str, api_key: Optional[str]) -> dict:+ headers: dict[str, str] = {}+ if api_key:+ headers["Authorization"] = f"Bearer {api_key}"+ if "anthropic" in base_url:+ # Anthropic's OpenAI-compat layer also accepts the native headers.+ headers["x-api-key"] = api_key+ headers["anthropic-version"] = "2023-06-01"+ return headers+++class ExternalModelsRequest(BaseModel):+ base_url: str+ api_key: str = ""++[email protected]("/external/models")+async def list_external_models(req: ExternalModelsRequest):+ """Proxy the provider's /models listing (avoids CORS issues from the renderer).++ POST with the key in the body, never a GET query string: uvicorn's access log+ records the full request line, and that log ends up in runtime.log.+ """+ headers = _auth_headers(req.base_url, req.api_key)+ async with httpx.AsyncClient(timeout=10.0) as client:+ try:+ r = await client.get(f"{req.base_url.rstrip('/')}/models", headers=headers)+ r.raise_for_status()+ data = r.json().get("data", [])+ return {"models": sorted(m["id"] for m in data if isinstance(m, dict) and m.get("id"))}+ except Exception:+ return {"models": []}+++async def _unload_llm_after_workflow(request: AgentChatRequest, actions_done: list[ActionDone]) -> None:+ """Free the local LLM's VRAM once a workflow has been dispatched, so the+ workflow gets the full GPU. Best-effort — never fail the chat over it."""+ if request.provider.type != "local":+ return+ if not any(a.tool == "run_workflow" for a in actions_done):+ return+ try:+ await asyncio.to_thread(llama_pool.unload_all)+ except Exception:+ pass+++def _error_detail(r: httpx.Response) -> str:+ """The provider's own message (OpenAI-style `{"error": {"message": …}}`), else the raw body."""+ try:+ err = r.json().get("error")+ if isinstance(err, dict) and err.get("message"):+ return str(err["message"])[:300]+ if isinstance(err, str):+ return err[:300]+ except (ValueError, AttributeError):+ pass+ return r.text[:300]+++def _tool_arguments(raw) -> dict:+ """OpenAI-compatible servers send tool arguments as a JSON string."""+ if isinstance(raw, dict):+ return raw+ try:+ parsed = json.loads(raw or "{}")+ except (TypeError, ValueError):+ return {}+ return parsed if isinstance(parsed, dict) else {}+++def _user_entry(m: ChatMessage, send_images: bool) -> dict:+ if not (m.images and send_images):+ return {"role": m.role, "content": m.content}+ parts: list[dict] = [{"type": "text", "text": m.content}]+ for data_url in m.images:+ parts.append({"type": "image_url", "image_url": {"url": data_url}})+ return {"role": m.role, "content": parts}+++def _drop_images(messages: list[dict]) -> bool:+ """Replace image parts with a text note, in place. True if any were dropped."""+ dropped = False+ for m in messages:+ if not isinstance(m.get("content"), list):+ continue+ texts = [p["text"] for p in m["content"] if p.get("type") == "text"]+ if any(p.get("type") == "image_url" for p in m["content"]):+ dropped = True+ texts.append("[An image was attached, but this model reads text only.]")+ m["content"] = "\n".join(texts)+ return dropped++[email protected]("/chat", response_model=AgentChatResponse)+async def agent_chat(request: AgentChatRequest):+ messages: list[dict] = [{"role": "system", "content": SYSTEM_PROMPT}]++ # Inject scene context so the LLM knows current state+ if request.context:+ ctx_lines = []+ if request.context.get("currentMeshPath"):+ ctx_lines.append(f"Current mesh path: {request.context['currentMeshPath']}")+ if request.context.get("meshTriangles"):+ ctx_lines.append(f"Current mesh triangles: {request.context['meshTriangles']:,}")+ if ctx_lines:+ messages.append({+ "role": "system",+ "content": "Scene context:\n" + "\n".join(ctx_lines),+ })++ extensions = request.context.get("extensions") or []+ if extensions:+ ext_lines = [+ f"- {e['id']} ({e.get('input', '?')}→{e.get('output', '?')}): {e.get('name', e['id'])}"+ for e in extensions+ ]+ messages.append({+ "role": "system",+ "content": (+ "Available extensions (use the exact id when creating workflows):\n"+ + "\n".join(ext_lines)+ ),+ })++ # ONE system message, first. Qwen3.5's chat template raises "System message+ # must be at the beginning", which llama-server returns as a flat HTTP 400;+ # other templates silently drop the extra ones.+ messages = [{"role": "system", "content": "\n\n".join(m["content"] for m in messages)}]++ slot = None+ send_images = True+ extra: dict = {}+ if request.provider.type == "local":+ try:+ spec = llm_server.resolve_model(request.model)+ # hold=True: the slot stays claimed for the whole loop, so neither the+ # idle reaper nor a model loading elsewhere can evict it mid-answer.+ slot = await asyncio.to_thread(llama_pool.ensure, request.model, spec, True)+ except Exception as e:+ return AgentChatResponse(message=f"Could not start the local LLM: {e}")+ base_url = slot.base_url+ headers: dict = {}+ send_images = spec["vision"]+ extra.update(llm_server.sampling_for(request.model))+ if request.thinking == "off":+ extra["chat_template_kwargs"] = {"enable_thinking": False}+ else:+ if not request.provider.base_url:+ return AgentChatResponse(message="No provider URL configured. Set one in Settings → Agent.")+ base_url = request.provider.base_url.rstrip("/")+ headers = _auth_headers(base_url, request.provider.api_key)++ for m in request.messages:+ messages.append(_user_entry(m, send_images))++ actions_done: list[ActionDone] = []+ all_thinking: list[str] = []+ final: AgentChatResponse | None = None++ try:+ async with httpx.AsyncClient(timeout=120.0) as client:+ for _ in range(10): # max tool-call rounds+ r = await client.post(+ f"{base_url}/chat/completions",+ headers=headers,+ json={"model": request.model, "messages": messages, "tools": TOOLS, "stream": False, **extra},+ )+ # An external model's vision support is unknown up front, and a+ # text-only one rejects image parts with a 400 that failed the+ # whole turn. Retry once with the images described as omitted.+ if r.status_code == 400 and request.provider.type != "local" and _drop_images(messages):+ r = await client.post(+ f"{base_url}/chat/completions",+ headers=headers,+ json={"model": request.model, "messages": messages, "tools": TOOLS, "stream": False, **extra},+ )++ if r.status_code != 200:+ return AgentChatResponse(message=f"LLM error ({r.status_code}): {_error_detail(r)}")++ msg = r.json()["choices"][0]["message"]+ tool_calls = msg.get("tool_calls") or []+ assistant: dict = {"role": "assistant", "content": msg.get("content") or ""}+ if tool_calls:+ assistant["tool_calls"] = tool_calls+ messages.append(assistant)++ clean_content, thinking_text = _extract_thinking(msg)+ if thinking_text:+ all_thinking.append(thinking_text)++ if not tool_calls:+ final = AgentChatResponse(message=clean_content, actions=actions_done)+ break++ for tc in tool_calls:+ fn = tc["function"]+ result_text, payload = await execute_tool(fn["name"], _tool_arguments(fn.get("arguments")), request.context)+ actions_done.append(ActionDone(tool=fn["name"], result=result_text, payload=payload))+ messages.append({"role": "tool", "tool_call_id": tc.get("id", ""), "content": result_text})+ except httpx.HTTPError as e:+ return AgentChatResponse(message=f"Could not reach the LLM at {base_url}: {e}", actions=actions_done)+ finally:+ if slot is not None:+ slot.release()++ # After the release: unload_all() spares a held slot, so unloading while+ # still holding ours would keep the agent's own model on the GPU.+ await _unload_llm_after_workflow(request, actions_done)++ if final is None:+ final = AgentChatResponse(message="Reached maximum tool iterations.", actions=actions_done)+ final.thinking = "\n\n---\n\n".join(all_thinking) if all_thinking else None+ return finaldiff --git a/apps/forge-desktop/api/routers/export.py b/apps/forge-desktop/api/routers/export.pynew file mode 100644index 000000000..854d8bf21--- /dev/null+++ b/apps/forge-desktop/api/routers/export.py@@ -0,0 +1,216 @@+import base64+import binascii+import io+import math+from pathlib import Path++import trimesh+from fastapi import APIRouter, HTTPException+from fastapi.responses import Response, FileResponse++from services import imported_sources+# Import the module (not the name) so WORKSPACE_DIR is read at call time: the+# settings endpoint rebinds it when the user moves the workspace.+import services.generator_registry as registry++router = APIRouter(tags=["export"])++SUPPORTED = {"glb", "stl", "obj", "ply"}++# Formats OrcaSlicer's importer accepts (see the orcaslicer://open contract).+# GLB is deliberately excluded — OrcaSlicer cannot import glTF/GLB, so a .glb+# deeplink downloads but silently fails to slice.+SLICER_FORMATS = {"stl", "obj"}+SLICER_MEDIA_TYPES = {"stl": "model/stl", "obj": "text/plain"}++# Image-to-3D output has no inherent physical scale (a single photo carries no+# real-world size), and AI generators emit roughly unit-sized meshes — which+# import into a slicer as an invisible ~1 mm speck. Normalise the longest+# bounding-box edge to a sane, obviously-printable default; the user rescales+# in OrcaSlicer as needed.+DEFAULT_PRINT_LONGEST_MM = 50.0++# ...but this route also serves meshes the user authored or imported, which DO+# carry a real-world size. Silently resizing a 180 mm part down to 50 mm wastes+# a print, so only rescale what is small enough to be unit-sized AI output.+UNIT_SCALE_MAX = 5.0++# Source formats whose up-axis is Y (the glTF convention). Everything else this+# route accepts — STL, OBJ, PLY — is conventionally Z-up already.+GLTF_SUFFIXES = {".glb", ".gltf"}+++def _to_single_mesh(loaded: object) -> "trimesh.Trimesh":+ """Flatten a loaded GLB into one Trimesh, baking scene-graph node transforms.++ ``trimesh.util.concatenate(scene.geometry.values())`` would DROP the node+ transforms and misassemble a multi-node scene, so flatten at the scene level+ where the graph transforms are applied.+ """+ if isinstance(loaded, trimesh.Trimesh):+ return loaded+ if isinstance(loaded, trimesh.Scene):+ if len(loaded.geometry) == 0:+ raise HTTPException(422, "Mesh contains no geometry")+ # Bake the scene-graph node transforms into a single mesh. The spelling+ # varies across trimesh versions — to_mesh()/to_geometry() are the modern+ # APIs (4.6+); dump(concatenate=True) is the pre-removal fallback for 4.5.+ for flatten in (lambda s: s.to_mesh(), lambda s: s.to_geometry(), lambda s: s.dump(concatenate=True)):+ try:+ result = flatten(loaded)+ except (AttributeError, TypeError):+ continue+ if isinstance(result, trimesh.Trimesh):+ return result+ if isinstance(result, (list, tuple)) and result:+ return trimesh.util.concatenate(result)+ # Fallback: concatenate the geometry as-is (may ignore node transforms).+ return trimesh.util.concatenate(list(loaded.geometry.values()))+ raise HTTPException(422, "Unsupported mesh contents")+++def _scale_to_print_size(mesh: "trimesh.Trimesh", longest_mm: float = DEFAULT_PRINT_LONGEST_MM) -> None:+ """Uniformly scale ``mesh`` in place so its longest bbox edge is ``longest_mm``."""+ extents = mesh.extents+ longest = float(max(extents)) if extents is not None and len(extents) else 0.0+ if longest > 1e-9 and math.isfinite(longest):+ mesh.apply_scale(longest_mm / longest)+++def _normalize_print_scale(mesh: "trimesh.Trimesh") -> bool:+ """Rescale ``mesh`` only if it looks unit-sized; return whether it was rescaled.++ A mesh whose longest edge already exceeds ``UNIT_SCALE_MAX`` is assumed to+ carry a real-world size the user chose, and is left untouched.+ """+ extents = mesh.extents+ longest = float(max(extents)) if extents is not None and len(extents) else 0.0+ if not math.isfinite(longest) or not (1e-9 < longest <= UNIT_SCALE_MAX):+ return False+ _scale_to_print_size(mesh)+ return True+++def _resolve_slicer_source(token: str) -> tuple[Path, str]:+ """Decode ``token`` into an existing source file and its ORIGINAL suffix.++ Two kinds of source are accepted:++ * a workspace-relative path, confined to the workspace by ancestry;+ * an absolute path, but ONLY when the user imported that exact file this+ session (see ``services.imported_sources``). Membership there is an+ equality test on the resolved path, so this grants no traversal and does+ not widen the route to arbitrary disk paths.++ The returned suffix is the format the user actually supplied — for an import+ that is the pre-conversion extension, which is what decides the up-axis.+ """+ try:+ padded = token + "=" * (-len(token) % 4)+ decoded = base64.urlsafe_b64decode(padded.encode("ascii")).decode("utf-8")+ except (binascii.Error, UnicodeDecodeError, ValueError):+ raise HTTPException(400, "Malformed source token")++ candidate = Path(decoded)+ if candidate.is_absolute():+ original_suffix = imported_sources.source_suffix(candidate)+ if original_suffix is None:+ raise HTTPException(400, "Invalid path")+ full_path = candidate.resolve()+ if not full_path.is_file():+ raise HTTPException(404, f"File not found: {decoded}")+ return full_path, original_suffix++ # Containment check via ancestry, not string prefix: `startswith` would let a+ # sibling like `<workspace>-other/...` slip through, and `..` escapes resolve+ # outside the workspace and fail this check.+ workspace = registry.WORKSPACE_DIR.resolve()+ full_path = (workspace / decoded).resolve()+ if full_path != workspace and workspace not in full_path.parents:+ raise HTTPException(400, "Invalid path")+ if not full_path.is_file():+ raise HTTPException(404, f"File not found: {decoded}")+ return full_path, full_path.suffix.lower()++[email protected]("/slicer/{fmt}/{token}/{filename}")+def export_for_slicer(fmt: str, token: str, filename: str):+ """Serve a generated GLB converted to a slicer-importable mesh, at a URL+ shaped for OrcaSlicer's ``orcaslicer://open?file=<url>`` deeplink.++ The URL is intentionally path-only and ends in the real filename+extension+ (e.g. ``/export/slicer/stl/<b64url-workspace-path>/model.stl``). OrcaSlicer+ downloads the URL and derives the import filename — and therefore the mesh+ format — from the URL's FINAL path segment, so a query string (``?path=...``)+ would corrupt the parsed extension and the model would silently fail to+ import. ``token`` is the url-safe-base64 of the source path — workspace-+ relative, or absolute for a file the user imported this session (see+ ``_resolve_slicer_source``); ``filename`` (e.g. ``model.stl``) is what+ OrcaSlicer names the download.+ """+ fmt = fmt.lower()+ if fmt not in SLICER_FORMATS:+ raise HTTPException(400, f"Unsupported slicer format: {fmt}. Supported: {', '.join(sorted(SLICER_FORMATS))}")+ if not filename.lower().endswith(f".{fmt}"):+ raise HTTPException(400, "Filename must end with the requested format extension")++ full_path, source_suffix = _resolve_slicer_source(token)++ mesh = _to_single_mesh(trimesh.load(str(full_path)))+ # glTF/GLB is Y-up; OrcaSlicer's world is Z-up. Rotate +90° about X so the+ # model imports standing upright instead of on its side. (Modly's own viewer+ # rests generated meshes on the Y=0 plane, confirming Y is the up axis.)+ # STL/OBJ/PLY sources are already Z-up, so rotating them would do the very+ # thing this corrects — lay an upright model on its side.+ if source_suffix in GLTF_SUFFIXES:+ mesh.apply_transform(trimesh.transformations.rotation_matrix(math.pi / 2, [1, 0, 0]))+ _normalize_print_scale(mesh)++ data = mesh.export(file_type=fmt)+ if isinstance(data, str):+ data = data.encode("utf-8")+ return Response(+ content=data,+ media_type=SLICER_MEDIA_TYPES.get(fmt, "application/octet-stream"),+ # Fixed name (not the client-supplied segment) — keeps arbitrary input out+ # of the response header. OrcaSlicer names the file from the URL anyway.+ headers={"Content-Disposition": f'attachment; filename="model.{fmt}"'},+ )++[email protected]("/{fmt}")+def export_mesh(fmt: str, path: str):+ if fmt not in SUPPORTED:+ raise HTTPException(400, f"Unsupported format: {fmt}. Supported: {', '.join(SUPPORTED)}")++ full_path = (registry.WORKSPACE_DIR / path).resolve()+ if not registry.is_within_workspace(full_path):+ raise HTTPException(400, "Invalid path")+ if not full_path.exists():+ raise HTTPException(404, f"File not found: {path}")++ # GLB — serve directly, no conversion needed+ if fmt == "glb":+ return FileResponse(str(full_path), media_type="model/gltf-binary")++ # Load and flatten scene to a single mesh+ loaded = trimesh.load(str(full_path))+ if isinstance(loaded, trimesh.Scene):+ geoms = list(loaded.geometry.values())+ mesh = trimesh.util.concatenate(geoms) if len(geoms) > 1 else geoms[0]+ else:+ mesh = loaded++ buf = io.BytesIO()+ if fmt == "stl":+ mesh.export(buf, file_type="stl")+ media_type = "model/stl"+ elif fmt == "ply":+ mesh.export(buf, file_type="ply")+ media_type = "application/octet-stream"+ else: # obj+ mesh.export(buf, file_type="obj")+ media_type = "text/plain"++ buf.seek(0)+ return Response(content=buf.read(), media_type=media_type)diff --git a/apps/forge-desktop/api/routers/extensions.py b/apps/forge-desktop/api/routers/extensions.pynew file mode 100644index 000000000..fdfbf0e0c--- /dev/null+++ b/apps/forge-desktop/api/routers/extensions.py@@ -0,0 +1,232 @@+import asyncio+import json+import os+import platform as platform_module+import re+import subprocess+import sys+from pathlib import Path+from fastapi import APIRouter, Body, HTTPException++router = APIRouter(tags=["extensions"])++[email protected]("/reload")+async def reload_extensions(payload: dict | None = Body(default=None)):+ """+ Re-scans the extensions/ folder and reloads the registry without restarting FastAPI.+ Unloads all currently loaded generators before reloading.+ """+ from services.generator_registry import generator_registry+ validation_capability = None+ if isinstance(payload, dict):+ candidate = payload.get("validationCapability")+ if isinstance(candidate, dict):+ validation_capability = candidate+ # Off the event loop: reload waits for any in-progress model load.+ await asyncio.to_thread(generator_registry.reload, validation_capability)+ return {+ "reloaded": True,+ "models": list(generator_registry._generators.keys()),+ "errors": generator_registry.load_errors(),+ }++[email protected]("/setup/{ext_id}")+async def setup_extension(ext_id: str):+ """+ Creates the isolated venv for an extension by running its setup.py.+ Called automatically after installing an extension from GitHub.+ Runs setup.py with Modly's embedded Python and the detected GPU SM.+ """+ from services.generator_registry import EXTENSIONS_DIR++ if EXTENSIONS_DIR is None or not EXTENSIONS_DIR.exists():+ raise HTTPException(400, "EXTENSIONS_DIR not configured")++ ext_dir = EXTENSIONS_DIR / ext_id+ setup_py = ext_dir / "setup.py"++ if not ext_dir.exists():+ raise HTTPException(404, f"Extension '{ext_id}' not found in {EXTENSIONS_DIR}")+ if not setup_py.exists():+ # No setup.py → legacy extension, nothing to do+ return {"status": "skipped", "reason": "no setup.py"}++ # Detect GPU compute capability. NVIDIA keeps detection priority, exactly+ # like electron/main/gpu-detect.ts: a Ryzen APU beside an NVIDIA dGPU must+ # resolve to CUDA on both code paths.+ gpu_sm, cuda_version = _detect_nvidia_gpu()+ gfx_target = "" if gpu_sm else _detect_gfx_target()+ flavor = "cuda" if gpu_sm else ("rocm" if gfx_target else "cpu")++ # Pass arguments as JSON so setup.py sees torch_flavor. The keys mirror+ # runExtensionSetup in electron/main/ipc-handlers.ts exactly — setup.py+ # scripts read the same contract whichever side launched them. Note this+ # endpoint is a fallback: Electron normally runs setup.py itself, and only+ # that path gets the ROCm index rewriting for extensions that ignore+ # torch_flavor.+ args = json.dumps({+ "python_exe": sys.executable,+ "ext_dir": str(ext_dir),+ "gpu_sm": gpu_sm,+ "cuda_version": cuda_version,+ "accelerator": flavor,+ "torch_flavor": flavor,+ "gfx_target": gfx_target,+ "torch_index_url": _rocm_index_url() if flavor == "rocm" else "",+ "platform": sys.platform,+ "arch": _node_arch(),+ })++ # Run setup.py using Modly's embedded Python (sys.executable)+ loop = asyncio.get_running_loop()+ result = await loop.run_in_executor(+ None,+ lambda: subprocess.run(+ [sys.executable, str(setup_py), args],+ capture_output=True,+ text=True,+ # pip's own output carries box-drawing characters; the locale codec+ # (cp1252 on Windows) raises on some of them and would turn a+ # successful setup into a 500 with no usable message.+ encoding="utf-8",+ errors="replace",+ )+ )++ if result.returncode != 0:+ raise HTTPException(500, f"setup.py failed:\n{result.stderr}")++ return {+ "status": "ok",+ "gpu_sm": gpu_sm,+ "gfx_target": gfx_target,+ "output": result.stdout,+ }++[email protected]("/errors")+async def extension_errors():+ """Returns extension loading errors (invalid manifest, failed import, etc.)."""+ from services.generator_registry import generator_registry+ return generator_registry.load_errors()+++def _detect_nvidia_gpu() -> tuple[int, int]:+ """+ Returns (compute capability, max CUDA version) — e.g. (86, 124) — or (0, 0)+ when there is no NVIDIA GPU.++ Asks nvidia-smi rather than torch: this process runs in Modly's main venv,+ which has no torch at all (see api/requirements.txt), so a torch import+ always failed here and silently reported every machine as CPU-only. Asking+ the driver also sidesteps the ROCm ambiguity — PyTorch's HIP build answers+ the whole torch.cuda API, reporting (12, 0) for a gfx1200 Radeon exactly+ like an sm_120 Blackwell. Mirrors parseNvidiaSmi in+ electron/main/gpu-detect.ts, including the driver → CUDA version table.+ """+ try:+ result = subprocess.run(+ ["nvidia-smi", "--query-gpu=compute_cap,driver_version", "--format=csv,noheader"],+ capture_output=True,+ text=True,+ timeout=15,+ )+ except (OSError, subprocess.SubprocessError):+ return 0, 0+ if result.returncode != 0:+ return 0, 0++ line = result.stdout.strip().splitlines()[0].strip() if result.stdout.strip() else ""+ if not line:+ return 0, 0+ parts = [part.strip() for part in line.split(",")]++ try:+ sm = round(float(parts[0]) * 10)+ except (ValueError, IndexError):+ sm = 86+ try:+ driver_major = int((parts[1] if len(parts) > 1 else "0").split(".")[0])+ except ValueError:+ driver_major = 0++ cuda_version = 118 # safe minimum+ for threshold, version in (+ (570, 128), (560, 126), (555, 125), (550, 124),+ (545, 123), (535, 122), (530, 121), (525, 120), (520, 118),+ ):+ if driver_major >= threshold:+ cuda_version = version+ break+ return sm, cuda_version+++def _rocm_index_url() -> str:+ """The pip index a ROCm torch install must come from. Mirrors+ resolveRocmTorchSpec in electron/main/gpu-detect.ts."""+ override = os.environ.get("MODLY_ROCM_INDEX", "").strip()+ if override:+ return override+ if sys.platform == "win32":+ return "https://repo.amd.com/rocm/whl-multi-arch/"+ return "https://download.pytorch.org/whl/rocm7.2"+++def _node_arch() -> str:+ """platform.machine() mapped onto Node's process.arch vocabulary, so+ setup.py sees the same values whichever side launched it."""+ machine = platform_module.machine().lower()+ if machine in ("x86_64", "amd64"):+ return "x64"+ if machine in ("aarch64", "arm64"):+ return "arm64"+ return machine+++def _detect_gfx_target() -> str:+ """+ Returns the ROCm compute target (e.g. "gfx1200"), or "" when there is no AMD GPU.++ Reads the kernel's KFD topology rather than asking torch: this process runs+ in Modly's main venv, which has no torch at all (see api/requirements.txt).+ The amdgpu driver publishes the target on its own, so no ROCm install is+ needed either. Mirrors electron/main/gpu-detect.ts.+ """+ kfd_nodes = Path("/sys/class/kfd/kfd/topology/nodes")+ if not Path("/dev/kfd").exists() or not kfd_nodes.is_dir():+ return ""++ def _prop(text: str, key: str) -> int:+ match = re.search(rf"^{key}\s+(\d+)\s*$", text, re.M)+ return int(match.group(1)) if match else 0++ try:+ nodes = sorted(kfd_nodes.iterdir(), key=lambda p: int(p.name) if p.name.isdigit() else 0)+ except OSError:+ return ""++ # Among GPU nodes the largest simd_count wins, mirroring parseKfdGfxTarget+ # in electron/main/gpu-detect.ts: on an APU + dGPU machine the APU commonly+ # gets the lower node number, and the discrete card has more SIMDs.+ best_target, best_simd = "", 0+ for node in nodes:+ try:+ text = (node / "properties").read_text()+ except OSError:+ continue+ # Node 0 is the CPU node (simd_count 0) and carries no compute target.+ simd_count = _prop(text, "simd_count")+ if simd_count <= 0:+ continue+ # major*10000 + minor*100 + step, minor and step read as hex digits.+ version = _prop(text, "gfx_target_version")+ if version <= 0:+ continue+ major, minor, step = version // 10000, (version % 10000) // 100, version % 100+ if major <= 0 or minor > 15 or step > 15:+ continue+ if simd_count > best_simd:+ best_target, best_simd = f"gfx{major}{minor:x}{step:x}", simd_count+ return best_targetdiff --git a/apps/forge-desktop/api/routers/generation.py b/apps/forge-desktop/api/routers/generation.pynew file mode 100644index 000000000..73d0baae9--- /dev/null+++ b/apps/forge-desktop/api/routers/generation.py@@ -0,0 +1,391 @@+import asyncio+import json+import threading+import time+import traceback+import uuid+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+from typing import Dict, Optional, Union+from fastapi import APIRouter, File, Form, UploadFile, HTTPException, BackgroundTasks+from services.generators.base import smooth_progress, GenerationCancelled++import re as _re+# Import the module (not the name) so WORKSPACE_DIR is read at call time: the+# settings endpoint rebinds it when the user relocates the workspace, and a+# binding captured at import would keep writing output to the old directory.+import services.generator_registry as registry+from services.generator_registry import generator_registry+from schemas.generation import GenerateFromArtifactRequest, JobStatus+from services.artifact_input import (+ RESERVED_ARTIFACT_PARAMS,+ TypedArtifactInput,+ validate_artifact_input,+)++router = APIRouter(tags=["generation"])++# Shared with workflow_runs.create_run_from_image so the two endpoints can't drift apart on+# what counts as a valid remesh mode the way they had drifted on `collection` before #238.+VALID_REMESH_MODES = ("quad", "triangle", "none")++_jobs: Dict[str, JobStatus] = {}+_cancelled: set = set()+_cancel_events: Dict[str, threading.Event] = {}+_completed_at: Dict[str, float] = {}+_job_generators: Dict[str, object] = {}+# A pinned generation owns the complete switch/load/generate lifecycle. Keeping+# that lifecycle on one dedicated worker provides process-wide serialization+# without parking default-executor workers on a blocking lock acquisition.+_pinned_generation_executor = ThreadPoolExecutor(+ max_workers=1,+ thread_name_prefix="modly-pinned-generation",+)++_JOB_TTL = 1800 # purge terminal jobs after 30 minutes+++def _purge_old_jobs() -> None:+ cutoff = time.monotonic() - _JOB_TTL+ stale = [jid for jid, t in _completed_at.items() if t < cutoff]+ for jid in stale:+ _jobs.pop(jid, None)+ _cancelled.discard(jid)+ _cancel_events.pop(jid, None)+ _job_generators.pop(jid, None)+ _completed_at.pop(jid, None)+++def sanitize_collection(collection: str) -> str:+ """Normalize a caller-supplied collection name into a safe workspace subfolder.++ The value becomes a directory under the workspace (``WORKSPACE_DIR / collection``), so a+ name carrying a path separator or a drive/wildcard character could escape that root or fail+ to create on Windows. Such a name, or an empty one, falls back to ``"Default"`` rather than+ raising, because a generation the caller already paid for should still land somewhere+ sensible. Shared so every entry point that routes output into a collection sanitizes it the+ same way; a second copy of this rule is a second chance to forget a character.++ Legality and containment are different questions, so they are asked separately: the+ reserved characters above are refused outright, and containment is put to the path+ library rather than to the spelling -- the same ``relative_to`` check+ ``generator_registry._path_belongs_to`` uses, so the two containment checks in this+ backend agree rather than drifting on their own semantics. A character blocklist alone+ lets ``".."`` through -- it contains none of the listed characters -- and+ ``WORKSPACE_DIR / ".."`` resolves to the workspace's *parent*, so the generated mesh+ would land outside the root.++ A name ending in a dot or space is refused too, even once it clears both checks above:+ Windows silently drops trailing dots/spaces from the final path component it actually+ creates, so ``mkdir()`` on ``"Exports..."`` lands in the very same folder as+ ``"Exports"`` -- two collections that look distinct to this function would otherwise+ merge their output on disk without either caller being told.+ """+ collection = (collection or "").strip()+ if (+ not collection+ or _re.search(r'[/:*?"<>|\\]', collection)+ or collection != collection.rstrip(". ")+ ):+ return "Default"++ try:+ (registry.WORKSPACE_DIR / collection).resolve().relative_to(+ registry.WORKSPACE_DIR.resolve()+ )+ except (OSError, ValueError):+ return "Default"++ return collection++[email protected]("/from-image")+async def generate_from_image(+ background_tasks: BackgroundTasks,+ image: UploadFile = File(...),+ model_id: str = Form("sf3d"),+ collection: str = Form("Default"),+ remesh: str = Form("quad"),+ enable_texture: bool = Form(False),+ texture_resolution: int = Form(1024),+ params: str = Form("{}"),+):+ if not image.content_type or not image.content_type.startswith("image/"):+ raise HTTPException(400, "File must be an image")++ if remesh not in VALID_REMESH_MODES:+ raise HTTPException(400, "remesh must be 'quad', 'triangle', or 'none'")++ collection = sanitize_collection(collection)++ # Verify the requested model exists in the registry+ try:+ generator_registry.get_generator(model_id)+ output_kind = generator_registry.get_manifest(model_id).get("output", "mesh")+ except ValueError as e:+ raise HTTPException(400, str(e))++ # Parse model-specific params from JSON and merge with common fields+ try:+ model_params = json.loads(params)+ except (json.JSONDecodeError, TypeError):+ model_params = {}++ job_id = str(uuid.uuid4())+ image_bytes = await image.read()+ full_params = {+ "remesh": remesh,+ "enable_texture": enable_texture,+ "texture_resolution": texture_resolution,+ **model_params,+ }++ _purge_old_jobs()++ job = JobStatus(job_id=job_id, status="pending", progress=0)+ _jobs[job_id] = job+ _cancel_events[job_id] = threading.Event()++ background_tasks.add_task(+ _run_generation, job_id, image_bytes, full_params, collection, output_kind, model_id+ )++ return {"job_id": job_id}++[email protected]("/from-artifact")+async def generate_from_artifact(+ request: GenerateFromArtifactRequest,+ background_tasks: BackgroundTasks,+):+ """Queue a validated typed artifact without serializing it as image bytes."""+ try:+ manifest = generator_registry.get_manifest(request.model_id)+ except (KeyError, ValueError) as exc:+ raise HTTPException(400, str(exc)) from exc+ declared = manifest.get("inputs") or [manifest.get("input", "image")]+ if request.input_kind not in declared:+ raise HTTPException(400, f"Model {request.model_id} does not accept {request.input_kind} input")+ try:+ artifact = validate_artifact_input(registry.WORKSPACE_DIR, request.input_kind, request.input_path)+ except ValueError as exc:+ raise HTTPException(400, str(exc)) from exc++ params = {k: v for k, v in request.params.items() if k not in RESERVED_ARTIFACT_PARAMS}+ params["scene_manifest_path"] = str(artifact.path)+ collection = sanitize_collection(request.collection)+ job_id = str(uuid.uuid4())+ _purge_old_jobs()+ _jobs[job_id] = JobStatus(job_id=job_id, status="pending", progress=0)+ _cancel_events[job_id] = threading.Event()+ background_tasks.add_task(+ _run_generation, job_id, artifact, params, collection, manifest.get("output", "mesh"), request.model_id+ )+ return {"job_id": job_id}+++[email protected]("/status/{job_id}")+async def job_status(job_id: str):+ job = _jobs.get(job_id)+ if not job:+ raise HTTPException(404, f"Job {job_id} not found")+ return job++[email protected]("/cancel/{job_id}")+async def cancel_job(job_id: str):+ job = _jobs.get(job_id)+ if not job:+ raise HTTPException(404, f"Job {job_id} not found")+ _cancelled.add(job_id)+ if job_id in _cancel_events:+ _cancel_events[job_id].set()+ if job.status in ("pending", "running"):+ job.status = "cancelled"+ _completed_at[job_id] = time.monotonic()+ # Kill only the subprocess bound to this job. A queued cancellation must not+ # terminate whichever earlier job currently owns the active generator.+ try:+ gen = _job_generators.get(job_id)+ if gen is not None and hasattr(gen, "_proc") and gen._proc and gen._proc.poll() is None:+ gen._proc.kill()+ gen._loaded = False+ gen._proc = None+ except Exception:+ pass+ return {"cancelled": True}+++async def _run_generation(+ job_id: str,+ model_input: Union[bytes, TypedArtifactInput],+ params: dict,+ collection: str = "Default",+ output_kind: str = "mesh",+ model_id: Optional[str] = None,+) -> None:+ # Pinned jobs share one model lifecycle. Switching is deliberately deferred+ # until this job runs on the dedicated worker: request-time switches can+ # otherwise unload a running job or leave A loading beside B. Crucially,+ # queued jobs are executor work items rather than default-executor threads+ # blocked on a lock, so cancelling a waiter cannot orphan queue ownership or+ # starve the worker that performs generation.+ loop = asyncio.get_running_loop()+ executor = _pinned_generation_executor if model_id is not None else None+ # Shown while this job waits behind another one on the single worker;+ # _run_generation_impl clears it as soon as the job actually starts.+ queued_job = _jobs.get(job_id)+ if queued_job is not None and executor is not None:+ queued_job.step = "Waiting for the previous generation…"+ future = loop.run_in_executor(+ executor,+ _run_generation_impl,+ job_id,+ model_input,+ params,+ collection,+ output_kind,+ model_id,+ )+ try:+ await future+ except asyncio.CancelledError:+ # asyncio cancellation attempts to cancel a queued concurrent future.+ # If it has already begun, the event lets the generator stop safely.+ _cancelled.add(job_id)+ cancel_event = _cancel_events.get(job_id)+ if cancel_event is not None:+ cancel_event.set()+ job = _jobs.get(job_id)+ if job is not None and job.status in ("pending", "running"):+ job.status = "cancelled"+ _completed_at[job_id] = time.monotonic()+ raise+++def _run_generation_impl(+ job_id: str,+ model_input: Union[bytes, TypedArtifactInput],+ params: dict,+ collection: str,+ output_kind: str,+ model_id: Optional[str],+) -> None:+ if job_id in _cancelled:+ return+ job = _jobs[job_id]+ job.status = "running"+ job.step = None++ def progress_cb(pct: int, step: str = "") -> None:+ # Monotonic: the loading phase walks the bar up on a background thread and+ # extensions then report their own 0->100 scale, so an unguarded assignment+ # yanks the bar backwards on the first generation progress message.+ if pct > job.progress:+ job.progress = pct+ if step:+ job.step = step++ try:+ # Refuse a selected weight variant that is not installed before loading+ # anything. Uses the job's model: the switch to it happens below.+ generator_registry.assert_weight_variant_installed(params, model_id)++ # Check if the model needs to be loaded BEFORE calling the generator+ # getter, because that call can load the model in a blocking manner.+ get_generator = (lambda: generator_registry.activate_ready_generator(model_id)) \+ if model_id is not None else generator_registry.get_active+ if model_id is not None:+ _job_generators[job_id] = generator_registry.get_generator(model_id)+ status_reader = (lambda: generator_registry.model_status(model_id)) \+ if model_id is not None else generator_registry.active_status+ status = status_reader()+ if not status["loaded"]:+ active = status+ model_name = active['name']+ init_label = f"Downloading {model_name}…" if not active['downloaded'] else f"Loading {model_name}…"+ progress_cb(0, init_label)+ stop_load_evt = threading.Event()+ load_thread = threading.Thread(+ target=smooth_progress,+ args=(progress_cb, 0, 9, init_label, stop_load_evt, 4.0),+ daemon=True,+ )+ load_thread.start()+ try:+ gen = get_generator()+ finally:+ stop_load_evt.set()+ else:+ gen = get_generator()++ _job_generators[job_id] = gen+ if job_id in _cancelled:+ return++ # Direct output to the collection subfolder+ coll_dir = registry.WORKSPACE_DIR / collection+ coll_dir.mkdir(parents=True, exist_ok=True)+ gen.outputs_dir = coll_dir++ cancel_event = _cancel_events.get(job_id)+ if isinstance(model_input, TypedArtifactInput):+ # Revalidate just before crossing the inference boundary. The+ # subprocess runner repeats this check inside the worker.+ from services.artifact_input import revalidate_artifact_input+ model_input = revalidate_artifact_input(registry.WORKSPACE_DIR, model_input)+ import inspect+ supports_cancel = "cancel_event" in inspect.signature(gen.generate_artifact).parameters+ output_path = (+ gen.generate_artifact(model_input.kind, model_input.path, params, progress_cb, cancel_event)+ if supports_cancel+ else gen.generate_artifact(model_input.kind, model_input.path, params, progress_cb)+ )+ else:+ import inspect+ supports_cancel = "cancel_event" in inspect.signature(gen.generate).parameters+ output_path = (+ gen.generate(model_input, params, progress_cb, cancel_event)+ if supports_cancel+ else gen.generate(model_input, params, progress_cb)+ )++ if job_id in _cancelled:+ return++ output_path = Path(output_path).resolve(strict=True)+ if output_kind == "scene":+ from services.scene_input import validate_scene_input+ try:+ output_relative = output_path.relative_to(registry.WORKSPACE_DIR.resolve())+ output_path = validate_scene_input(registry.WORKSPACE_DIR, output_relative.as_posix())+ except (OSError, ValueError) as exc:+ raise ValueError("Generated scene output is not a valid workspace scene") from exc++ job.status = "done"+ job.progress = 100+ _completed_at[job_id] = time.monotonic()+ try:+ rel = output_path.relative_to(registry.WORKSPACE_DIR)+ job.output_url = f"/workspace/{rel.as_posix()}"+ except ValueError:+ job.output_url = f"/workspace/{collection}/{output_path.name}"++ except GenerationCancelled:+ job.status = "cancelled"+ _completed_at[job_id] = time.monotonic()+ except Exception as exc:+ if job_id in _cancelled:+ return+ tb = traceback.format_exc()+ msg = f"[Generation ERROR] {exc}\n{tb}"+ try:+ print(msg)+ except UnicodeEncodeError:+ print(msg.encode("ascii", errors="replace").decode("ascii"))+ job.status = "error"+ job.error = tb.strip()+ _completed_at[job_id] = time.monotonic()+ finally:+ _job_generators.pop(job_id, None)diff --git a/apps/forge-desktop/api/routers/llm.py b/apps/forge-desktop/api/routers/llm.pynew file mode 100644index 000000000..33e1534cc--- /dev/null+++ b/apps/forge-desktop/api/routers/llm.py@@ -0,0 +1,418 @@+"""+Local LLM engine endpoints — model catalog, GGUF downloads, llama-server lifecycle.+Reuses the streamed/resumable downloader from routers.model.+"""+import asyncio+import json+import threading+from pathlib import Path+from typing import Optional+import httpx+from fastapi import APIRouter, HTTPException+from fastapi.responses import StreamingResponse+from pydantic import BaseModel++from routers.model import DownloadCancelled, DownloadPaused, _download_file_streamed+from services import llm_server+from services.llm_server import llama_pool++router = APIRouter(tags=["llm"])++_controls: dict[str, dict[str, threading.Event]] = {}+++class _DownloadState:+ """Tracks one model's in-flight download independent of any single SSE+ connection, so closing/reopening the Model Library modal reattaches to the+ same download instead of racing a second one against the same .part file."""++ def __init__(self) -> None:+ self.last_msg: dict = {}+ self.subscribers: list[asyncio.Queue] = []+ self.task: asyncio.Task | None = None+++_downloads: dict[str, _DownloadState] = {}+++def _new_control(key: str) -> dict[str, threading.Event]:+ control: dict[str, threading.Event] = {"pause": threading.Event(), "cancel": threading.Event()}+ _controls[key] = control+ return control+++def _check_control(control: dict[str, threading.Event]) -> None:+ if control["cancel"].is_set():+ raise DownloadCancelled()+ if control["pause"].is_set():+ raise DownloadPaused()+++def _fmt(data: dict) -> str:+ return f"data: {json.dumps(data)}\n\n"+++# ─── Catalog / status ─────────────────────────────────────────────────────────+[email protected]("/models")+async def list_models(tag: Optional[str] = None, downloaded: bool = False):+ """Model library. `tag` filters catalog entries by category (e.g. tag=code+ for coder models); custom user GGUFs are always included since their+ capabilities are unknown. `downloaded=true` keeps only ready-to-use models."""+ models = llm_server.list_models()+ if tag:+ models = [m for m in models if m.get("source") == "custom" or tag in (m.get("tags") or [])]+ if downloaded:+ models = [m for m in models if m.get("downloaded")]+ return {"models": models}++[email protected]("/status")+async def status():+ return {+ "binary_installed": llm_server.binary_installed(),+ "has_nvidia_gpu": llm_server.has_nvidia_gpu(),+ "vram_gb": llm_server.detect_vram_gb() or None,+ "models_dir": str(llm_server.LLM_MODELS_DIR),+ "server": await asyncio.to_thread(llama_pool.snapshot),+ }+++class LlmConfigRequest(BaseModel):+ max_models: str | int # "auto" or 1..MAX_SLOT_PORTS++[email protected]("/config")+async def get_config():+ return {+ "max_models": llm_server.load_config().get("max_models", "auto"),+ "resolved_max_models": llm_server.resolve_max_models(),+ "vram_gb": llm_server.detect_vram_gb() or None,+ "max_slot_ports": llm_server.MAX_SLOT_PORTS,+ }++[email protected]("/config")+async def set_config(request: LlmConfigRequest):+ value: str | int = request.max_models+ if isinstance(value, str) and value.lower() != "auto":+ try:+ value = int(value)+ except ValueError:+ raise HTTPException(status_code=422, detail="max_models must be 'auto' or an integer")+ if isinstance(value, int) and not (1 <= value <= llm_server.MAX_SLOT_PORTS):+ raise HTTPException(status_code=422, detail=f"max_models must be between 1 and {llm_server.MAX_SLOT_PORTS}")+ cfg = llm_server.load_config()+ cfg["max_models"] = value+ llm_server.save_config(cfg)+ # A lowered limit applies immediately — small-VRAM users count on it.+ await asyncio.to_thread(llama_pool.enforce_limit)+ return {"max_models": value, "resolved_max_models": llm_server.resolve_max_models()}++[email protected]("/unload")+async def unload():+ await asyncio.to_thread(llama_pool.unload_all)+ return {"unloaded": True}++[email protected]("/models/{model_id}")+async def delete_model(model_id: str):+ try:+ spec = llm_server.resolve_model(model_id)+ except KeyError as e:+ raise HTTPException(status_code=404, detail=str(e))+ if await asyncio.to_thread(llama_pool.is_loaded, model_id):+ await asyncio.to_thread(llama_pool.unload, model_id)+ spec["gguf_path"].unlink(missing_ok=True)+ if spec.get("mmproj_path"):+ spec["mmproj_path"].unlink(missing_ok=True)+ return {"deleted": True}+++# ─── Chat completion through the managed server ───────────────────────────────++class LlmChatRequest(BaseModel):+ model: str+ messages: list[dict]+ temperature: Optional[float] = None+ max_tokens: Optional[int] = None+ stream: Optional[bool] = False++[email protected]("/chat")+async def llm_chat(request: LlmChatRequest):+ """Load `model` (hot-swapping if needed) and run one OpenAI-format chat completion.++ Used by workflow nodes (LLM, Text to CAD, …) so they share the managed+ llama-server instead of loading their own copy of the model. When+ `stream` is set, the llama-server SSE chunks are proxied straight through so+ the caller can render tokens as they arrive.+ """+ try:+ spec = llm_server.resolve_model(request.model)+ except KeyError as e:+ raise HTTPException(status_code=404, detail=str(e))+ try:+ # hold=True: the slot comes back claimed, so a model loading in another+ # thread cannot evict it between here and the request below.+ slot = await asyncio.to_thread(llama_pool.ensure, request.model, spec, True)+ except Exception as e:+ raise HTTPException(status_code=503, detail=f"Could not start the local LLM: {e}")++ payload: dict = {"model": request.model, "messages": request.messages, "stream": bool(request.stream)}+ if request.temperature is not None:+ payload["temperature"] = request.temperature+ if request.max_tokens is not None:+ payload["max_tokens"] = request.max_tokens++ # The claim spans the whole completion, not just its end: a generation longer+ # than the idle TTL (a Text-to-CAD node can sit here for minutes) used to be+ # reaped mid-answer, since only a *finished* call marked the slot as used.+ if request.stream:+ async def proxy():+ try:+ async with httpx.AsyncClient(timeout=600.0) as client:+ async with client.stream("POST", f"{slot.base_url}/chat/completions", json=payload) as r:+ if r.status_code != 200:+ body = (await r.aread()).decode("utf-8", "replace")[:300]+ yield f"data: {json.dumps({'error': f'llama-server error ({r.status_code}): {body}'})}\n\n"+ return+ async for line in r.aiter_lines():+ if line.startswith("data: "):+ yield f"{line}\n\n"+ finally:+ slot.release()+ return StreamingResponse(proxy(), media_type="text/event-stream")++ try:+ async with httpx.AsyncClient(timeout=600.0) as client:+ r = await client.post(f"{slot.base_url}/chat/completions", json=payload)+ if r.status_code != 200:+ raise HTTPException(status_code=502, detail=f"llama-server error ({r.status_code}): {r.text[:300]}")+ return r.json()+ finally:+ slot.release()+++# ─── GGUF download (SSE) ──────────────────────────────────────────────────────+[email protected]("/download/pause")+async def pause_download(model_id: str):+ control = _controls.get(model_id)+ if control:+ control["pause"].set()+ return {"paused": True}++[email protected]("/download/cancel")+async def cancel_download(model_id: str):+ """Cancel an in-flight download, or clean up a paused one.++ A paused download has already left `_run_download` — its control is gone+ from `_controls`, so setting the cancel event would be a no-op. Reporting+ success there left the user with a multi-GB .part file they believed they+ had deleted, so the partial files are removed here instead."""+ control = _controls.get(model_id)+ if control:+ control["cancel"].set()+ return {"cancelled": True, "removed_partials": []}++ entry = next((e for e in llm_server.load_catalog() if e["id"] == model_id), None)+ removed = _discard_incomplete(entry) if entry else []+ _downloads.pop(model_id, None)+ return {"cancelled": bool(removed), "removed": removed}+++def _model_files(entry: dict) -> list[Path]:+ """Every file a model needs on disk: the weights, plus the vision projector."""+ paths = [llm_server.LLM_MODELS_DIR / entry["hf_filename"]]+ if entry.get("hf_mmproj_filename"):+ paths.append(llm_server.LLM_MODELS_DIR / llm_server.mmproj_local_name(entry))+ return paths+++def _discard_incomplete(entry: dict) -> list[str]:+ """Drop what a cancelled download left behind, and report what went.++ Not just the .part: a vision model downloads weights then projector, so+ cancelling during the second one left 2.5 GB of finished weights on disk+ under a model still reported as `downloaded: false` — no trash button is+ offered for those, so the space could not be reclaimed from the UI at all.+ A model whose files are all present is complete, not in flight, and is+ never touched here (deleting it is what DELETE /llm/models/{id} is for)."""+ paths = _model_files(entry)+ if all(p.exists() for p in paths):+ return []+ removed = []+ for path in paths:+ for target in (path.with_suffix(path.suffix + ".part"), path):+ if target.exists():+ target.unlink(missing_ok=True)+ removed.append(target.name)+ return removed+++def _is_terminal(msg: dict) -> bool:+ return msg.get("status") == "done" or "error" in msg or msg.get("cancelled") or msg.get("paused")+++async def _run_download(model_id: str, entry: dict, control: dict[str, threading.Event], state: _DownloadState) -> None:+ """Owns one model's download end to end, independent of any SSE connection.+ Broadcasts progress to every currently-attached watcher (see `_broadcast`)."""+ loop = asyncio.get_running_loop()++ def _broadcast(msg: dict) -> None:+ # _progress (below) runs in a worker thread — hop back onto the loop.+ def _do() -> None:+ state.last_msg = msg+ for q in list(state.subscribers):+ q.put_nowait(msg)+ loop.call_soon_threadsafe(_do)++ from huggingface_hub import hf_hub_url++ # Vision models ship a companion mmproj file — download it alongside the+ # weights, stored under a per-model local name (HF names collide).+ files: list[tuple[str, str, int]] = [(entry["hf_filename"], entry["hf_filename"], entry.get("size_bytes") or 0)]+ if entry.get("hf_mmproj_filename"):+ files.append((+ entry["hf_mmproj_filename"],+ llm_server.mmproj_local_name(entry),+ entry.get("mmproj_size_bytes") or 0,+ ))+ grand_total = sum(size for _, _, size in files)++ try:+ _broadcast({"percent": 0, "status": "Starting download…"})+ completed_bytes = 0++ for index, (hf_filename, local_filename, _size) in enumerate(files):+ url = hf_hub_url(repo_id=entry["hf_repo"], filename=hf_filename)++ def _progress(msg: dict, _base: int = completed_bytes) -> None:+ done = _base + msg.get("bytesDownloaded", 0)+ if grand_total:+ pct = min(99, round(done / grand_total * 100))+ # The streaming helper reports per-file figures. A vision+ # model downloads two files, so the bar (combined percent)+ # and the label baked into `status` (per-file percent) drew+ # two different numbers side by side. Restate all of it+ # against the combined total; `file`/`fileIndex` stay+ # per-file, which is what they're for.+ msg["percent"] = pct+ msg["bytesDownloaded"] = done+ msg["totalBytes"] = grand_total+ status = msg.get("status") or ""+ if status.endswith("%"):+ msg["status"] = f"{status.rsplit(' ', 1)[0]} {pct}%"+ _broadcast(msg)++ await loop.run_in_executor(+ None,+ lambda url=url, filename=local_filename, cb=_progress: _download_file_streamed(+ url=url,+ filename=filename,+ dest_dir=str(llm_server.LLM_MODELS_DIR),+ file_index=index + 1,+ total_files=len(files),+ base_percent=0,+ progress_cb=cb,+ control=control,+ ),+ )+ completed_bytes += _size++ _broadcast({"percent": 100, "status": "done"})++ except DownloadPaused:+ # Carry the last percent so the modal's bar stays where it stopped+ # instead of snapping back to 0 behind the Resume button.+ _broadcast({"paused": True, "status": "paused", "percent": state.last_msg.get("percent", 0)})+ except DownloadCancelled:+ _discard_incomplete(entry)+ _broadcast({"cancelled": True, "status": "cancelled", "percent": 0})+ except Exception as exc:+ _broadcast({"error": str(exc)})+ finally:+ if _controls.get(model_id) is control:+ _controls.pop(model_id, None)++[email protected]("/download")+async def download_model(model_id: str):+ entry = next((e for e in llm_server.load_catalog() if e["id"] == model_id), None)+ if entry is None:+ raise HTTPException(status_code=404, detail=f"Unknown catalog model: {model_id}")++ # Reconnect-safe: if this model is already downloading, attach a new watcher+ # instead of starting a second download racing the same .part file — this is+ # what lets the Model Library modal be closed and reopened mid-download.+ state = _downloads.get(model_id)+ if state is None or state.task is None or state.task.done():+ control = _new_control(model_id)+ state = _DownloadState()+ _downloads[model_id] = state+ state.task = asyncio.create_task(_run_download(model_id, entry, control, state))++ queue: asyncio.Queue[dict] = asyncio.Queue()+ state.subscribers.append(queue)+ if state.last_msg:+ queue.put_nowait(state.last_msg) # replay current progress immediately on (re)connect++ async def stream():+ try:+ while True:+ msg = await queue.get()+ yield _fmt(msg)+ if _is_terminal(msg):+ break+ finally:+ if queue in state.subscribers:+ state.subscribers.remove(queue)++ return StreamingResponse(stream(), media_type="text/event-stream")+++# ─── Engine (llama-server binary) install (SSE) ───────────────────────────────+[email protected]("/binary/install")+async def install_binary():+ if llm_server.binary_installed():+ async def already():+ yield _fmt({"percent": 100, "status": "done"})+ return StreamingResponse(already(), media_type="text/event-stream")++ control = _new_control("__binary__")++ async def stream():+ loop = asyncio.get_running_loop()+ queue: asyncio.Queue[dict] = asyncio.Queue()++ def _progress(msg: dict) -> None:+ loop.call_soon_threadsafe(queue.put_nowait, msg)++ try:+ future = loop.run_in_executor(+ None,+ lambda: llm_server.install_binary(_progress, lambda: _check_control(control)),+ )+ while not future.done():+ try:+ msg = await asyncio.wait_for(queue.get(), timeout=2.0)+ except asyncio.TimeoutError:+ continue+ else:+ yield _fmt(msg)+ await future+ while not queue.empty():+ yield _fmt(queue.get_nowait())+ except (DownloadPaused, DownloadCancelled):+ yield _fmt({"cancelled": True, "status": "cancelled"})+ except Exception as exc:+ yield _fmt({"error": str(exc)})+ finally:+ if _controls.get("__binary__") is control:+ _controls.pop("__binary__", None)++ return StreamingResponse(stream(), media_type="text/event-stream")diff --git a/apps/forge-desktop/api/routers/model.py b/apps/forge-desktop/api/routers/model.pynew file mode 100644index 000000000..aab4c3f4c--- /dev/null+++ b/apps/forge-desktop/api/routers/model.py@@ -0,0 +1,624 @@+import asyncio+import json+import time+import os+import socket+import threading+from pathlib import Path+from typing import Optional+from urllib.error import HTTPError, URLError+from urllib.request import Request, urlopen+from fastapi import APIRouter, Header, HTTPException, Request as FastAPIRequest+from fastapi.responses import StreamingResponse+from services.generator_registry import generator_registry+import services.generator_registry as registry_module+from services.extension_process import ExtensionProcess+from services.model_sources import (+ normalize_model_sources,+ resolve_download_path,+ resolve_source_destination_at_root,+ resolve_weight_storage_root,+ validate_source_file_plan,+)++router = APIRouter(tags=["model"])+++class DownloadPaused(Exception):+ pass+++class DownloadCancelled(Exception):+ pass+++_download_controls: dict[str, dict[str, threading.Event]] = {}+++def _download_control(model_id: str) -> dict[str, threading.Event]:+ """Return the current control for pause/cancel endpoints."""+ control = _download_controls.get(model_id)+ if control is None:+ control = {"pause": threading.Event(), "cancel": threading.Event()}+ _download_controls[model_id] = control+ return control+++def _new_download_control(model_id: str) -> dict[str, threading.Event]:+ """Create a fresh control for a new download session."""+ control: dict[str, threading.Event] = {"pause": threading.Event(), "cancel": threading.Event()}+ _download_controls[model_id] = control+ return control+++def _check_download_control(control: dict[str, threading.Event]) -> None:+ if control["cancel"].is_set():+ raise DownloadCancelled()+ if control["pause"].is_set():+ raise DownloadPaused()++[email protected]("/status")+async def model_status():+ """Status of the active model."""+ return await asyncio.to_thread(generator_registry.active_status)++[email protected]("/all")+async def all_models_status():+ """Status of all known models (downloaded, loaded, required VRAM)."""+ return await asyncio.to_thread(generator_registry.all_status)++[email protected]("/params")+async def model_params(model_id: Optional[str] = None):+ """Parameter schema of the active model (or a specified model)."""+ try:+ return await asyncio.to_thread(generator_registry.params_schema, model_id)+ except KeyError:+ raise HTTPException(404, f"Unknown model ID: {model_id}")++[email protected]("/switch")+async def switch_model(model_id: str):+ """Switch the active model."""+ try:+ await asyncio.to_thread(generator_registry.switch_model, model_id)+ return {"active": model_id}+ except ValueError as e:+ raise HTTPException(400, str(e))++[email protected]("/unload-all")+async def unload_all_models():+ """Unloads all models from memory to free VRAM/RAM."""+ # Off the event loop: unloading waits for any in-progress model load.+ await asyncio.to_thread(generator_registry.unload_all)+ # The local LLMs hold VRAM too; "Free memory" left them resident.+ from services.llm_server import llama_pool+ await asyncio.to_thread(llama_pool.unload_all)+ # Force Python to release memory back to the OS+ import gc+ gc.collect()+ try:+ import ctypes, sys+ if sys.platform == "win32":+ k32 = ctypes.windll.kernel32+ k32.SetProcessWorkingSetSizeEx(k32.GetCurrentProcess(), -1, -1, 0)+ except Exception:+ pass+ return {"unloaded": True}++[email protected]("/unload/{model_id:path}")+async def unload_model(model_id: str):+ """Unloads a model from memory so its files can be safely deleted."""+ try:+ gen = generator_registry.get_generator(model_id)+ except ValueError as exc:+ if model_id in generator_registry._generators:+ raise HTTPException(409, str(exc)) from exc+ return {"unloaded": True} # No runtime registered for these files.+ # unload() on ExtensionProcess deliberately swallows IPC errors; deletion+ # needs a confirmed process exit so no worker can retain file handles.+ if isinstance(gen, ExtensionProcess):+ gen.stop()+ else:+ gen.unload()+ if gen.is_loaded():+ raise HTTPException(409, "Model is still loaded; weights were preserved")+ return {"unloaded": True}++[email protected]("/hf-download/pause")+async def pause_hf_download(model_id: str):+ control = _download_control(model_id)+ control["pause"].set()+ return {"paused": True}++[email protected]("/hf-download/cancel")+async def cancel_hf_download(model_id: str):+ control = _download_control(model_id)+ control["cancel"].set()+ return {"cancelled": True}++[email protected]("/hf-download-sources")+async def hf_download_sources(request: FastAPIRequest, model_id: str):+ """Download sources into one validated node or extension-shared target."""+ try:+ body = await request.json()+ if not isinstance(body, dict):+ raise ValueError("Request body must be an object")+ raw_sources = body.get("sources")+ if raw_sources is None:+ raise ValueError("sources are required")+ sources = normalize_model_sources({"model_sources": raw_sources})+ model_root = resolve_weight_storage_root(registry_module.MODELS_DIR, model_id)+ destinations = {+ source["id"]: resolve_source_destination_at_root(+ model_root, source["destination"]+ )+ for source in sources+ }+ except (TypeError, ValueError) as exc:+ raise HTTPException(400, str(exc)) from exc++ authorization = request.headers.get("authorization", "")+ hf_token = (+ authorization[7:].strip()+ if authorization.lower().startswith("bearer ")+ else os.environ.get("HUGGING_FACE_HUB_TOKEN")+ or os.environ.get("HF_TOKEN")+ or None+ )+ control = _new_download_control(model_id)++ async def stream():+ loop = asyncio.get_running_loop()++ def _fmt(data: dict) -> str:+ return f"data: {json.dumps(data)}\n\n"++ try:+ yield _fmt({"percent": 0, "status": "Listing repository files..."})+ files_by_source: dict[str, list[str]] = {}++ for source in sources:+ _check_download_control(control)++ def _list_files(current=source):+ from huggingface_hub import list_repo_files+ listed = list_repo_files(+ current["repo_id"],+ revision=current.get("revision"),+ token=hf_token,+ )+ include = current.get("include_prefixes", [])+ skip = current.get("skip_prefixes", [])+ return [+ filename for filename in listed+ if (not include or any(filename.startswith(prefix) for prefix in include))+ if not any(filename.startswith(prefix) for prefix in skip)+ ]++ files = await loop.run_in_executor(None, _list_files)+ if not files:+ raise RuntimeError(+ f'No files found in Hugging Face repo: {source["repo_id"]}'+ )+ destination = destinations[source["id"]]+ for filename in files:+ resolve_download_path(destination, filename)+ files_by_source[source["id"]] = files++ validate_source_file_plan(sources, files_by_source)+ planned_files = [+ (source, filename)+ for source in sources+ for filename in files_by_source[source["id"]]+ ]+ total = len(planned_files)+ yield _fmt({"percent": 1, "status": f"Downloading {total} files..."})++ from huggingface_hub import hf_hub_url++ for index, (source, filename) in enumerate(planned_files):+ _check_download_control(control)+ display_file = f'{source["id"]}/{filename}'+ base_percent = 1 + round(index / total * 94)+ yield _fmt({+ "percent": base_percent,+ "file": display_file,+ "fileIndex": index + 1,+ "totalFiles": total,+ "status": f"Starting {display_file}",+ "bytesDownloaded": 0,+ "stalledSeconds": 0,+ })++ queue: asyncio.Queue[dict] = asyncio.Queue()++ def _progress(message: dict) -> None:+ message["file"] = display_file+ loop.call_soon_threadsafe(queue.put_nowait, message)++ url = hf_hub_url(+ repo_id=source["repo_id"],+ filename=filename,+ revision=source.get("revision"),+ )+ future = loop.run_in_executor(+ None,+ lambda: _download_file_streamed(+ url=url,+ filename=filename,+ dest_dir=str(destinations[source["id"]]),+ file_index=index + 1,+ total_files=total,+ base_percent=base_percent,+ progress_cb=_progress,+ control=control,+ token=hf_token,+ ),+ )+ while not future.done():+ try:+ message = await asyncio.wait_for(queue.get(), timeout=2.0)+ except asyncio.TimeoutError:+ continue+ yield _fmt(message)++ final_size = await future+ _check_download_control(control)+ yield _fmt({+ "percent": 1 + round((index + 1) / total * 94),+ "file": display_file,+ "fileIndex": index + 1,+ "totalFiles": total,+ "status": "Downloaded",+ "bytesDownloaded": final_size,+ "stalledSeconds": 0,+ })++ yield _fmt({"percent": 100, "status": "done"})+ except DownloadPaused:+ yield _fmt({"paused": True, "status": "paused"})+ except DownloadCancelled:+ for part in model_root.rglob("*.part"):+ part.unlink(missing_ok=True)+ yield _fmt({"cancelled": True, "status": "cancelled"})+ except Exception as exc:+ yield _fmt({"error": str(exc)})+ finally:+ if _download_controls.get(model_id) is control:+ _download_controls.pop(model_id, None)++ return StreamingResponse(stream(), media_type="text/event-stream")++[email protected]("/hf-download")+async def hf_download(+ repo_id: str,+ model_id: str,+ skip_prefixes: Optional[str] = None,+ include_prefixes: Optional[str] = None,+ x_hf_token: Optional[str] = Header(default=None),+):+ """+ Streams a HuggingFace Hub model download via SSE.+ Downloads into MODELS_DIR / model_id applying the filtering+ declared in the extension manifest (hf_skip_prefixes / hf_include_prefixes).++ skip_prefixes: JSON-encoded list of path prefixes to exclude.+ include_prefixes: JSON-encoded list of path prefixes to include (whitelist).+ X-HF-Token: HuggingFace access token for gated repos (from Electron settings).+ A HEADER, not a query param: uvicorn logs the full request+ line to stdout, python-bridge.ts pipes that into runtime.log,+ and `log:readAll` hands that file to the user for bug+ reports — the token used to travel all the way there.+ All fall back to the extension's manifest / environment when not supplied.++ SSE format: data: {"percent": 0-100, "file": "...", "status": "..."}+ """+ token = x_hf_token+ import json as _json+ import os+ dest_dir = str(registry_module.MODELS_DIR / model_id)+ # Prefer skip_prefixes passed directly from the client (authoritative, no registry dep)+ if skip_prefixes:+ try:+ skip_list = _json.loads(skip_prefixes)+ except Exception:+ skip_list = []+ else:+ try:+ skip_list = generator_registry.get_manifest(model_id).get("hf_skip_prefixes", [])+ except KeyError:+ skip_list = []++ if include_prefixes:+ try:+ include_list = _json.loads(include_prefixes)+ except Exception:+ include_list = []+ else:+ try:+ include_list = generator_registry.get_manifest(model_id).get("hf_include_prefixes", [])+ except KeyError:+ include_list = []++ # Token: explicit query param > env var > None+ hf_token = token or os.environ.get("HUGGING_FACE_HUB_TOKEN") or os.environ.get("HF_TOKEN") or None+ control = _new_download_control(model_id)++ async def stream():+ loop = asyncio.get_running_loop()++ def _fmt(data: dict) -> str:+ return f"data: {json.dumps(data)}\n\n"++ try:+ yield _fmt({"percent": 0, "status": "Listing repository files..."})+ _check_download_control(control)++ def _list_files():+ from huggingface_hub import list_repo_files+ return [+ f for f in list_repo_files(repo_id, token=hf_token)+ if (not include_list or any(f.startswith(p) for p in include_list))+ if not any(f.startswith(p) for p in skip_list)+ ]++ files = await loop.run_in_executor(None, _list_files)+ total = len(files)++ if total == 0:+ yield _fmt({"error": f"No files found in HuggingFace repo: {repo_id}"})+ return++ yield _fmt({"percent": 1, "status": f"Downloading {total} files..."})++ from huggingface_hub import hf_hub_url++ for i, filename in enumerate(files):+ _check_download_control(control)+ yield _fmt({+ "percent": 1 + round(i / total * 94),+ "file": filename,+ "fileIndex": i + 1,+ "totalFiles": total,+ "status": f"Starting {filename}",+ "bytesDownloaded": 0,+ "stalledSeconds": 0,+ })++ base_pct = 1 + round(i / total * 94)+ queue: asyncio.Queue[dict] = asyncio.Queue()++ def _progress(msg: dict) -> None:+ loop.call_soon_threadsafe(queue.put_nowait, msg)++ url = hf_hub_url(repo_id=repo_id, filename=filename)+ dl_future = loop.run_in_executor(+ None,+ lambda: _download_file_streamed(+ url=url,+ filename=filename,+ dest_dir=dest_dir,+ file_index=i + 1,+ total_files=total,+ base_percent=base_pct,+ progress_cb=_progress,+ control=control,+ token=hf_token,+ ),+ )++ while not dl_future.done():+ try:+ msg = await asyncio.wait_for(queue.get(), timeout=2.0)+ except asyncio.TimeoutError:+ continue+ else:+ yield _fmt(msg)++ final_size = await dl_future+ _check_download_control(control)++ # Reserve 1-95 for file downloads, leave 95-100 for finalisation+ pct = 1 + round((i + 1) / total * 94)+ yield _fmt({+ "percent": pct,+ "file": filename,+ "fileIndex": i + 1,+ "totalFiles": total,+ "status": "Downloaded",+ "bytesDownloaded": final_size,+ "stalledSeconds": 0,+ })++ yield _fmt({"percent": 100, "status": "done"})++ except DownloadPaused:+ yield _fmt({"paused": True, "status": "paused"})+ except DownloadCancelled:+ # Remove only partial files; completed files are preserved so the+ # next download can resume from where it left off.+ for part in Path(dest_dir).rglob("*.part"):+ part.unlink(missing_ok=True)+ yield _fmt({"cancelled": True, "status": "cancelled"})+ except Exception as exc:+ yield _fmt({"error": str(exc)})+ finally:+ # Only remove the control if it still belongs to this session.+ if _download_controls.get(model_id) is control:+ _download_controls.pop(model_id, None)++ return StreamingResponse(stream(), media_type="text/event-stream")+++def _download_file_streamed(+ *,+ url: str,+ filename: str,+ dest_dir: str,+ file_index: int,+ total_files: int,+ base_percent: int,+ progress_cb,+ control: dict[str, threading.Event],+ token: Optional[str] = None,+) -> int:+ final_path = Path(dest_dir) / filename+ temp_path = final_path.with_suffix(final_path.suffix + ".part")+ final_path.parent.mkdir(parents=True, exist_ok=True)++ if final_path.exists():+ if not final_path.is_file():+ raise RuntimeError(f"Download target is not a regular file: {filename}")+ existing_size = final_path.stat().st_size+ if existing_size > 0:+ return existing_size+ final_path.unlink()++ # Explicit token (from caller) > env vars > none+ hf_token = (+ token+ or os.environ.get("HF_TOKEN")+ or os.environ.get("HUGGINGFACE_HUB_TOKEN")+ or os.environ.get("HUGGING_FACE_HUB_TOKEN")+ )+ headers = {"User-Agent": "modly/0.3.1"}+ if hf_token:+ headers["Authorization"] = f"Bearer {hf_token}"++ retries = 3+ backoff = 2.0+ last_error: Exception | None = None++ for attempt in range(1, retries + 1):+ try:+ _check_download_control(control)+ existing_bytes = temp_path.stat().st_size if temp_path.exists() else 0+ request_headers = dict(headers)+ request_url = url+ if existing_bytes > 0:+ request_url = _resolve_direct_download_url(url, headers)+ request_headers["Range"] = f"bytes={existing_bytes}-"++ request = Request(request_url, headers=request_headers)+ with urlopen(request, timeout=30) as response:+ resumed = existing_bytes > 0 and getattr(response, "status", None) == 206+ if existing_bytes > 0 and not resumed:+ temp_path.unlink(missing_ok=True)+ existing_bytes = 0++ total_bytes = _response_total_bytes(response.headers, existing_bytes if resumed else 0)+ bytes_downloaded = existing_bytes+ last_emit = 0.0+ chunk_size = 1024 * 1024+ mode = "ab" if resumed else "wb"++ progress_cb({+ "percent": base_percent,+ "file": filename,+ "fileIndex": file_index,+ "totalFiles": total_files,+ "status": _download_status(bytes_downloaded, total_bytes, attempt, retries, resumed=resumed),+ "bytesDownloaded": bytes_downloaded,+ "totalBytes": total_bytes,+ "stalledSeconds": 0,+ })++ with open(temp_path, mode) as out:+ while True:+ _check_download_control(control)+ try:+ chunk = response.read(chunk_size)+ except socket.timeout as exc:+ raise TimeoutError(f"Timed out while downloading {filename}") from exc++ if not chunk:+ break++ out.write(chunk)+ bytes_downloaded += len(chunk)++ now = time.monotonic()+ if now - last_emit >= 0.5:+ progress_cb({+ "percent": base_percent,+ "file": filename,+ "fileIndex": file_index,+ "totalFiles": total_files,+ "status": _download_status(bytes_downloaded, total_bytes, attempt, retries, resumed=resumed),+ "bytesDownloaded": bytes_downloaded,+ "totalBytes": total_bytes,+ "stalledSeconds": 0,+ })+ last_emit = now++ temp_path.replace(final_path)+ return bytes_downloaded++ except (HTTPError, URLError, TimeoutError, OSError) as exc:+ last_error = exc+ preserved_bytes = temp_path.stat().st_size if temp_path.exists() else 0+ progress_cb({+ "percent": base_percent,+ "file": filename,+ "fileIndex": file_index,+ "totalFiles": total_files,+ "status": f"Retrying after error ({attempt}/{retries})…",+ "bytesDownloaded": preserved_bytes,+ "stalledSeconds": 0,+ })+ if attempt >= retries:+ break+ time.sleep(backoff)+ backoff *= 2++ raise RuntimeError(f"Failed to download {filename}: {last_error}")+++def _resolve_direct_download_url(url: str, headers: dict[str, str]) -> str:+ # HEAD request: follows redirects to get the final CDN URL without downloading the body.+ request = Request(url, headers=headers, method="HEAD")+ with urlopen(request, timeout=30) as response:+ return response.geturl()+++def _parse_content_length(raw: Optional[str]) -> Optional[int]:+ if not raw:+ return None+ try:+ return int(raw)+ except (TypeError, ValueError):+ return None+++def _download_status(downloaded: int, total: Optional[int], attempt: int, retries: int, resumed: bool = False) -> str:+ prefix = "Resuming…" if resumed and downloaded > 0 else "Downloading…"+ if total and total > 0:+ pct = min(100, round(downloaded / total * 100))+ return f"{prefix} {pct}%"+ if retries > 1 and attempt > 1:+ return f"{prefix} retry {attempt}/{retries}"+ return prefix+++def _response_total_bytes(headers, already_downloaded: int) -> Optional[int]:+ content_range = headers.get("Content-Range")+ if content_range and "/" in content_range:+ total_raw = content_range.split("/")[-1].strip()+ try:+ return int(total_raw)+ except (TypeError, ValueError):+ pass++ content_length = _parse_content_length(headers.get("Content-Length"))+ if content_length is None:+ return None+ return already_downloaded + content_lengthdiff --git a/apps/forge-desktop/api/routers/optimize.py b/apps/forge-desktop/api/routers/optimize.pynew file mode 100644index 000000000..c325ff206--- /dev/null+++ b/apps/forge-desktop/api/routers/optimize.py@@ -0,0 +1,433 @@+import hashlib+import os+import tempfile+import uuid++import numpy as np+import trimesh+from fastapi import APIRouter, HTTPException, UploadFile, File+from fastapi.responses import FileResponse, Response+from pathlib import Path+from urllib.parse import quote+from pydantic import BaseModel, Field++from services import imported_sources+# Import the module (not the name) so WORKSPACE_DIR is read at call time: the+# settings endpoint rebinds it when the user moves the workspace.+import services.generator_registry as registry+from services.mesh_ops import (+ MeshOpContext,+ MeshOpExecutionError,+ MeshOpNotFoundError,+ MeshOpResult,+ MeshOpUnavailableError,+ mesh_ops_registry,+)++router = APIRouter(tags=["optimize"])+++class OptimizeRequest(BaseModel):+ path: str # format: "{collection}/{filename}"+ target_faces: int+++class SmoothRequest(BaseModel):+ path: str # format: "{collection}/{filename}"+ iterations: int+++class MeshOpRequest(BaseModel):+ path: str+ params: dict[str, object] = Field(default_factory=dict)+++class TransformRequest(BaseModel):+ path: str # format: "{collection}/{filename}"+ matrix: list[list[float]] # row-major 4x4 world transform+++def _resolve_input_path(raw_path: str) -> Path:+ candidate = Path(raw_path)+ if candidate.is_absolute():+ resolved = candidate.resolve()+ if not resolved.exists():+ raise HTTPException(404, f"File not found: {raw_path}")+ return resolved++ resolved = (registry.WORKSPACE_DIR / raw_path).resolve()+ if not registry.is_within_workspace(resolved):+ raise HTTPException(400, "Invalid path")+ if not resolved.exists():+ raise HTTPException(404, f"File not found: {raw_path}")+ return resolved+++def _operation_output_path(input_path: Path, output_name: str) -> Path:+ workspace = registry.WORKSPACE_DIR.resolve()+ resolved_input = input_path.resolve()+ output_dir = (+ input_path.parent+ if resolved_input == workspace or workspace in resolved_input.parents+ else registry.WORKSPACE_DIR / "Workflows"+ )+ output_dir.mkdir(parents=True, exist_ok=True)+ return output_dir / output_name+++def _run_operation(+ operation_id: str,+ input_path: Path,+ params: dict[str, object],+ output_path: Path | None = None,+ preserve_visuals: bool = False,+) -> MeshOpResult:+ context = MeshOpContext(+ workspace_dir=registry.WORKSPACE_DIR,+ temp_dir=Path(tempfile.gettempdir()),+ output_path=output_path,+ preserve_visuals=preserve_visuals,+ )+ try:+ return mesh_ops_registry.run(operation_id, input_path, params, context)+ except MeshOpNotFoundError as exc:+ raise HTTPException(404, f"Unknown mesh operation: {operation_id}") from exc+ except FileNotFoundError as exc:+ raise HTTPException(404, str(exc)) from exc+ except (MeshOpUnavailableError, MeshOpExecutionError) as exc:+ raise HTTPException(503, str(exc)) from exc+ except (TypeError, ValueError) as exc:+ raise HTTPException(400, str(exc)) from exc+++def _operation_response(result: MeshOpResult) -> dict[str, object]:+ output_path = result.file_path.resolve()+ try:+ relative_path = output_path.relative_to(registry.WORKSPACE_DIR.resolve()).as_posix()+ except ValueError:+ payload: dict[str, object] = {"path": str(output_path)}+ else:+ payload = {+ "path": relative_path,+ "url": f"/workspace/{relative_path}",+ }+ payload.update(result.details)+ return payload++[email protected]("/ops")+def list_mesh_operations():+ return mesh_ops_registry.describe()++[email protected]("/op/{op_name}")+def run_mesh_operation(op_name: str, body: MeshOpRequest):+ input_path = _resolve_input_path(body.path)+ return _operation_response(+ _run_operation(op_name, input_path, body.params)+ )++[email protected]("/mesh")+def optimize_mesh(body: OptimizeRequest):+ target_faces = max(100, min(500_000, body.target_faces))+ input_path = _resolve_input_path(body.path)+ output_path = _operation_output_path(+ input_path,+ f"{input_path.stem}_opt{target_faces}.glb",+ )+ response = _operation_response(+ _run_operation(+ "decimate",+ input_path,+ {"target_faces": target_faces},+ output_path,+ )+ )+ return {+ "url": response.get("url"),+ "face_count": response.get("face_count", 0),+ }++[email protected]("/smooth")+def smooth_mesh(body: SmoothRequest):+ iterations = max(1, min(20, body.iterations))+ input_path = _resolve_input_path(body.path)+ output_path = _operation_output_path(+ input_path,+ f"{input_path.stem}_smooth{iterations}.glb",+ )+ response = _operation_response(+ _run_operation(+ "smooth",+ input_path,+ {"iterations": iterations, "lambda_": 0.5, "mode": "laplacian"},+ output_path,+ preserve_visuals=True,+ )+ )+ return {"url": response.get("url")}++[email protected]("/transform")+def transform_mesh(body: TransformRequest):+ # Bake an interactive-gizmo transform into the GLB at scene level so it+ # persists to export. Pure trimesh — no pymeshlab needed.+ input_path = _resolve_input_path(body.path)++ matrix = np.asarray(body.matrix, dtype=float)+ if matrix.shape != (4, 4):+ raise HTTPException(400, "matrix must be a 4x4 array")+ if not np.all(np.isfinite(matrix)):+ raise HTTPException(400, "matrix contains non-finite values")++ # Keep the loaded result as-is (Scene when textured/multi-geometry) so+ # apply_transform preserves materials and UVs.+ loaded = trimesh.load(str(input_path))+ loaded.apply_transform(matrix)++ stem = input_path.stem+ output_name = f"{stem}_xf_{uuid.uuid4().hex[:8]}.glb"+ workspace = registry.WORKSPACE_DIR.resolve()+ output_dir = input_path.parent if registry.is_within_workspace(input_path.resolve()) else workspace / "Workflows"+ output_dir.mkdir(parents=True, exist_ok=True)+ output_path = output_dir / output_name+ loaded.export(str(output_path))++ rel = output_path.resolve().relative_to(workspace).as_posix()+ return {"url": f"/workspace/{rel}"}+++class ImportByPathRequest(BaseModel):+ path: str # absolute path on disk+++# ---------------------------------------------------------------------------+# Gaussian Splatting support+#+# A 3DGS .ply is a point cloud whose colour lives in SH coefficients+# (f_dc_*), not in a texture or vertex colours — trimesh strips all of it and+# yields a blank blob. Detect those files by their header and convert them to+# the standard binary .splat format (rowLength = 32) read by the splat viewer:+# pos 3 × float32 (offset 0)+# scale 3 × float32 (offset 12) = exp(scale_i)+# rgba 4 × uint8 (offset 24) = 0.5 + C0·f_dc, sigmoid(opacity)+# rot 4 × uint8 (offset 28) = normalised quaternion (w,x,y,z)+# ---------------------------------------------------------------------------++_SH_C0 = 0.28209479177387814++# Bump when _convert_gaussian_ply_to_splat changes, to invalidate cached .splats+# whose source .ply mtime is unchanged.+_SPLAT_CONV_VERSION = 2++_PLY_TYPE_MAP = {+ "char": "i1", "uchar": "u1", "int8": "i1", "uint8": "u1",+ "short": "i2", "ushort": "u2", "int16": "i2", "uint16": "u2",+ "int": "i4", "uint": "u4", "int32": "i4", "uint32": "u4",+ "float": "f4", "float32": "f4", "double": "f8", "float64": "f8",+}+++def _is_gaussian_ply(file_path: Path) -> bool:+ try:+ with open(file_path, "rb") as f:+ head = f.read(2048)+ except OSError:+ return False+ if not head.startswith(b"ply"):+ return False+ text = head.split(b"end_header")[0].decode("ascii", "ignore")+ return all(marker in text for marker in ("f_dc_0", "scale_0", "rot_0"))+++def _convert_gaussian_ply_to_splat(ply_path: Path, out_path: str) -> None:+ import numpy as np++ with open(ply_path, "rb") as f:+ if f.readline().strip() != b"ply":+ raise ValueError("not a ply file")+ fmt = None+ count = 0+ element = None+ props: list[tuple[str, str]] = []+ while True:+ line = f.readline()+ if not line:+ raise ValueError("unexpected EOF in ply header")+ parts = line.split()+ if not parts:+ continue+ kw = parts[0]+ if kw == b"format":+ fmt = parts[1]+ elif kw == b"element":+ element = parts[1]+ if element == b"vertex":+ count = int(parts[2])+ elif kw == b"property" and element == b"vertex":+ # GS plys use only scalar float properties (no lists)+ props.append((parts[2].decode(), parts[1].decode()))+ elif kw == b"end_header":+ break+ if fmt != b"binary_little_endian":+ raise ValueError(f"unsupported ply format: {fmt!r}")++ dtype = np.dtype([(n, "<" + _PLY_TYPE_MAP[t]) for n, t in props])+ data = np.frombuffer(f.read(count * dtype.itemsize), dtype=dtype, count=count)++ def col(*names):+ return np.stack([data[n].astype(np.float32) for n in names], axis=1)++ xyz = col("x", "y", "z")+ scale = np.exp(col("scale_0", "scale_1", "scale_2"))++ # Normalise into the viewer's space: a 3DGS lives in an arbitrary world+ # frame (offset origin, any scale) and often has a few far-away "floater"+ # splats. Centre x/z on the robust 1–99 percentile box and scale to fit so+ # the model always lands in front of the camera (meshes get this for free+ # via Box3 centring; splats don't). The gaussian sizes scale with it.+ lo = np.percentile(xyz, 1, axis=0)+ hi = np.percentile(xyz, 99, axis=0)+ center = (lo + hi) / 2.0+ extent = float(np.max(hi - lo))+ factor = (2.0 / extent) if extent > 1e-6 else 1.0+ xyz = (xyz - center) * factor+ scale = scale * factor++ # Stand the model on the grid (y = 0), matching the mesh viewer. The client+ # flips the splat 180° about Z (3DGS is Y-down), negating Y so the robust+ # *top* (99th pct) of this space becomes the floor; shift it to 0 → feet on the grid.+ xyz[:, 1] -= float(np.percentile(xyz[:, 1], 99))+ rgb = np.clip((0.5 + _SH_C0 * col("f_dc_0", "f_dc_1", "f_dc_2")) * 255.0, 0, 255)+ alpha = np.clip(1.0 / (1.0 + np.exp(-data["opacity"].astype(np.float32))) * 255.0, 0, 255)+ rot = col("rot_0", "rot_1", "rot_2", "rot_3")+ rot /= np.linalg.norm(rot, axis=1, keepdims=True)+ rot_u8 = np.clip(rot * 128.0 + 128.0, 0, 255)++ out = np.zeros(count, dtype=[+ ("pos", "<f4", 3), ("scale", "<f4", 3), ("rgba", "u1", 4), ("rot", "u1", 4),+ ])+ out["pos"] = xyz+ out["scale"] = scale+ out["rgba"][:, :3] = rgb.astype(np.uint8)+ out["rgba"][:, 3] = alpha.astype(np.uint8)+ out["rot"] = rot_u8.astype(np.uint8)+ with open(out_path, "wb") as f:+ f.write(out.tobytes())++[email protected]("/import-by-path")+async def import_mesh_by_path(body: ImportByPathRequest):+ file_path = Path(body.path)+ if not file_path.is_file():+ raise HTTPException(400, "File not found")++ ext = file_path.suffix.lstrip(".").lower()+ if ext not in ("glb", "obj", "stl", "ply", "splat"):+ raise HTTPException(400, f"Unsupported format: {ext}")++ # Gaussian Splat: serve a .splat as-is, convert a GS .ply to .splat.+ # The viewer detects splats by the .splat/.ply extension in the served URL.+ if ext == "splat":+ return {"url": f"/optimize/serve-file?path={quote(str(file_path))}"}++ if ext == "ply" and _is_gaussian_ply(file_path):+ tmp_dir = tempfile.mkdtemp(prefix="modly_import_")+ output_path = os.path.join(tmp_dir, "splat.splat")+ try:+ _convert_gaussian_ply_to_splat(file_path, output_path)+ except Exception as err: # noqa: BLE001 — surface a clean error, never 500-crash+ raise HTTPException(400, f"Unrecognised Gaussian .ply: {err}")+ return {"url": f"/optimize/serve-file?path={quote(output_path)}"}++ if ext == "glb":+ # Serve the original file directly — no copy+ imported_sources.register(file_path, file_path)+ return {"url": f"/optimize/serve-file?path={quote(str(file_path))}"}++ # Mesh ply / obj / stl: convert to GLB in a temp directory (not the workspace)+ tmp_dir = tempfile.mkdtemp(prefix="modly_import_")+ output_path = os.path.join(tmp_dir, "mesh.glb")+ loaded = trimesh.load(str(file_path))+ loaded.export(output_path)+ # Remember the ORIGINAL extension: this conversion changes the container but+ # not the axes, so a .stl imported here still holds Z-up data despite the+ # .glb suffix, and must not be rotated as if it were glTF.+ imported_sources.register(output_path, file_path)+ return {"url": f"/optimize/serve-file?path={quote(output_path)}"}+++_SERVE_MEDIA_TYPES = {+ ".glb": "model/gltf-binary",+ ".splat": "application/octet-stream",+}++[email protected]("/serve-file")+def serve_file(path: str):+ file_path = Path(path)+ if not file_path.is_file():+ raise HTTPException(404, "File not found")+ media_type = _SERVE_MEDIA_TYPES.get(file_path.suffix.lower())+ if media_type is None:+ raise HTTPException(400, "Only GLB and SPLAT files can be served")+ return FileResponse(str(file_path), media_type=media_type)++[email protected]("/ply-to-splat")+def ply_to_splat(path: str):+ """Serve a Gaussian-Splat source as binary .splat for the splat viewer.++ `path` is workspace-relative (e.g. "Workflows/foo.ply"). A .splat is served+ as-is; a GS .ply is normalised + converted (cached by mtime + conv version).+ """+ src = (registry.WORKSPACE_DIR.resolve() / path).resolve()+ if not registry.is_within_workspace(src):+ raise HTTPException(400, "Invalid path")+ if not src.is_file():+ raise HTTPException(404, "File not found")++ if src.suffix.lower() == ".splat":+ return FileResponse(str(src), media_type="application/octet-stream")+ if src.suffix.lower() != ".ply" or not _is_gaussian_ply(src):+ raise HTTPException(400, "Not a Gaussian .ply")++ key = hashlib.md5(f"{src}:{int(src.stat().st_mtime)}:{_SPLAT_CONV_VERSION}".encode()).hexdigest()+ out = Path(tempfile.gettempdir()) / f"modly_splat_{key}.splat"+ if not out.is_file():+ try:+ _convert_gaussian_ply_to_splat(src, str(out))+ except Exception as err: # noqa: BLE001+ raise HTTPException(400, f"Unrecognised Gaussian .ply: {err}")+ return FileResponse(str(out), media_type="application/octet-stream")++[email protected]("/export")+def export_mesh(path: str, format: str):+ if format not in ("obj", "stl", "ply"):+ raise HTTPException(400, "Supported formats: obj, stl, ply")++ input_path = (registry.WORKSPACE_DIR / path).resolve()+ if not registry.is_within_workspace(input_path):+ raise HTTPException(400, "Invalid path")+ if not input_path.exists():+ raise HTTPException(404, f"File not found: {path}")++ loaded = trimesh.load(str(input_path))+ if isinstance(loaded, trimesh.Scene):+ geoms = list(loaded.geometry.values())+ mesh = trimesh.util.concatenate(geoms) if len(geoms) > 1 else geoms[0]+ else:+ mesh = loaded++ data = mesh.export(file_type=format)+ stem = input_path.stem+ mime = "text/plain" if format == "obj" else "application/octet-stream"+ # trimesh exports ply as bytes even in text mode — octet-stream is fine for all binary formats+ return Response(+ content=data,+ media_type=mime,+ headers={"Content-Disposition": f'attachment; filename="{stem}.{format}"'},+ )diff --git a/apps/forge-desktop/api/routers/settings.py b/apps/forge-desktop/api/routers/settings.pynew file mode 100644index 000000000..9106ad2d6--- /dev/null+++ b/apps/forge-desktop/api/routers/settings.py@@ -0,0 +1,56 @@+import asyncio+import os+from fastapi import APIRouter+from pydantic import BaseModel+from pathlib import Path+from typing import Optional++import services.generator_registry as reg_module++router = APIRouter(prefix="/settings", tags=["settings"])+++class PathsUpdate(BaseModel):+ models_dir: Optional[str] = None+ workspace_dir: Optional[str] = None+++class TokenUpdate(BaseModel):+ token: str++[email protected]("/paths")+async def get_paths():+ return {+ "models_dir": str(reg_module.MODELS_DIR),+ "workspace_dir": str(reg_module.WORKSPACE_DIR),+ }++[email protected]("/paths")+async def update_paths(body: PathsUpdate):+ # Off the event loop: changing paths waits for any in-progress model load.+ await asyncio.to_thread(+ reg_module.generator_registry.update_paths,+ Path(body.models_dir) if body.models_dir else None,+ Path(body.workspace_dir) if body.workspace_dir else None,+ )+ return {+ "models_dir": str(reg_module.MODELS_DIR),+ "workspace_dir": str(reg_module.WORKSPACE_DIR),+ }++[email protected]("/hf-token")+async def update_hf_token(body: TokenUpdate):+ """+ Update the HuggingFace token in this process's environment so that+ extension subprocesses spawned after this call inherit the new token.+ """+ if body.token:+ os.environ["HUGGING_FACE_HUB_TOKEN"] = body.token+ os.environ["HF_TOKEN"] = body.token+ else:+ os.environ.pop("HUGGING_FACE_HUB_TOKEN", None)+ os.environ.pop("HF_TOKEN", None)+ return {"ok": True}diff --git a/apps/forge-desktop/api/routers/status.py b/apps/forge-desktop/api/routers/status.pynew file mode 100644index 000000000..e54b0a0b9--- /dev/null+++ b/apps/forge-desktop/api/routers/status.py@@ -0,0 +1,9 @@+from fastapi import APIRouter++router = APIRouter(tags=["health"])++[email protected]("/health")+async def health():+ """Health check — used by Electron to know the API is ready."""+ return {"status": "ok"}diff --git a/apps/forge-desktop/api/routers/workflow_runs.py b/apps/forge-desktop/api/routers/workflow_runs.pynew file mode 100644index 000000000..ba654a53b--- /dev/null+++ b/apps/forge-desktop/api/routers/workflow_runs.py@@ -0,0 +1,110 @@+import json+import threading+import uuid+from typing import Optional+from fastapi import APIRouter, BackgroundTasks, File, Form, HTTPException, UploadFile+from pydantic import BaseModel++from routers.generation import (+ VALID_REMESH_MODES,+ _cancel_events,+ _jobs,+ _purge_old_jobs,+ _run_generation,+ cancel_job,+ sanitize_collection,+)+from schemas.generation import JobStatus+from services.generator_registry import generator_registry++router = APIRouter(tags=["workflow-runs"])+++class WorkflowRunStatus(BaseModel):+ run_id: str+ status: str+ progress: int = 0+ step: Optional[str] = None+ output_url: Optional[str] = None+ error: Optional[str] = None+ scene_candidate: Optional[dict] = None++[email protected]("/from-image")+async def create_run_from_image(+ background_tasks: BackgroundTasks,+ image: UploadFile = File(...),+ model_id: str = Form("sf3d"),+ # Where the result is filed. The legacy /generate/from-image already accepts this; the+ # canonical endpoint hardcoded "Default", so a run driven over REST/MCP landed in a folder+ # the Library does not index and stayed invisible in the app (#238). Same field, same+ # sanitizer, so both surfaces route output the same way.+ collection: str = Form("Default"),+ params: str = Form("{}"),+):+ if not image.content_type or not image.content_type.startswith("image/"):+ raise HTTPException(400, "File must be an image")++ try:+ model_params = json.loads(params)+ except (json.JSONDecodeError, TypeError):+ model_params = {}++ full_params = {+ "remesh": "quad",+ "enable_texture": False,+ "texture_resolution": 1024,+ **model_params,+ }++ # Keep the same request validation as /generate/from-image before filing a job.+ if full_params["remesh"] not in VALID_REMESH_MODES:+ raise HTTPException(400, "remesh must be 'quad', 'triangle', or 'none'")++ collection = sanitize_collection(collection)++ try:+ generator_registry.get_generator(model_id)+ output_kind = generator_registry.get_manifest(model_id).get("output", "mesh")+ except ValueError as e:+ raise HTTPException(400, str(e))++ job_id = str(uuid.uuid4())+ image_bytes = await image.read()++ _purge_old_jobs()++ _jobs[job_id] = JobStatus(job_id=job_id, status="pending", progress=0)+ _cancel_events[job_id] = threading.Event()++ background_tasks.add_task(+ _run_generation, job_id, image_bytes, full_params, collection, output_kind, model_id+ )++ return {"run_id": job_id, "status": "pending"}++[email protected]("/{run_id}", response_model=WorkflowRunStatus)+async def get_run(run_id: str):+ job = _jobs.get(run_id)+ if not job:+ raise HTTPException(404, f"Run {run_id} not found")++ scene_candidate = None+ if job.status == "done" and job.output_url:+ scene_candidate = {"workspace_path": job.output_url.removeprefix("/workspace/")}++ return WorkflowRunStatus(+ run_id=job.job_id,+ status=job.status,+ progress=job.progress,+ step=job.step,+ output_url=job.output_url,+ error=job.error,+ scene_candidate=scene_candidate,+ )++[email protected]("/{run_id}/cancel")+async def cancel_run(run_id: str):+ return await cancel_job(run_id)diff --git a/apps/forge-desktop/api/runner.py b/apps/forge-desktop/api/runner.pynew file mode 100644index 000000000..93feef5df--- /dev/null+++ b/apps/forge-desktop/api/runner.py@@ -0,0 +1,321 @@+"""+Modly Extension Runner — generic subprocess entry point.++Runs inside the extension's own venv. Loaded by ExtensionProcess via:+ {venv_python} {runner_path}++Environment variables (set by ExtensionProcess):+ EXTENSION_DIR — absolute path to the extension directory+ MODELS_DIR — where model weights are stored+ WORKSPACE_DIR — where generated files are saved+ MODLY_API_DIR — path to Modly's api/ dir (so generator.py can import+ from services.generators.base)++Protocol: newline-delimited JSON on stdin/stdout.+Stderr is captured separately by ExtensionProcess for logging.+"""+import sys+import json+import os+import traceback+import base64+import threading+import importlib.util+from pathlib import Path++# ------------------------------------------------------------------ #+# Env+# ------------------------------------------------------------------ #++EXT_DIR = Path(os.environ["EXTENSION_DIR"])+MODELS_DIR = Path(os.environ.get("MODELS_DIR", Path.home() / ".modly" / "models"))+WORKSPACE_DIR = Path(os.environ.get("WORKSPACE_DIR", Path.home() / ".modly" / "workspace"))+MODLY_API_DIR = os.environ.get("MODLY_API_DIR", "")+# MODEL_DIR is set by ExtensionProcess to match its own model_dir (composite node id path).+# Falls back to MODELS_DIR/manifest_id for standalone/legacy use.+_MODEL_DIR_OVERRIDE = os.environ.get("MODEL_DIR", "")+_MODEL_ID_OVERRIDE = os.environ.get("MODEL_ID", "")+_MODEL_NODE_ID_OVERRIDE = os.environ.get("MODEL_NODE_ID", "")+try:+ _SHARED_MODEL_DIRS = {+ str(group_id): Path(path)+ for group_id, path in json.loads(os.environ.get("SHARED_MODEL_DIRS", "{}")).items()+ }+except (AttributeError, TypeError, ValueError, json.JSONDecodeError):+ _SHARED_MODEL_DIRS = {}++# Inject Modly's api/ so generator.py can do:+# from services.generators.base import BaseGenerator, ...+if MODLY_API_DIR and MODLY_API_DIR not in sys.path:+ sys.path.insert(0, MODLY_API_DIR)++# Inject ext dir so generator.py can import local vendor modules+if str(EXT_DIR) not in sys.path:+ sys.path.insert(0, str(EXT_DIR))++# Match the UTF-8 pipe readers on the parent side even when the OS locale+# is a legacy codepage (cp1252/cp932 on Windows). Without this, any Unicode+# print() from a generator (e.g. tqdm output) crashes the worker.+from services.stdio_utf8 import ensure_utf8_stdio+ensure_utf8_stdio()+++# ------------------------------------------------------------------ #+# Protocol helpers+# ------------------------------------------------------------------ #++def send(msg: dict) -> None:+ sys.stdout.write(json.dumps(msg) + "\n")+ sys.stdout.flush()+++def recv():+ """Yields parsed JSON messages from stdin, one per line."""+ for raw in sys.stdin:+ raw = raw.strip()+ if raw:+ try:+ yield json.loads(raw)+ except json.JSONDecodeError as exc:+ send({"type": "log", "level": "error",+ "message": f"Runner: invalid JSON on stdin: {exc}"})+++# ------------------------------------------------------------------ #+# Generator loader+# ------------------------------------------------------------------ #++def load_generator(manifest: dict):+ """Dynamically load the generator class from generator.py."""+ spec = importlib.util.spec_from_file_location(+ "generator", EXT_DIR / "generator.py"+ )+ mod = importlib.util.module_from_spec(spec)+ sys.modules["generator"] = mod+ spec.loader.exec_module(mod)+ return getattr(mod, manifest["generator_class"])+++def _select_node(+ manifest: dict, model_dir_override: str, node_id_override: str = ""+) -> dict:+ nodes = manifest.get("nodes") or []+ if nodes and node_id_override:+ return next((n for n in nodes if n.get("id") == node_id_override), nodes[0])+ if nodes and model_dir_override:+ node_id = Path(model_dir_override).name+ return next((n for n in nodes if n.get("id") == node_id), nodes[0])+ if nodes:+ return nodes[0]+ return {}+++def _resolve_ready_schema(GenClass, node: dict, manifest: dict) -> list:+ try:+ return GenClass.params_schema()+ except Exception:+ return node.get("params_schema") or manifest.get("params_schema", [])+++def _generator_is_loaded(gen) -> bool:+ """+ Best-effort read of the generator's loaded state.++ Never raises: this is used on the error path, where a generator left in a+ half-initialised state can make is_loaded() itself blow up. An unreadable+ state is reported as "not loaded" so the caller reloads rather than reusing+ a worker that may be broken.+ """+ try:+ return bool(gen.is_loaded())+ except Exception:+ return False+++def _ensure_model_loaded(gen) -> bool:+ """+ Guarantees the model is in memory before inference. Returns True if a+ reload was needed.++ Texture pipelines are built lazily on first use, and extensions typically+ free the shape pipeline first to make room for them. When that setup fails+ (a missing `xatlas` being the common case) the generator is left with+ _model = None, yet the worker process stays alive and both ExtensionProcess+ and GeneratorRegistry still consider it loaded — so load() is never called+ again and every later generate() dies with++ TypeError: 'NoneType' object is not callable++ until the process is killed by hand. Re-loading here mirrors what+ GeneratorRegistry.get_active() already does host-side, which makes a failed+ setup recoverable on the next attempt instead of permanently poisoning the+ worker.+ """+ if _generator_is_loaded(gen):+ return False+ gen.load()+ return True+++def _apply_manifest_metadata(gen, manifest: dict, node: dict) -> None:+ gen.hf_repo = node.get("hf_repo") or manifest.get("hf_repo", "")+ gen.hf_skip_prefixes = node.get("hf_skip_prefixes") or manifest.get("hf_skip_prefixes", [])+ gen.download_check = node.get("download_check") or manifest.get("download_check", "")+ gen._params_schema = node.get("params_schema") or manifest.get("params_schema", [])+++def decode_model_input(msg: dict):+ """Decode legacy image bytes or revalidate a typed artifact in the worker."""+ if "input" not in msg:+ return base64.b64decode(msg["image_b64"])+ value = msg["input"]+ if not isinstance(value, dict) or set(value) != {"kind", "path"}:+ raise ValueError("Typed artifact input must contain exactly kind and path")+ from services.artifact_input import TypedArtifactInput, revalidate_artifact_input+ typed = TypedArtifactInput(kind=value.get("kind"), path=Path(value.get("path", "")))+ return revalidate_artifact_input(WORKSPACE_DIR, typed)+++def validate_requested_model(msg: dict, manifest: dict, node: dict) -> None:+ """Reject requests routed to a worker for a different manifest node."""+ requested = msg.get("model_id")+ if requested is None: # Backward compatibility with already-running legacy hosts.+ return+ expected = manifest["id"]+ if node.get("id"):+ expected = f"{expected}/{node['id']}"+ if requested != expected:+ raise ValueError(+ f"Generation request model '{requested}' does not match worker model '{expected}'"+ )+++# ------------------------------------------------------------------ #+# Main loop+# ------------------------------------------------------------------ #++def main() -> None:+ manifest = json.loads((EXT_DIR / "manifest.json").read_text(encoding="utf-8"))+ model_id = _MODEL_ID_OVERRIDE or manifest["id"]++ try:+ GenClass = load_generator(manifest)+ except Exception:+ send({"type": "error", "id": None,+ "message": "Failed to load generator class",+ "traceback": traceback.format_exc()})+ return++ # Support both flat manifest (legacy) and nodes[] format. The host passes an+ # explicit node id; MODEL_DIR name inference remains only as a legacy fallback.+ node = _select_node(manifest, _MODEL_DIR_OVERRIDE, _MODEL_NODE_ID_OVERRIDE)++ # Announce readiness and send params_schema so ExtensionProcess+ # can serve it without needing to query the subprocess later.+ # We try to get it from the generator class (may be a classmethod),+ # falling back to the selected node, then to the top-level manifest.+ send({"type": "ready", "params_schema": _resolve_ready_schema(GenClass, node, manifest)})++ # Use MODEL_DIR env var (set by ExtensionProcess) when available so the+ # generator uses the exact same path that is_downloaded() checks against.+ # Falls back to MODELS_DIR/manifest_id for legacy / standalone use.+ model_dir = Path(_MODEL_DIR_OVERRIDE) if _MODEL_DIR_OVERRIDE else MODELS_DIR / model_id+ gen = GenClass(model_dir, WORKSPACE_DIR)+ gen.MODEL_ID = model_id+ gen.MODEL_NODE_ID = node.get("id", "")+ gen.shared_model_dirs = dict(_SHARED_MODEL_DIRS)+ _apply_manifest_metadata(gen, manifest, node)++ # Active cancel events keyed by request id+ _cancel: dict[str, threading.Event] = {}++ for msg in recv():+ action = msg.get("action")+ rid = msg.get("id")++ try:+ # ---- load ------------------------------------------------+ if action == "load":+ gen.load()+ send({"type": "loaded"})++ # ---- generate --------------------------------------------+ elif action == "generate":+ validate_requested_model(msg, manifest, node)+ cancel_evt = threading.Event()+ _cancel[rid] = cancel_evt+ model_input = decode_model_input(msg)+ params = msg.get("params", {})+ if hasattr(model_input, "kind"):+ if not isinstance(params, dict):+ raise ValueError("Model params must be an object")+ from services.artifact_input import RESERVED_ARTIFACT_PARAMS+ params = {key: value for key, value in params.items()+ if key not in RESERVED_ARTIFACT_PARAMS}+ params["scene_manifest_path"] = str(model_input.path)+ if msg.get("outputs_dir"):+ gen.outputs_dir = Path(msg["outputs_dir"])+ gen.outputs_dir.mkdir(parents=True, exist_ok=True)++ def progress_cb(pct: int, step: str = "") -> None:+ send({"type": "progress", "id": rid, "pct": pct, "step": step})++ try:+ if _ensure_model_loaded(gen):+ send({"type": "log", "level": "warning",+ "message": ("Model was not loaded (earlier setup failure?); "+ "reloaded before generating.")})+ if hasattr(model_input, "kind"):+ output_path = gen.generate_artifact(+ model_input.kind, model_input.path, params, progress_cb, cancel_evt+ )+ else:+ output_path = gen.generate(model_input, params, progress_cb, cancel_evt)+ if node.get("output") == "scene":+ from services.scene_input import validate_scene_input+ resolved_output = Path(output_path).resolve(strict=True)+ try:+ relative_output = resolved_output.relative_to(WORKSPACE_DIR.resolve(strict=True))+ except (OSError, ValueError) as exc:+ raise ValueError("Generated scene output is outside the workspace") from exc+ output_path = validate_scene_input(WORKSPACE_DIR, relative_output.as_posix())+ send({"type": "done", "id": rid, "output_path": str(output_path)})+ except Exception as exc:+ # Detect GenerationCancelled by name to avoid import issues+ if type(exc).__name__ == "GenerationCancelled":+ send({"type": "cancelled", "id": rid})+ else:+ # Report whether the model survived the failure so the+ # host can drop its cached "loaded" flag and reload+ # instead of reusing a worker whose _model is None.+ send({"type": "error", "id": rid,+ "message": str(exc),+ "traceback": traceback.format_exc(),+ "loaded": _generator_is_loaded(gen)})+ finally:+ _cancel.pop(rid, None)++ # ---- cancel ----------------------------------------------+ elif action == "cancel":+ evt = _cancel.get(rid)+ if evt:+ evt.set()++ # ---- unload ----------------------------------------------+ elif action == "unload":+ gen.unload()+ send({"type": "unloaded"})++ # ---- shutdown --------------------------------------------+ elif action == "shutdown":+ gen.unload()+ break++ except Exception:+ send({"type": "error", "id": rid,+ "message": "Unexpected runner error",+ "traceback": traceback.format_exc()})+++if __name__ == "__main__":+ main()diff --git a/apps/forge-desktop/api/schemas/__init__.py b/apps/forge-desktop/api/schemas/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/apps/forge-desktop/api/schemas/generation.py b/apps/forge-desktop/api/schemas/generation.pynew file mode 100644index 000000000..04c18c858--- /dev/null+++ b/apps/forge-desktop/api/schemas/generation.py@@ -0,0 +1,20 @@+from typing import Any, Literal, Optional+from pydantic import BaseModel, Field+++class JobStatus(BaseModel):+ job_id: str+ status: Literal["pending", "running", "done", "error", "cancelled"]+ progress: int = 0 # 0–100+ step: Optional[str] = None # Human-readable current step+ output_url: Optional[str] = None+ error: Optional[str] = None+++class GenerateFromArtifactRequest(BaseModel):+ """Generic typed-artifact request. Only scene is public in this release."""+ input_kind: Literal["scene"]+ input_path: str+ model_id: str+ collection: str = "Workflows"+ params: dict[str, Any] = Field(default_factory=dict)diff --git a/apps/forge-desktop/api/services/__init__.py b/apps/forge-desktop/api/services/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/apps/forge-desktop/api/services/artifact_input.py b/apps/forge-desktop/api/services/artifact_input.pynew file mode 100644index 000000000..05f4661d4--- /dev/null+++ b/apps/forge-desktop/api/services/artifact_input.py@@ -0,0 +1,34 @@+"""Typed model artifact inputs shared by the API, worker bridge, and runner."""+from dataclasses import dataclass+from pathlib import Path++from services.scene_input import validate_scene_input++SUPPORTED_ARTIFACT_INPUTS = frozenset({"scene"})++# Transport parameters set by the host; callers must not be able to forge them.+RESERVED_ARTIFACT_PARAMS = frozenset({+ "artifact_path", "input_kind", "input_path", "scene_path", "scene_manifest_path",+})+++@dataclass(frozen=True)+class TypedArtifactInput:+ kind: str+ path: Path+++def validate_artifact_input(workspace: Path, kind: str, input_path: str) -> TypedArtifactInput:+ if kind not in SUPPORTED_ARTIFACT_INPUTS:+ raise ValueError(f"Unsupported artifact input kind: {kind}")+ if kind == "scene":+ return TypedArtifactInput(kind="scene", path=validate_scene_input(workspace, input_path))+ raise ValueError(f"Unsupported artifact input kind: {kind}")+++def revalidate_artifact_input(workspace: Path, value: TypedArtifactInput) -> TypedArtifactInput:+ try:+ relative = value.path.resolve(strict=True).relative_to(workspace.resolve(strict=True))+ except (OSError, ValueError) as exc:+ raise ValueError("Artifact input is outside the workspace") from exc+ return validate_artifact_input(workspace, value.kind, relative.as_posix())diff --git a/apps/forge-desktop/api/services/extension_process.py b/apps/forge-desktop/api/services/extension_process.pynew file mode 100644index 000000000..5eaed4b87--- /dev/null+++ b/apps/forge-desktop/api/services/extension_process.py@@ -0,0 +1,473 @@+"""+ExtensionProcess — manages a generator running in an isolated subprocess.++Each extension runs in its own venv via runner.py.+Communication is done via newline-delimited JSON on stdin/stdout.++Interface is intentionally compatible with direct BaseGenerator usage+so GeneratorRegistry can treat both transparently.+"""+import base64+import json+import os+import platform+import queue+import re+import subprocess+import sys+import threading+import uuid+from pathlib import Path+from typing import Callable, Optional++_RUNNER_PATH = Path(__file__).parent.parent / "runner.py"+_MISSING_MODULE_RE = re.compile(r"No module named ['\"]([^'\"]+)['\"]")+_AUTO_REPAIR_PACKAGE_MAP = {+ "PIL": "Pillow",+}+++def _venv_python(ext_dir: Path) -> Path:+ """Returns the path to the venv's Python executable."""+ if platform.system() == "Windows":+ return ext_dir / "venv" / "Scripts" / "python.exe"+ return ext_dir / "venv" / "bin" / "python"+++class ExtensionProcess:+ """+ Wraps an extension subprocess. Presents the same interface as a+ direct generator (load / unload / generate / is_loaded / params_schema).+ """++ def __init__(self, ext_dir: Path, manifest: dict) -> None:+ self.ext_dir = ext_dir+ self.manifest = manifest+ self.model_dir = None # set by registry after init+ self.outputs_dir = None # set by registry after init+ self.shared_model_dirs: dict[str, Path] = {}++ self._proc: Optional[subprocess.Popen] = None+ self._queue: queue.Queue = queue.Queue()+ self._lock: threading.Lock = threading.Lock()+ self._loaded: bool = False++ # Mirrors BaseGenerator attributes used by the registry+ self.hf_repo = manifest.get("hf_repo", "")+ self.hf_skip_prefixes = manifest.get("hf_skip_prefixes", [])+ self.download_check = manifest.get("download_check", "")+ self._params_schema = manifest.get("params_schema", [])++ # Public metadata+ self.MODEL_ID = manifest.get("id", "")+ self.DISPLAY_NAME = manifest.get("name", "")+ self.VRAM_GB = manifest.get("vram_gb", 0)++ # ------------------------------------------------------------------ #+ # Subprocess lifecycle+ # ------------------------------------------------------------------ #++ def _build_env(self) -> dict:+ from services.generator_registry import MODELS_DIR, WORKSPACE_DIR+ env = os.environ.copy()+ env["EXTENSION_DIR"] = str(self.ext_dir)+ env["MODELS_DIR"] = str(MODELS_DIR)+ env["WORKSPACE_DIR"] = str(WORKSPACE_DIR)+ env["MODLY_API_DIR"] = str(Path(__file__).parent.parent)+ # Lets extensions call back into the Modly API (e.g. /llm/chat for the shared LLM).+ env.setdefault("MODLY_API_URL", "http://127.0.0.1:8765")+ # Force the worker's Python stdio to UTF-8 so it matches the UTF-8+ # pipe readers below regardless of the OS locale (cp1252/cp932).+ env["PYTHONUTF8"] = "1"+ env["PYTHONIOENCODING"] = "utf-8"+ if sys.platform == "darwin":+ env.setdefault("NUMBA_DISABLE_JIT", "1")+ # Must be set before the subprocess's first `import torch` — PyTorch+ # reads this once to decide whether MPS ops with no Metal kernel+ # (e.g. 3D pooling) fall back to CPU or raise NotImplementedError.+ # Setting it inside generator.py is too late, since generator.py+ # itself imports torch before calling select_device().+ env.setdefault("PYTORCH_ENABLE_MPS_FALLBACK", "1")+ # Keep capability identity separate from storage identity. MODEL_DIR+ # retains its node-private meaning; shared roots are passed explicitly.+ if self.model_dir is not None:+ env["MODEL_DIR"] = str(self.model_dir)+ env["MODEL_ID"] = self.MODEL_ID+ env["MODEL_NODE_ID"] = self.manifest.get(+ "node_id", self.MODEL_ID.split("/", 1)[-1]+ )+ env["SHARED_MODEL_DIRS"] = json.dumps(+ {group_id: str(path) for group_id, path in self.shared_model_dirs.items()}+ )+ # Extension venvs are based on python-embed which ships without a CA bundle.+ # Only set SSL_CERT_FILE if not already provided (preserves corporate/custom certs).+ if "SSL_CERT_FILE" not in env:+ try:+ import certifi+ env["SSL_CERT_FILE"] = certifi.where()+ except ImportError:+ pass+ return env++ def _start(self) -> None:+ """Launch the subprocess and wait for the 'ready' signal."""+ python = _venv_python(self.ext_dir)+ if not python.exists():+ raise RuntimeError(+ f"[{self.MODEL_ID}] venv not found at {python}. "+ "Run the extension's setup.py first."+ )++ for attempt in range(3):+ # Use a fresh queue per subprocess lifetime so late messages from an+ # older reader thread cannot poison startup for the new process.+ run_queue: queue.Queue = queue.Queue()+ self._queue = run_queue+ self._proc = subprocess.Popen(+ [str(python), str(_RUNNER_PATH)],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ # Without these, text=True decodes with the locale codec — cp1252+ # on Windows. tqdm draws its partial blocks with U+258D/U+258F,+ # whose UTF-8 bytes (0x8d/0x8f) are undefined there: the decode+ # raises, _stderr_loop dies, nobody drains the pipe, and the+ # child blocks forever on write once it fills. errors="replace"+ # keeps a stray non-UTF-8 byte from resurrecting that failure.+ encoding="utf-8",+ errors="replace",+ bufsize=1,+ env=self._build_env(),+ )++ # Background thread: read stdout → queue+ reader = threading.Thread(target=self._read_loop, args=(self._proc, run_queue), daemon=True)+ reader.start()++ # Background thread: forward stderr to our stderr+ stderr_fwd = threading.Thread(target=self._stderr_loop, args=(self._proc,), daemon=True)+ stderr_fwd.start()++ # Wait for ready — runner sends params_schema in this message+ msg = self._recv(timeout=None)+ if msg.get("type") == "ready":+ # Override params_schema with what the generator class actually declares+ if msg.get("params_schema"):+ self._params_schema = msg["params_schema"]++ print(f"[ExtensionProcess] {self.MODEL_ID} subprocess started (pid {self._proc.pid})")+ return++ self._proc.kill()+ self._proc.wait()+ missing_module = self._extract_missing_module(msg)+ package_name = self._resolve_auto_repair_package(missing_module) if missing_module else None+ if package_name and attempt < 2:+ self._install_missing_package(python, missing_module, package_name)+ continue++ raise RuntimeError(f"[{self.MODEL_ID}] Expected 'ready', got: {msg}")++ def _extract_missing_module(self, msg: dict) -> Optional[str]:+ """Returns missing import name from a runner error payload, if present."""+ blob = f"{msg.get('message', '')}\n{msg.get('traceback', '')}"+ match = _MISSING_MODULE_RE.search(blob)+ return match.group(1) if match else None++ def _resolve_auto_repair_package(self, module_name: str) -> Optional[str]:+ """+ Maps a missing import name to a pip package for safe auto-repair.++ Important: do not guess package names for arbitrary missing modules,+ because that can install wrong packages and break environments.+ """+ if module_name in _AUTO_REPAIR_PACKAGE_MAP:+ return _AUTO_REPAIR_PACKAGE_MAP[module_name]+ root = module_name.split(".")[0]+ return _AUTO_REPAIR_PACKAGE_MAP.get(root)++ def _install_missing_package(self, python: Path, module_name: str, package_name: str) -> None:+ """Best-effort auto-repair for a known missing import in extension venv."""+ print(+ f"[ExtensionProcess] {self.MODEL_ID} missing module '{module_name}' "+ f"-> installing '{package_name}'"+ )+ try:+ subprocess.run(+ [str(python), "-m", "pip", "install", package_name],+ check=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ encoding="utf-8",+ errors="replace",+ )+ except subprocess.CalledProcessError as exc:+ details = (exc.stderr or exc.stdout or "").strip()+ raise RuntimeError(+ f"[{self.MODEL_ID}] Auto-repair failed while installing '{package_name}' "+ f"for missing module '{module_name}'.\n{details[-2000:]}"+ ) from exc++ def _read_loop(self, proc: subprocess.Popen, msg_queue: queue.Queue) -> None:+ """Continuously reads stdout and pushes parsed JSON to the queue."""+ try:+ for line in proc.stdout:+ line = line.strip()+ if line:+ try:+ msg_queue.put(json.loads(line))+ except json.JSONDecodeError:+ print(f"[{self.MODEL_ID}] {line}", file=sys.stderr)+ finally:+ msg_queue.put(None) # sentinel: process is done++ def _stderr_loop(self, proc: subprocess.Popen) -> None:+ """Forward subprocess stderr to the main process stderr, emitting+ one line every time we see EITHER '\\n' or '\\r'. tqdm writes live+ progress updates with '\\r' only, so a newline-only iterator would+ buffer every tick until the loop exits with '\\n' — which is why+ the HUD's log pane went dark during multi-minute volume decode.++ No per-line extension-id prefix: the HUD log pane is a single+ truncated line, and eating 20 characters with "[modly-hy3d2-mac] "+ hides the tail of the tqdm bar the user actually wants to read.+ """+ stream = proc.stderr+ if stream is None:+ return+ buf = []+ while True:+ ch = stream.read(1)+ if not ch:+ if buf:+ print(''.join(buf), file=sys.stderr, flush=True)+ return+ if ch in ("\r", "\n"):+ if buf:+ print(''.join(buf), file=sys.stderr, flush=True)+ buf = []+ else:+ buf.append(ch)++ def _send(self, msg: dict) -> None:+ with self._lock:+ self._proc.stdin.write(json.dumps(msg) + "\n")+ self._proc.stdin.flush()++ def _recv(self, timeout: float | None = 120.0) -> dict:+ try:+ msg = self._queue.get(timeout=timeout)+ except queue.Empty:+ raise TimeoutError(f"[{self.MODEL_ID}] No response from subprocess after {timeout}s")+ if msg is None:+ raise RuntimeError(f"[{self.MODEL_ID}] Subprocess died unexpectedly")+ return msg++ def _ensure_started(self) -> None:+ if self._proc is None or self._proc.poll() is not None:+ self._start()++ # ------------------------------------------------------------------ #+ # BaseGenerator-compatible interface+ # ------------------------------------------------------------------ #++ def is_downloaded(self) -> bool:+ if self.download_check:+ return (self.model_dir / self.download_check).exists()+ return self.model_dir.exists() and any(self.model_dir.iterdir())++ def is_loaded(self) -> bool:+ return self._loaded and self._proc is not None and self._proc.poll() is None++ def load(self) -> None:+ self._ensure_started()+ self._send({"action": "load"})++ msg = self._recv(timeout=None) # model load can be arbitrarily slow+ if msg.get('type') in ['loaded', 'ready']:+ self._loaded = True+ elif msg.get("type") == "error":+ raise RuntimeError(msg.get("traceback") or msg.get("message"))+ else:+ raise RuntimeError(f"[{self.MODEL_ID}] Unexpected response to load: {msg}")++ def unload(self) -> None:+ if self._proc and self._proc.poll() is None:+ try:+ self._send({"action": "unload"})+ self._recv(timeout=30.0)+ except Exception:+ pass+ self._loaded = False++ def generate(+ self,+ image_bytes: bytes,+ params: dict,+ progress_cb: Optional[Callable[[int, str], None]] = None,+ cancel_event: Optional[threading.Event] = None,+ ) -> Path:+ return self._generate_request(+ {"image_b64": base64.b64encode(image_bytes).decode()},+ params, progress_cb, cancel_event,+ )++ def _receive_generation(+ self,+ req_id: str,+ progress_cb: Optional[Callable[[int, str], None]],+ cancel_event: Optional[threading.Event],+ ) -> Path:+ from services.generators.base import GenerationCancelled++ # Grace period after sending a cooperative cancel before hard-killing+ # the subprocess. Long enough to let generators that check cancel_event+ # between steps shut down cleanly, short enough that the user isn't+ # left staring at a stuck UI when the subprocess is blocked inside a+ # native call (octree decode, marching cubes, etc.) that ignores stdin.+ CANCEL_GRACE_SECONDS = 3.0++ cancel_sent_at: Optional[float] = None+ while True:+ # Check for cancellation+ if cancel_event and cancel_event.is_set():+ if cancel_sent_at is None:+ # First observation of the cancel — ask the subprocess to stop.+ try:+ self._send({"action": "cancel", "id": req_id})+ except Exception:+ pass+ import time+ cancel_sent_at = time.monotonic()+ else:+ import time+ if time.monotonic() - cancel_sent_at >= CANCEL_GRACE_SECONDS:+ # Grace period expired — the subprocess is not+ # responding (almost certainly stuck in native code).+ # Hard-kill it and drop our state so the next+ # generation forces a fresh load.+ try:+ if self._proc and self._proc.poll() is None:+ self._proc.kill()+ self._proc.wait(timeout=5.0)+ except Exception:+ pass+ self._loaded = False+ self._proc = None+ print(+ f"[ExtensionProcess] {self.MODEL_ID} subprocess killed "+ f"after {CANCEL_GRACE_SECONDS}s grace; model will reload on next run",+ file=sys.stderr,+ )+ raise GenerationCancelled()++ # Poll queue with short timeout so we can re-check cancel_event+ try:+ msg = self._queue.get(timeout=0.5)+ except queue.Empty:+ continue++ if msg is None:+ raise RuntimeError(f"[{self.MODEL_ID}] Subprocess died during generation")++ t = msg.get("type")++ if t == "progress":+ if progress_cb:+ progress_cb(msg.get("pct", 0), msg.get("step", ""))++ elif t == "done":+ return Path(msg["output_path"])++ elif t == "error":+ # A failed generation can leave the worker without a model: a+ # lazy texture-setup failure frees the shape pipeline and then+ # raises. The worker reports its post-failure state, so drop+ # our cached flag and let GeneratorRegistry.get_active() reload+ # before the next run rather than reusing a broken worker.+ if msg.get("loaded") is False:+ self._loaded = False+ raise RuntimeError(msg.get("traceback") or msg.get("message", "Unknown error"))++ elif t == "cancelled":+ raise GenerationCancelled()++ elif t == "log":+ print(f"[{self.MODEL_ID}] {msg.get('message', '')}", file=sys.stderr)++ def generate_artifact(+ self,+ input_kind: str,+ artifact_path: Path,+ params: dict,+ progress_cb: Optional[Callable[[int, str], None]] = None,+ cancel_event: Optional[threading.Event] = None,+ ) -> Path:+ """Send a typed artifact envelope to the isolated runner."""+ from services.artifact_input import TypedArtifactInput, revalidate_artifact_input+ from services.generator_registry import WORKSPACE_DIR++ validated = revalidate_artifact_input(+ WORKSPACE_DIR, TypedArtifactInput(kind=input_kind, path=artifact_path)+ )+ return self._generate_request(+ {"input": {"kind": validated.kind, "path": str(validated.path)}},+ params, progress_cb, cancel_event,+ )++ def _generate_request(+ self,+ input_payload: dict,+ params: dict,+ progress_cb: Optional[Callable[[int, str], None]],+ cancel_event: Optional[threading.Event],+ ) -> Path:+ req_id = str(uuid.uuid4())+ self._send({+ "action": "generate", "id": req_id, "model_id": self.MODEL_ID,+ **input_payload, "params": params,+ "outputs_dir": str(self.outputs_dir) if self.outputs_dir else None,+ })+ return self._receive_generation(req_id, progress_cb, cancel_event)++ def params_schema(self) -> list:+ return self._params_schema++ def stop(self) -> None:+ """Hard-stop the subprocess.++ Used by Free Memory / unload_all. Cooperative shutdown was the wrong+ semantics here: torch.mps.empty_cache() does not reliably release+ wired Metal pages, so only process exit actually returns the memory+ to the OS. We SIGKILL, reap the zombie, and drop our refs so the+ next load() starts a fresh subprocess.+ """+ proc = self._proc+ self._loaded = False+ if proc and proc.poll() is None:+ try:+ proc.kill()+ proc.wait(timeout=5)+ except Exception as exc:+ # Keep the process reference so callers can verify that the+ # worker may still be alive and refuse to mutate its venv.+ self._proc = proc+ raise RuntimeError(+ f"[{self.MODEL_ID}] Could not stop extension subprocess"+ ) from exc+ if proc.poll() is None:+ self._proc = proc+ raise RuntimeError(+ f"[{self.MODEL_ID}] Extension subprocess is still running"+ )+ self._proc = None+ self._drain_queue()++ def _drain_queue(self) -> None:+ while not self._queue.empty():+ try:+ self._queue.get_nowait()+ except queue.Empty:+ breakdiff --git a/apps/forge-desktop/api/services/generator_registry.py b/apps/forge-desktop/api/services/generator_registry.pynew file mode 100644index 000000000..2792030e9--- /dev/null+++ b/apps/forge-desktop/api/services/generator_registry.py@@ -0,0 +1,1015 @@+"""+GeneratorRegistry — manages the lifecycle of all model adapters.+Dynamically loads extensions from the extensions/ folder.++To add a new model: create a folder in extensions/ with+ - manifest.json (metadata + hf_repo + pip_requirements...)+ - generator.py (class extending BaseGenerator)+No other file needs to be modified.+"""+import importlib+import importlib.util+import hmac+import json+import os+import re+import secrets+import stat+import sys+import threading+from contextlib import contextmanager+from functools import wraps+from pathlib import Path+from types import ModuleType+from typing import Dict, Iterator, List, Optional, Set, Tuple++from services.generators.base import BaseGenerator+from services.extension_process import ExtensionProcess, _venv_python+from services.model_sources import (+ missing_weight_variant,+ model_sources_are_downloaded,+ normalize_model_sources,+ normalize_weight_group_references,+ normalize_weight_groups,+ normalize_weight_variants,+ validate_model_node_ids,+ resolve_weight_group_root,+ safe_source_id,+ weight_group_sources_are_downloaded,+)++# ------------------------------------------------------------------ #+# Global paths+# ------------------------------------------------------------------ #++_models_dir_raw = os.environ.get("MODELS_DIR") or str(Path.home() / ".modly" / "models")+_workspace_dir_raw = os.environ.get("WORKSPACE_DIR") or str(Path.home() / ".modly" / "workspace")+MODELS_DIR = Path(_models_dir_raw)+WORKSPACE_DIR = Path(_workspace_dir_raw)++MODELS_DIR.mkdir(parents=True, exist_ok=True)+WORKSPACE_DIR.mkdir(parents=True, exist_ok=True)++# extensions/ folder — in userData (passed by Electron via EXTENSIONS_DIR)+_extensions_dir_raw = os.environ.get("EXTENSIONS_DIR", "")+EXTENSIONS_DIR = Path(_extensions_dir_raw) if _extensions_dir_raw else None+_REGISTRATION_PENDING_PREFIX = ".modly-registration-pending-"+_EXTENSION_ID = re.compile(r"^[a-z0-9][a-z0-9._-]*$")+_REGISTRATION_PENDING_NAME = re.compile(+ rf"^{re.escape(_REGISTRATION_PENDING_PREFIX)}"+ r"(?P<extension_id>[a-z0-9][a-z0-9._-]*)-(?P<suffix>\d+)$"+)+_REGISTRATION_CAPABILITY_LOCK = threading.Lock()++print(f"[Registry] MODELS_DIR = {MODELS_DIR}")+print(f"[Registry] WORKSPACE_DIR = {WORKSPACE_DIR}")+print(f"[Registry] EXTENSIONS_DIR = {EXTENSIONS_DIR or '(not set)'}")+++def is_within_workspace(resolved_path: Path) -> bool:+ """True when an already-resolved path is the current workspace or inside it.++ Compares ancestry, not string prefixes: ``startswith`` would also accept a+ sibling folder such as ``<workspace>-other``. Reads WORKSPACE_DIR at call+ time, since moving the workspace rebinds it.+ """+ workspace = WORKSPACE_DIR.resolve()+ return resolved_path == workspace or workspace in resolved_path.parents+++# ------------------------------------------------------------------ #+# Extension loader+# ------------------------------------------------------------------ #++def _path_belongs_to(path: object, root: Path) -> bool:+ if not isinstance(path, (str, os.PathLike)):+ return False+ try:+ Path(path).resolve().relative_to(root)+ return True+ except (OSError, ValueError):+ return False+++class _LegacyImportContext:+ def __init__(self, root: Path) -> None:+ self.root = root.resolve()+ self.modules: Dict[str, ModuleType] = {}+ self.local_names: Set[str] = set()+ for child in self.root.iterdir():+ if child.is_file() and child.suffix == ".py" and child.stem != "__init__":+ self.local_names.add(child.stem)+ elif child.is_dir() and (child / "__init__.py").is_file():+ self.local_names.add(child.name)+++class _LegacyImportManager:+ """Isolates plain sibling imports used by legacy direct extensions."""++ def __init__(self) -> None:+ self._contexts: Dict[Path, _LegacyImportContext] = {}+ self._lock = threading.RLock()++ def register(self, root: Path) -> _LegacyImportContext:+ resolved = root.resolve()+ context = self._contexts.get(resolved)+ if context is None:+ context = _LegacyImportContext(resolved)+ self._contexts[resolved] = context+ return context++ def _owner(self, module: ModuleType) -> Optional[_LegacyImportContext]:+ module_file = getattr(module, "__file__", None)+ for context in self._contexts.values():+ if _path_belongs_to(module_file, context.root):+ return context+ return None++ def _capture_and_evict_owned_modules(self) -> None:+ for name, module in list(sys.modules.items()):+ if not isinstance(module, ModuleType):+ continue+ owner = self._owner(module)+ if owner is None:+ continue+ owner.modules[name] = module+ sys.modules.pop(name, None)++ @staticmethod+ def _matches_local_name(module_name: str, local_names: Set[str]) -> bool:+ return any(+ module_name == local_name or module_name.startswith(f"{local_name}.")+ for local_name in local_names+ )++ @contextmanager+ def activate(self, context: _LegacyImportContext) -> Iterator[None]:+ # sys.path and sys.modules are process-global. Serializing direct legacy+ # calls prevents concurrent generators from observing each other's+ # same-named sibling modules.+ with self._lock:+ original_path = list(sys.path)+ shadowed: Dict[str, ModuleType] = {}+ self._capture_and_evict_owned_modules()++ for name, module in list(sys.modules.items()):+ if self._matches_local_name(name, context.local_names) and isinstance(module, ModuleType):+ shadowed[name] = module+ sys.modules.pop(name, None)++ sys.modules.update(context.modules)+ managed_roots = {str(item.root) for item in self._contexts.values()}+ sys.path[:] = [str(context.root)] + [+ entry for entry in original_path if entry not in managed_roots+ ]+ importlib.invalidate_caches()++ try:+ yield+ finally:+ self._capture_and_evict_owned_modules()+ for name in list(sys.modules):+ if self._matches_local_name(name, context.local_names):+ sys.modules.pop(name, None)+ sys.modules.update(shadowed)+ sys.path[:] = original_path+ importlib.invalidate_caches()++ def clear(self) -> None:+ with self._lock:+ self._capture_and_evict_owned_modules()+ for context in self._contexts.values():+ for module in context.modules.values():+ cached = getattr(module, "__cached__", None)+ if _path_belongs_to(cached, context.root):+ try:+ Path(cached).unlink(missing_ok=True)+ except OSError:+ pass+ context.modules.clear()+ self._contexts.clear()+ importlib.invalidate_caches()+++class _LegacyGeneratorProxy:+ def __init__(+ self,+ target: BaseGenerator,+ manager: _LegacyImportManager,+ context: _LegacyImportContext,+ ) -> None:+ object.__setattr__(self, "_target", target)+ object.__setattr__(self, "_manager", manager)+ object.__setattr__(self, "_context", context)++ def __getattr__(self, name: str):+ manager = object.__getattribute__(self, "_manager")+ context = object.__getattribute__(self, "_context")+ target = object.__getattribute__(self, "_target")+ with manager.activate(context):+ value = getattr(target, name)+ if not callable(value):+ return value++ @wraps(value)+ def call_in_context(*args, **kwargs):+ with manager.activate(context):+ return value(*args, **kwargs)++ return call_in_context++ def __setattr__(self, name: str, value: object) -> None:+ manager = object.__getattribute__(self, "_manager")+ context = object.__getattribute__(self, "_context")+ target = object.__getattribute__(self, "_target")+ with manager.activate(context):+ setattr(target, name, value)+++def _manifest_model_ids(manifest: dict, fallback_id: str) -> List[str]:+ """Returns the registry keys a readable model manifest is expected to add."""+ ext_id = manifest.get("id")+ if not isinstance(ext_id, str) or not ext_id:+ return [fallback_id]++ raw_nodes = manifest.get("nodes", [])+ if not isinstance(raw_nodes, list):+ raw_nodes = []+ nodes = [+ node for node in raw_nodes+ if isinstance(node, dict) and isinstance(node.get("id"), str) and node["id"]+ ]+ return [f"{ext_id}/{node['id']}" for node in nodes] or [ext_id]+++def _record_discovery_error(+ errors: Dict[str, str],+ message: str,+ *,+ manifest: Optional[dict] = None,+ fallback_id: str,+) -> None:+ keys = _manifest_model_ids(manifest, fallback_id) if manifest is not None else [fallback_id]+ for key in keys:+ errors[key] = message+++def _registration_pending(extension_id: str) -> bool:+ if EXTENSIONS_DIR is None:+ return False+ prefix = f"{_REGISTRATION_PENDING_PREFIX}{extension_id}-"+ try:+ return any(+ child.name.startswith(prefix)+ and child.name[len(prefix):].isdigit()+ for child in EXTENSIONS_DIR.iterdir()+ )+ except OSError:+ return False+++RegistrationValidationAuthorization = Tuple[str, Path, Path]+++def _consume_registration_validation_capability(+ capability: object,+) -> Optional[RegistrationValidationAuthorization]:+ """Validates and atomically consumes one exact root-sidecar capability."""+ if EXTENSIONS_DIR is None or not isinstance(capability, dict):+ return None++ extension_id = capability.get("extensionId")+ destination_name = capability.get("destinationName")+ state_name = capability.get("stateName")+ token = capability.get("token")+ if not all(isinstance(value, str) and value for value in (+ extension_id,+ destination_name,+ state_name,+ token,+ )):+ return None+ if len(token) < 32:+ return None+ if (+ _EXTENSION_ID.fullmatch(extension_id) is None+ or destination_name != extension_id+ ):+ return None++ name_match = _REGISTRATION_PENDING_NAME.fullmatch(state_name)+ if name_match is None or name_match.group("extension_id") != extension_id:+ return None++ with _REGISTRATION_CAPABILITY_LOCK:+ try:+ root = EXTENSIONS_DIR.resolve()+ state_path = EXTENSIONS_DIR / state_name+ if state_path.parent.resolve() != root:+ return None+ destination_path = Path(os.path.abspath(root / destination_name))+ if destination_path.parent != root:+ return None+ matching_state_names = sorted(+ child.name+ for child in root.iterdir()+ if (+ (match := _REGISTRATION_PENDING_NAME.fullmatch(child.name))+ is not None+ and match.group("extension_id") == extension_id+ )+ )+ if matching_state_names != [state_name]:+ return None+ state_stat = state_path.lstat()+ if (+ stat.S_ISLNK(state_stat.st_mode)+ or not stat.S_ISREG(state_stat.st_mode)+ or state_stat.st_nlink != 1+ ):+ return None+ if (+ os.name != "nt"+ and (+ stat.S_IMODE(state_stat.st_mode) & 0o077+ or (+ hasattr(os, "getuid")+ and state_stat.st_uid != os.getuid()+ )+ )+ ):+ return None++ state = json.loads(state_path.read_text(encoding="utf-8"))+ if (+ not isinstance(state, dict)+ or state.get("version") != 1+ or state.get("extensionId") != extension_id+ or state.get("destinationName") != destination_name+ or state.get("consumed") is not False+ or not isinstance(state.get("token"), str)+ or not hmac.compare_digest(state["token"], token)+ ):+ return None++ # Replace the exact sidecar atomically while retaining its pending+ # filename. Normal reloads therefore keep quarantining the+ # extension, while this capability cannot be replayed.+ consumed_state = {+ "version": 1,+ "extensionId": extension_id,+ "destinationName": destination_name,+ "consumed": True,+ }+ temporary_path = root / (+ f".modly-registration-capability-{secrets.token_hex(16)}"+ )+ try:+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL+ if hasattr(os, "O_NOFOLLOW"):+ flags |= os.O_NOFOLLOW+ descriptor = os.open(temporary_path, flags, 0o600)+ try:+ if os.name != "nt":+ os.fchmod(descriptor, 0o600)+ with os.fdopen(descriptor, "w", encoding="utf-8") as stream:+ descriptor = -1+ json.dump(consumed_state, stream)+ stream.flush()+ os.fsync(stream.fileno())+ finally:+ if descriptor >= 0:+ os.close(descriptor)+ os.replace(temporary_path, state_path)+ finally:+ try:+ temporary_path.unlink()+ except FileNotFoundError:+ pass+ except (OSError, TypeError, ValueError, json.JSONDecodeError):+ return None++ return extension_id, state_path, destination_path+++def _discover_extensions(+ legacy_imports: _LegacyImportManager,+ registration_authorization: Optional[RegistrationValidationAuthorization] = None,+) -> Tuple[+ Dict[str, Tuple[type, dict, Path, Optional[_LegacyImportContext]]],+ Dict[str, str],+]:+ """+ Scans EXTENSIONS_DIR to find valid extensions.+ Each extension must have manifest.json + generator.py.+ Returns ({full_id: (GeneratorClass, node_manifest, ext_dir)}, errors)+ where full_id is "ext_id/node_id".+ """+ result: Dict[str, Tuple[type, dict, Path, Optional[_LegacyImportContext]]] = {}+ errors: Dict[str, str] = {}++ if EXTENSIONS_DIR is None or not EXTENSIONS_DIR.exists():+ print(f"[Registry] WARNING: EXTENSIONS_DIR not set or not found: {EXTENSIONS_DIR}")+ return result, errors++ for ext_dir in sorted(EXTENSIONS_DIR.iterdir()):+ if not ext_dir.is_dir():+ continue+ # Dot-dirs are install machinery (staging/backup), never extensions+ if ext_dir.name.startswith("."):+ continue+ manifest_path = ext_dir / "manifest.json"+ generator_path = ext_dir / "generator.py"++ if not manifest_path.exists():+ message = f"Extension '{ext_dir.name}' is missing manifest.json."+ print(f"[Registry] ERROR: {message}")+ _record_discovery_error(errors, message, fallback_id=ext_dir.name)+ continue++ try:+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))+ except Exception as exc:+ message = f"Extension '{ext_dir.name}' has an invalid manifest.json: {exc}"+ print(f"[Registry] ERROR: {message}")+ _record_discovery_error(errors, message, fallback_id=ext_dir.name)+ continue+ if not isinstance(manifest, dict):+ message = f"Extension '{ext_dir.name}' has an invalid manifest.json: expected an object."+ print(f"[Registry] ERROR: {message}")+ _record_discovery_error(errors, message, fallback_id=ext_dir.name)+ continue++ try:+ # Process extensions run via Electron's process runner, not this+ # registry — skip them even when their entry file is generator.py.+ if manifest.get("type", "model") != "model":+ print(f"[Registry] Skipping '{ext_dir.name}': type "+ f"'{manifest.get('type')}' is not handled by this registry")+ continue++ ext_id = manifest["id"]+ class_name = manifest["generator_class"]++ if "model_sources" in manifest:+ raise ValueError("model_sources must be declared on a model node")++ weight_groups = normalize_weight_groups(manifest)++ if ext_id != ext_dir.name:+ message = (+ f"Extension folder '{ext_dir.name}' declares mismatched "+ f"manifest id '{ext_id}'. Folder and manifest IDs must match."+ )+ print(f"[Registry] ERROR: {message}")+ _record_discovery_error(+ errors,+ message,+ fallback_id=ext_dir.name,+ )+ continue++ raw_nodes = manifest.get("nodes", [])+ if not isinstance(raw_nodes, list):+ raw_nodes = []+ nodes = [+ node for node in raw_nodes+ if isinstance(node, dict) and node.get("id")+ ]+ group_by_id = {group["id"]: group for group in weight_groups or []}+ uses_shared_weights = weight_groups is not None or any(+ "weight_groups" in node for node in nodes+ )+ if uses_shared_weights or any("model_sources" in node for node in nodes):+ validate_model_node_ids(raw_nodes)+ if uses_shared_weights:+ for node in nodes:+ raw_node_id = node.get("id")+ if (+ weight_groups is not None+ and isinstance(raw_node_id, str)+ and raw_node_id.casefold() == "_shared"+ ):+ raise ValueError('model node id "_shared" is reserved')+ node_id = safe_source_id(raw_node_id, "model node id")+ normalize_weight_group_references(+ node,+ weight_groups,+ field_name=f"nodes[{node_id}].weight_groups",+ )+ if "weight_groups" in node and "weight_variants" in node:+ raise ValueError(+ f'model node "{node_id}": weight_variants cannot be combined '+ "with weight_groups"+ )+ if "weight_groups" in node and "hf_repo" in node:+ raise ValueError(+ f'model node "{node_id}" must use model_sources for private '+ "weights when weight_groups are declared"+ )+ for node in nodes:+ declared_inputs = node.get("inputs")+ uses_scene_input = (+ node.get("input", "image") == "scene"+ or (isinstance(declared_inputs, list) and "scene" in declared_inputs)+ )+ if uses_scene_input and (+ "inputs" in node or node.get("input", "image") != "scene"+ ):+ raise ValueError(+ f'model node "{node.get("id", "unknown")}" must declare scene '+ 'as its single input field'+ )++ # Markers left while setup or runtime registration is unfinished:+ # the folder is not ready to be loaded. The readable manifest lets+ # the UI attach this error to each expected model node even when+ # startup could not immediately restore a locked backup.+ install_interrupted = (+ (ext_dir / ".modly-incomplete").exists()+ or (ext_dir / ".modly-registration-pending").exists()+ or (+ _registration_pending(ext_id)+ and not (+ registration_authorization is not None+ and registration_authorization[0] == ext_id+ and registration_authorization[1].exists()+ # Normalize like the capability's destination (resolved+ # root + name): EXTENSIONS_DIR may be a Windows 8.3 short+ # path. The extension folder itself is not resolved.+ and registration_authorization[2]+ == Path(os.path.abspath(ext_dir.parent.resolve() / ext_dir.name))+ )+ )+ )+ if install_interrupted:+ message = (+ f"Extension '{ext_id}' has an incomplete installation "+ "or interrupted runtime registration. "+ "Restart Modly to recover it, or click 'Repair' on the Models page."+ )+ print(f"[Registry] ERROR: {message}")+ _record_discovery_error(+ errors,+ message,+ manifest=manifest,+ fallback_id=ext_dir.name,+ )+ continue++ if not generator_path.exists():+ message = f"Extension '{ext_id}' is missing generator.py."+ print(f"[Registry] ERROR: {message}")+ _record_discovery_error(+ errors,+ message,+ manifest=manifest,+ fallback_id=ext_dir.name,+ )+ continue++ # --- Subprocess mode (new): venv present → use ExtensionProcess ---+ # Also force subprocess mode for extensions that ship a build_vendor.py+ # but whose vendor/ directory hasn't been built yet: this surfaces a+ # loadError in the UI (Repair button) so the user can run setup.py.+ has_venv = _venv_python(ext_dir).is_file()+ has_setup = (ext_dir / "setup.py").is_file()+ has_build_vendor = (ext_dir / "build_vendor.py").exists()+ vendor_built = (ext_dir / "vendor").exists()+ needs_setup = (has_setup and not has_venv) or (has_build_vendor and not vendor_built)+ subprocess_mode = has_venv or needs_setup++ cls_or_None = None+ legacy_context = None+ if not subprocess_mode:+ # --- Direct mode (legacy): no venv → load generator.py directly ---+ # Plain sibling imports are exposed only inside the serialized+ # import context. Never leave extension roots on host sys.path.+ legacy_context = legacy_imports.register(ext_dir)+ with legacy_imports.activate(legacy_context):+ module_name = f"extensions.{ext_id}.generator"+ spec = importlib.util.spec_from_file_location(module_name, generator_path)+ if spec is None or spec.loader is None:+ raise ImportError(f"Could not create an import spec for {generator_path}")+ module = importlib.util.module_from_spec(spec)+ sys.modules[module_name] = module+ spec.loader.exec_module(module)+ cls_or_None = getattr(module, class_name)++ if nodes:+ for node in nodes:+ model_sources = normalize_model_sources(node)+ group_ids = normalize_weight_group_references(+ node,+ weight_groups,+ field_name=f"nodes[{node['id']}].weight_groups",+ ) or []+ weight_variants = normalize_weight_variants(+ node, node.get("params_schema", manifest.get("params_schema", []))+ )+ node_manifest = {+ **manifest,+ "id": f"{ext_id}/{node['id']}",+ "ext_id": ext_id,+ "node_id": node["id"],+ "name": node.get("name", node["id"]),+ "hf_repo": node.get("hf_repo", ""),+ "download_check": node.get("download_check", ""),+ "hf_skip_prefixes": node.get("hf_skip_prefixes", []),+ "hf_include_prefixes": node.get("hf_include_prefixes", []),+ "params_schema": node.get("params_schema", manifest.get("params_schema", [])),+ "input": node.get("input", "image"),+ "inputs": node.get("inputs"),+ "output": node.get("output", "mesh"),+ "weight_groups": [group_by_id[group_id] for group_id in group_ids],+ }+ if model_sources is not None:+ node_manifest["model_sources"] = model_sources+ if weight_variants is not None:+ node_manifest["weight_variants"] = weight_variants+ full_id = f"{ext_id}/{node['id']}"+ result[full_id] = (cls_or_None, node_manifest, ext_dir, legacy_context)+ if subprocess_mode:+ if has_venv:+ print(f"[Registry] Loaded subprocess node: {full_id}")+ else:+ print(f"[Registry] Node '{full_id}' needs setup (venv missing)")+ else:+ print(f"[Registry] Loaded node: {full_id} ({class_name})")+ else:+ # No nodes defined — register by ext_id as fallback+ result[ext_id] = (cls_or_None, manifest, ext_dir, legacy_context)+ if subprocess_mode:+ if has_venv:+ print(f"[Registry] Loaded subprocess extension: {ext_id}")+ else:+ print(f"[Registry] Extension '{ext_id}' needs setup (venv missing)")+ else:+ print(f"[Registry] Loaded extension: {ext_id} ({class_name})")++ except Exception as exc:+ message = f"Failed to discover extension '{ext_dir.name}': {exc}"+ print(f"[Registry] ERROR: {message}")+ _record_discovery_error(+ errors,+ message,+ manifest=manifest,+ fallback_id=ext_dir.name,+ )++ return result, errors+++# ------------------------------------------------------------------ #+# GeneratorRegistry+# ------------------------------------------------------------------ #++class GeneratorRegistry:+ def __init__(self) -> None:+ self._generators: Dict[str, BaseGenerator] = {}+ self._manifests: Dict[str, dict] = {}+ self._errors: Dict[str, str] = {}+ # Serializes everything that changes which generators exist or are+ # loaded (switch/load, unload, reload, path changes). Read-only status+ # calls deliberately skip it: a load can hold it for minutes (first-run+ # downloads happen inside load()), and status must stay responsive.+ self._lifecycle_lock = threading.RLock()+ self._legacy_imports = _LegacyImportManager()+ self._active_id: str = os.environ.get("SELECTED_MODEL_ID", "sf3d")++ def initialize(+ self,+ registration_authorization: Optional[RegistrationValidationAuthorization] = None,+ ) -> None:+ """Discovers and instantiates all extensions. Call at startup."""+ extensions, discovery_errors = _discover_extensions(+ self._legacy_imports,+ registration_authorization,+ )+ self._errors.update(discovery_errors)++ for model_id, entry in extensions.items():+ cls, manifest, ext_dir, legacy_context = entry+ try:+ if cls is None:+ # Subprocess mode: venv must exist+ if not _venv_python(ext_dir).is_file():+ raise RuntimeError(+ "venv not found — extension needs setup. "+ "Click 'Repair' on the Models page to run setup.py."+ )+ # Subprocess mode: wrap in ExtensionProcess+ gen = ExtensionProcess(ext_dir, manifest)+ # Pin the subprocess envelope to the exact registry key;+ # multi-node workers must never fall back to an extension ID.+ gen.MODEL_ID = model_id+ gen.model_dir = MODELS_DIR / model_id+ gen.outputs_dir = WORKSPACE_DIR+ else:+ # Legacy direct mode+ if legacy_context is None:+ raise RuntimeError("legacy import context is missing")+ with self._legacy_imports.activate(legacy_context):+ direct_gen = cls(MODELS_DIR / model_id, WORKSPACE_DIR)+ gen = _LegacyGeneratorProxy(+ direct_gen,+ self._legacy_imports,+ legacy_context,+ )+ gen.hf_repo = manifest.get("hf_repo", "")+ gen.hf_skip_prefixes = manifest.get("hf_skip_prefixes", [])+ gen.download_check = manifest.get("download_check", "")+ gen._params_schema = manifest.get("params_schema", [])++ gen.MODEL_ID = model_id+ gen.MODEL_NODE_ID = manifest.get("node_id", "")+ gen.shared_model_dirs = {+ group["id"]: resolve_weight_group_root(+ MODELS_DIR, manifest.get("ext_id", model_id.split("/", 1)[0]), group["id"]+ )+ for group in manifest.get("weight_groups", [])+ }++ self._generators[model_id] = gen+ self._manifests[model_id] = manifest+ self._errors.pop(model_id, None)+ except Exception as exc:+ msg = f"Failed to instantiate generator '{model_id}': {exc}"+ print(f"[Registry] ERROR: {msg}")+ self._errors[model_id] = msg++ if not self._generators:+ print("[Registry] WARNING: No extensions found.")+ return++ if self._active_id not in self._generators:+ fallback = next(iter(self._generators))+ print(+ f"[Registry] WARNING: SELECTED_MODEL_ID='{self._active_id}' is unknown. "+ f"Falling back to '{fallback}'."+ )+ self._active_id = fallback++ print(f"[Registry] Active model : {self._active_id}")+ print(f"[Registry] All models : {list(self._generators.keys())}")++ def reload(self, validation_capability: object = None) -> None:+ """+ Re-scans extensions and updates the registry without restarting FastAPI.+ Unloads all current generators before reloading.+ """+ registration_authorization = _consume_registration_validation_capability(+ validation_capability,+ )+ with self._lifecycle_lock:+ print("[Registry] Reloading extensions...")+ for gen in self._generators.values():+ if isinstance(gen, ExtensionProcess):+ gen.stop()+ if gen._proc is not None:+ raise RuntimeError(+ "Extension subprocess remained attached after stop()"+ )+ else:+ try:+ gen.unload()+ except Exception:+ pass+ self._generators.clear()+ self._manifests.clear()+ self._errors.clear()+ self._remove_legacy_paths()+ self.initialize(registration_authorization)+ print("[Registry] Reload complete.")++ def load_errors(self) -> Dict[str, str]:+ """Returns extension loading errors."""+ return dict(self._errors)++ def _remove_legacy_paths(self) -> None:+ """Clears direct-extension import state owned by this registry."""+ self._legacy_imports.clear()++ # ------------------------------------------------------------------ #+ # Generator access+ # ------------------------------------------------------------------ #++ @staticmethod+ def _assert_not_quarantined(model_id: str) -> None:+ extension_id = model_id.split("/", 1)[0]+ if _registration_pending(extension_id):+ raise ValueError(+ f"Model ID '{model_id}' belongs to an extension with pending "+ "runtime registration. Repair or reload the extension first."+ )++ def get_active(self) -> BaseGenerator:+ """Returns the active generator. Downloads and loads if necessary."""+ with self._lifecycle_lock:+ return self.get_ready_generator(self._active_id)++ def get_ready_generator(self, model_id: str) -> BaseGenerator:+ """Load and return exactly ``model_id`` without consulting active state."""+ with self._lifecycle_lock:+ gen = self.get_generator(model_id)+ downloaded = self._is_downloaded(model_id, gen)+ manifest = self._manifests[model_id]+ if (+ "model_sources" in manifest or manifest.get("weight_groups")+ ) and not downloaded:+ raise RuntimeError(+ "Model sources are incomplete. Download this node's shared and private weights "+ "from the Modly Models page before generation."+ )+ if not gen.is_loaded():+ if not downloaded:+ if isinstance(gen, ExtensionProcess):+ # Let the subprocess handle its own download logic during+ # load() — some extensions (e.g. mv-adapter) need custom+ # multi-repo downloads that the standard HF endpoint can't do.+ pass+ else:+ gen._auto_download()+ gen.load()+ return gen++ def activate_ready_generator(self, model_id: str) -> BaseGenerator:+ """Atomically make ``model_id`` active and return it ready for inference."""+ with self._lifecycle_lock:+ self.switch_model(model_id)+ return self.get_ready_generator(model_id)++ def model_status(self, model_id: str) -> dict:+ gen = self.get_generator(model_id)+ manifest = self._manifests[model_id]+ return {+ "id": model_id,+ "name": manifest.get("name", gen.DISPLAY_NAME),+ "downloaded": self._is_downloaded(model_id, gen),+ "loaded": gen.is_loaded(),+ }++ def assert_weight_variant_installed(+ self, params: dict, model_id: Optional[str] = None+ ) -> None:+ """Refuse generation when the weight variant selected by params is not installed.++ ``model_id`` is the job's model. Pinned jobs only switch to it once they+ run, so the active model is not a reliable stand-in before that.+ """+ target_id = model_id or self._active_id+ manifest = self._manifests.get(target_id, {})+ option = missing_weight_variant(+ MODELS_DIR, target_id, manifest.get("weight_variants"), params+ )+ if option is not None:+ raise RuntimeError(+ f'{option["label"]} weights for {target_id} are not installed. '+ "Install them from the Extensions page, or select an installed variant."+ )++ def get_generator(self, model_id: str) -> BaseGenerator:+ self._assert_not_quarantined(model_id)+ if model_id not in self._generators:+ raise ValueError(+ f"Unknown model ID: '{model_id}'. "+ f"Available: {list(self._generators.keys())}"+ )+ return self._generators[model_id]++ def get_manifest(self, model_id: str) -> dict:+ """Returns the manifest of an extension."""+ if model_id not in self._manifests:+ raise KeyError(f"No manifest for model ID: '{model_id}'")+ return self._manifests[model_id]++ def switch_model(self, model_id: str) -> None:+ """Switches the active model. Unloads the previous one if different."""+ with self._lifecycle_lock:+ self._assert_not_quarantined(model_id)+ if model_id not in self._generators:+ raise ValueError(+ f"Unknown model ID: '{model_id}'. "+ f"Available: {list(self._generators.keys())}"+ )+ # 3D generation owns the GPU: evict the chat LLMs before anything is+ # about to allocate on it. The trigger is "the target model is not+ # resident", not "the target model changed" — the common case is the+ # default generator, which is already `_active_id` at boot and still+ # has to load its weights. Gating on the id alone let a full LLM pool+ # (2 slots, ~11.6 GB of 12) sit through an entire generation.+ target = self._generators[model_id]+ if model_id != self._active_id or not target.is_loaded():+ from services.llm_server import llama_pool+ llama_pool.unload_all()++ if model_id != self._active_id:+ if self._active_id in self._generators:+ self._generators[self._active_id].unload()+ self._active_id = model_id++ # ------------------------------------------------------------------ #+ # Status+ # ------------------------------------------------------------------ #++ def _is_downloaded(self, model_id: str, gen: BaseGenerator) -> bool:+ manifest = self._manifests[model_id]+ private_ready = True+ if "model_sources" in manifest:+ private_ready = model_sources_are_downloaded(+ MODELS_DIR, model_id, manifest["model_sources"]+ )+ shared_ready = all(+ weight_group_sources_are_downloaded(+ MODELS_DIR,+ manifest.get("ext_id", model_id.split("/", 1)[0]),+ group,+ )+ for group in manifest.get("weight_groups", [])+ )+ if "model_sources" in manifest or manifest.get("weight_groups"):+ return private_ready and shared_ready+ return gen.is_downloaded()++ def active_status(self) -> dict:+ return self.model_status(self._active_id)++ def all_status(self) -> list:+ result = []+ active_id = self._active_id+ # Snapshot: a concurrent reload() may clear the dicts mid-iteration.+ for model_id, gen in list(self._generators.items()):+ manifest = self._manifests.get(model_id)+ if manifest is None:+ continue+ result.append({+ "id": model_id,+ "name": manifest.get("name", gen.DISPLAY_NAME),+ "description": manifest.get("description", ""),+ "version": manifest.get("version", ""),+ "vram_gb": manifest.get("vram_gb", gen.VRAM_GB),+ "hf_repo": manifest.get("hf_repo", ""),+ "tags": manifest.get("tags", []),+ "downloaded": self._is_downloaded(model_id, gen),+ "loaded": gen.is_loaded(),+ "active": model_id == active_id,+ })+ return result++ def params_schema(self, model_id: Optional[str] = None) -> list:+ target_id = model_id or self._active_id+ gen = self._generators.get(target_id)+ if gen is None:+ raise KeyError(target_id)+ return gen.params_schema()++ # ------------------------------------------------------------------ #+ # Paths update & shutdown+ # ------------------------------------------------------------------ #++ def update_paths(self, models_dir: Optional[Path], workspace_dir: Optional[Path]) -> None:+ global MODELS_DIR, WORKSPACE_DIR+ import services.generator_registry as _self_module++ with self._lifecycle_lock:+ if models_dir is not None:+ self.unload_all()+ models_dir.mkdir(parents=True, exist_ok=True)+ _self_module.MODELS_DIR = models_dir+ for model_id, gen in self._generators.items():+ gen.model_dir = models_dir / model_id+ manifest = self._manifests[model_id]+ gen.shared_model_dirs = {+ group["id"]: resolve_weight_group_root(+ models_dir,+ manifest.get("ext_id", model_id.split("/", 1)[0]),+ group["id"],+ )+ for group in manifest.get("weight_groups", [])+ }++ if workspace_dir is not None:+ workspace_dir.mkdir(parents=True, exist_ok=True)+ _self_module.WORKSPACE_DIR = workspace_dir+ for gen in self._generators.values():+ gen.outputs_dir = workspace_dir++ def unload_all(self) -> None:+ with self._lifecycle_lock:+ still_loaded = []+ for model_id, gen in self._generators.items():+ if isinstance(gen, ExtensionProcess):+ gen.stop()+ else:+ gen.unload()+ if gen.is_loaded():+ still_loaded.append(model_id)+ if still_loaded:+ raise RuntimeError(+ "Models are still loaded; weights were preserved: "+ + ", ".join(still_loaded)+ )+++# Singleton+generator_registry = GeneratorRegistry()diff --git a/apps/forge-desktop/api/services/generators/__init__.py b/apps/forge-desktop/api/services/generators/__init__.pynew file mode 100644index 000000000..ba455197a--- /dev/null+++ b/apps/forge-desktop/api/services/generators/__init__.py@@ -0,0 +1,5 @@+# Adapters are loaded dynamically from extensions/ by generator_registry.py.+# This file only exposes BaseGenerator for external imports.+from .base import BaseGenerator, smooth_progress++__all__ = ["BaseGenerator", "smooth_progress"]diff --git a/apps/forge-desktop/api/services/generators/base.py b/apps/forge-desktop/api/services/generators/base.pynew file mode 100644index 000000000..63ded9ada--- /dev/null+++ b/apps/forge-desktop/api/services/generators/base.py@@ -0,0 +1,244 @@+"""+BaseGenerator — contract that each model adapter must implement.+"""+from abc import ABC, abstractmethod+import threading+from pathlib import Path+from typing import Callable, Optional+++class GenerationCancelled(Exception):+ """Raised by generators when a cancel_event is set mid-generation."""+++def select_device() -> str:+ """+ Picks the best torch device available on this machine: CUDA (NVIDIA) ->+ MPS (Apple Silicon) -> CPU. Extensions should call this instead of+ hardcoding `.cuda()` / `torch.cuda.is_available()` so device logic lives+ in one place and Windows/CUDA behavior is unaffected.++ PyTorch only falls back to CPU for MPS ops with no Metal kernel (e.g. 3D+ pooling) — instead of raising NotImplementedError — if+ PYTORCH_ENABLE_MPS_FALLBACK=1 is set *before the process's first `import+ torch`*. That's set for every extension subprocess in+ ExtensionProcess._build_env(); the setdefault() below is just a+ best-effort backstop for callers that reach select_device() before+ importing torch themselves.+ """+ import os+ import torch++ if torch.cuda.is_available():+ return "cuda"+ if torch.backends.mps.is_available():+ os.environ.setdefault("PYTORCH_ENABLE_MPS_FALLBACK", "1")+ return "mps"+ return "cpu"+++def select_dtype(device: str):+ """+ Picks a safe default dtype for `device`. MPS has incomplete fp16 kernel+ coverage (attention, layer norm, some interpolation ops), so extensions+ get fp32 there and on CPU; CUDA keeps fp16 for speed/memory.+ """+ import torch++ return torch.float16 if device == "cuda" else torch.float32+++def smooth_progress(+ progress_cb: Callable[[int, str], None],+ start: int,+ end: int,+ label: str,+ stop: threading.Event,+ interval: float = 3.0,+) -> None:+ """+ Smoothly increments progress between start and end while a+ long-running operation runs without being able to emit callbacks.+ Stops as soon as stop is set.+ """+ current = start+ max_reach = end - 2+ increment = max(1, (end - start) // 10)++ while current < max_reach and not stop.is_set():+ stop.wait(interval)+ if stop.is_set():+ break+ current = min(current + increment, max_reach)+ progress_cb(current, label)+++class BaseGenerator(ABC):+ # ------------------------------------------------------------------ #+ # Metadata — override in each subclass+ # ------------------------------------------------------------------ #+ MODEL_ID: str = ""+ MODEL_NODE_ID: str = ""+ DISPLAY_NAME: str = ""+ VRAM_GB: int = 0 # Minimum recommended VRAM (in GB)++ def __init__(self, model_dir: Path, outputs_dir: Path) -> None:+ self.model_dir = model_dir+ self.outputs_dir = outputs_dir+ self._model = None+ # Injected by the registry from the manifest+ self.hf_repo: str = ""+ self.hf_skip_prefixes: list = []+ self.download_check: str = "" # relative path to check in model_dir+ self._params_schema: list = [] # params declared in the manifest+ # Host-resolved extension-scoped shared weight roots, keyed by group id.+ # Model identity and the private model_dir remain unchanged.+ self.shared_model_dirs: dict[str, Path] = {}++ # ------------------------------------------------------------------ #+ # Model lifecycle+ # ------------------------------------------------------------------ #++ def is_downloaded(self) -> bool:+ """+ Checks that model files are present on disk.+ Uses download_check from the manifest if available,+ otherwise checks that model_dir exists and is non-empty.+ Can be overridden in generator.py for custom logic.+ """+ if self.download_check:+ return (self.model_dir / self.download_check).exists()+ return self.model_dir.exists() and any(self.model_dir.iterdir())++ @abstractmethod+ def load(self) -> None:+ """Load the model into memory (GPU/CPU)."""+ ...++ def unload(self) -> None:+ """Release memory. Can be overridden if needed."""+ self._model = None+ import gc+ gc.collect()+ try:+ import torch+ if torch.cuda.is_available():+ torch.cuda.empty_cache()+ elif torch.backends.mps.is_available():+ torch.mps.empty_cache()+ except ImportError:+ pass+ # Force the OS to reclaim unused memory from this process+ try:+ import ctypes+ import sys+ if sys.platform == "win32":+ kernel32 = ctypes.windll.kernel32+ kernel32.SetProcessWorkingSetSizeEx(+ kernel32.GetCurrentProcess(), -1, -1, 0+ )+ except Exception:+ pass++ def is_loaded(self) -> bool:+ return self._model is not None++ # ------------------------------------------------------------------ #+ # Inference+ # ------------------------------------------------------------------ #++ def generate(+ self,+ image_bytes: bytes,+ params: dict,+ progress_cb: Optional[Callable[[int, str], None]] = None,+ cancel_event: Optional[threading.Event] = None,+ ) -> Path:+ """+ Starts 3D generation from an image.+ Returns the path to the generated .glb file.+ progress_cb(percent: int, step_label: str)+ cancel_event: set this to interrupt generation between steps.+ """+ raise NotImplementedError(+ f"{type(self).__name__} does not implement legacy image generation"+ )++ def generate_artifact(+ self,+ input_kind: str,+ artifact_path: Path,+ params: dict,+ progress_cb: Optional[Callable[[int, str], None]] = None,+ cancel_event: Optional[threading.Event] = None,+ ) -> Path:+ """Generate from a validated typed artifact.++ Typed-artifact extensions must implement this explicitly. Falling back+ to ``generate`` would pass a filesystem ``Path`` to the legacy+ image-bytes ABI and fail far from the actual contract violation.+ """+ raise NotImplementedError(+ f"{type(self).__name__} does not implement {input_kind} artifact generation"+ )++ def _check_cancelled(self, cancel_event: Optional[threading.Event]) -> None:+ """Raises GenerationCancelled if cancel_event is set."""+ if cancel_event and cancel_event.is_set():+ raise GenerationCancelled()++ # ------------------------------------------------------------------ #+ # Parameter schema (for the UI)+ # ------------------------------------------------------------------ #++ def params_schema(self) -> list:+ """+ Returns the parameter schema for the UI.+ Reads _params_schema injected from the manifest.+ Can be overridden in generator.py for custom logic.+ """+ return self._params_schema++ # ------------------------------------------------------------------ #+ # Standard download+ # ------------------------------------------------------------------ #++ def _auto_download(self) -> None:+ """+ Downloads weights from self.hf_repo (injected by the registry).+ Used as a fallback when is_downloaded() returns False.+ Extensions can override this method for custom logic.+ """+ if not self.hf_repo:+ raise RuntimeError(+ f"[{self.MODEL_ID}] Cannot download: hf_repo not configured. "+ "Check the extension's manifest.json."+ )++ from huggingface_hub import snapshot_download++ print(f"[{self.__class__.__name__}] Downloading {self.hf_repo} -> {self.model_dir} ...")+ self.model_dir.mkdir(parents=True, exist_ok=True)++ ignore = list(self.hf_skip_prefixes) + [+ "*.md", "LICENSE", "NOTICE", "Notice.txt", ".gitattributes",+ ]+ snapshot_download(+ repo_id=self.hf_repo,+ local_dir=str(self.model_dir),+ ignore_patterns=ignore,+ )+ print(f"[{self.__class__.__name__}] Download complete.")++ # ------------------------------------------------------------------ #+ # Helpers+ # ------------------------------------------------------------------ #++ def _report(+ self,+ progress_cb: Optional[Callable[[int, str], None]],+ pct: int,+ step: str,+ ) -> None:+ if progress_cb:+ progress_cb(pct, step)diff --git a/apps/forge-desktop/api/services/imported_sources.py b/apps/forge-desktop/api/services/imported_sources.pynew file mode 100644index 000000000..a21dded52--- /dev/null+++ b/apps/forge-desktop/api/services/imported_sources.py@@ -0,0 +1,53 @@+"""Registry of meshes the user explicitly imported from outside the workspace.++`/optimize/import-by-path` serves files the user picked through the OS file+dialog, either in place or converted into a temp dir — never from the workspace.+The slicer export route confines itself to the workspace by design, so those+imports would be unsliceable without widening that guard to arbitrary absolute+paths, which would be a real regression.++This registry is the narrow alternative: a route may accept an absolute path+only if it is an EXACT member here, i.e. a file the user chose themselves in+this session. Membership is an equality test, never a prefix test, so it grants+no traversal.++It also remembers each file's ORIGINAL suffix. An imported `.stl` is converted+to GLB on import without any axis change, so the container extension alone would+mislead a consumer into applying the glTF Y-up -> Z-up rotation to data that is+already Z-up.++Session-scoped and in-memory: it is emptied when the backend restarts, so a+deeplink replayed after a restart is rejected rather than silently served. Links+are consumed within a second of the click, so this is not worth persisting.+"""++from pathlib import Path++# resolved absolute path (str) -> original suffix, lowercase, with the dot+_SOURCES: dict[str, str] = {}+++def register(served_path: str | Path, original_path: str | Path) -> str:+ """Record a user-imported file as sliceable and return its resolved path.++ ``served_path`` is what gets served (possibly a converted temp GLB);+ ``original_path`` is the file the user actually picked, whose suffix decides+ the source format.+ """+ resolved = str(Path(served_path).resolve())+ _SOURCES[resolved] = Path(original_path).suffix.lower()+ return resolved+++def source_suffix(path: str | Path) -> str | None:+ """Original suffix of a registered import, or None if it is not registered."""+ return _SOURCES.get(str(Path(path).resolve()))+++def is_registered(path: str | Path) -> bool:+ return source_suffix(path) is not None+++def clear() -> None:+ """Drop every entry — for tests."""+ _SOURCES.clear()diff --git a/apps/forge-desktop/api/services/llm_server.py b/apps/forge-desktop/api/services/llm_server.pynew file mode 100644index 000000000..c41fb196a--- /dev/null+++ b/apps/forge-desktop/api/services/llm_server.py@@ -0,0 +1,1045 @@+"""+Local LLM engine — manages a llama.cpp `llama-server` subprocess.++Everything lives under the agent directory (MODLY_LLM_DIR, set by Electron to+the `agent` folder beside models/, extensions/, … — ~/.modly/llm/ when the API+runs standalone):+ bin/ llama-server binary + DLLs (auto-downloaded from GitHub releases)+ models/ GGUF files (catalog downloads + any custom .gguf the user drops in)+ logs/ one log per llama-server slot+ config.json pool settings (max_models)++Nothing is hardcoded to a machine: the binary variant is picked per-platform+(CUDA if an NVIDIA driver is present, otherwise Vulkan, otherwise CPU) and+models are chosen by the user from the catalog.+"""+import contextlib+import hashlib+import os+import re+import shutil+import subprocess+import sys+import tempfile+import threading+import time+import zipfile+from pathlib import Path+from typing import Callable, Optional+from urllib.request import Request, urlopen+import json as _json++LLM_DIR = Path(os.environ.get("MODLY_LLM_DIR") or Path.home() / ".modly" / "llm")+BIN_DIR = LLM_DIR / "bin"+LLM_MODELS_DIR = LLM_DIR / "models"+LOGS_DIR = LLM_DIR / "logs"+SERVER_PORT = int(os.environ.get("MODLY_LLM_PORT", "8791"))++# Modly is first and foremost a 3D-generation app: the LLM must never sit on+# VRAM it isn't using. Idle models are evicted after this many seconds.+IDLE_TTL_SECONDS = int(os.environ.get("MODLY_LLM_IDLE_TTL", "300"))++# Multi-model pool: each loaded model gets its own llama-server process on its+# own port (SERVER_PORT .. SERVER_PORT+MAX_SLOT_PORTS-1). How many may run at+# once is user-configurable ("auto" sizes it from the GPU's VRAM — small cards+# stay at 1, exactly like the old single-slot behavior).+MAX_SLOT_PORTS = 4+CONFIG_PATH = LLM_DIR / "config.json"++LLM_MODELS_DIR.mkdir(parents=True, exist_ok=True)+++def load_config() -> dict:+ try:+ return _json.loads(CONFIG_PATH.read_text(encoding="utf-8"))+ except Exception:+ return {}+++def save_config(cfg: dict) -> None:+ CONFIG_PATH.write_text(_json.dumps(cfg, indent=2), encoding="utf-8")+++_vram_gb_cache: Optional[float] = None+++def detect_vram_gb() -> float:+ """Total VRAM of the first NVIDIA GPU in GiB (0.0 if none/unknown)."""+ global _vram_gb_cache+ if _vram_gb_cache is not None:+ return _vram_gb_cache+ try:+ out = subprocess.run(+ ["nvidia-smi", "--query-gpu=memory.total", "--format=csv,noheader,nounits"],+ capture_output=True, text=True, timeout=10,+ ).stdout.strip().splitlines()+ _vram_gb_cache = round(float(out[0]) / 1024.0, 1) if out else 0.0+ except Exception:+ _vram_gb_cache = 0.0+ return _vram_gb_cache+++def resolve_max_models() -> int:+ """How many llama-server processes may run at once.++ Priority: MODLY_LLM_MAX_MODELS env → user config → auto from VRAM.+ Auto is deliberately conservative: 8 GB cards keep the single-slot+ behavior, VRAM stays available for the 3D pipeline."""+ raw = os.environ.get("MODLY_LLM_MAX_MODELS") or load_config().get("max_models") or "auto"+ if isinstance(raw, str) and raw.lower() == "auto":+ # Thresholds sit just under the marketing size on purpose: a card sold+ # as "12 GB" reports 12227 MiB = 11.9 GiB, so a `>= 12` test excluded+ # every 12 GB card there is (5070, 4070, 3060 12G…) from the 2-slot+ # tier it was written for. Same story at 20 for a 20/24 GB card.+ vram = detect_vram_gb()+ n = 3 if vram >= 19.5 else 2 if vram >= 11.5 else 1+ else:+ try:+ n = int(raw)+ except (TypeError, ValueError):+ n = 1+ return max(1, min(n, MAX_SLOT_PORTS))++_BINARY_NAME = "llama-server.exe" if sys.platform == "win32" else "llama-server"+_UA = {"User-Agent": "modly-llm"}++# Pinned to a known-good tag by default so installs are reproducible and never+# silently pick up a broken/incompatible "latest" release. Set MODLY_LLM_RELEASE+# to another llama.cpp tag (e.g. "b10075") to override, or to "latest" to track+# the newest release.+_RELEASE_TAG = os.environ.get("MODLY_LLM_RELEASE", "b10075")+_RELEASES_API = (+ "https://api.github.com/repos/ggml-org/llama.cpp/releases/latest"+ if _RELEASE_TAG.lower() == "latest"+ else f"https://api.github.com/repos/ggml-org/llama.cpp/releases/tags/{_RELEASE_TAG}"+)++CATALOG_PATH = Path(__file__).resolve().parent.parent / "resources" / "llm_catalog.json"++DEFAULT_CTX = 16384+DEFAULT_NGL = 99+++def load_catalog() -> list[dict]:+ return _json.loads(CATALOG_PATH.read_text(encoding="utf-8"))+++_FALLBACK_DEFAULT_MODEL = "qwen3-4b"++# What the agent sends when a catalog entry declares nothing of its own. Low+# temperature is what keeps small models from emitting malformed tool-call JSON.+_DEFAULT_SAMPLING = {"temperature": 0.2}+++def sampling_for(model_id: str) -> dict:+ """Sampling parameters for one local model.++ Model families publish the settings they were tuned for, and ignoring them+ is not neutral: served at a flat temperature with no presence penalty, a+ Qwen 3.5 repeated the same lookup ten times in one turn and never acted.+ A catalog entry can therefore carry its own `sampling` block."""+ entry = next((e for e in load_catalog() if e["id"] == model_id), None)+ declared = (entry or {}).get("sampling") or {}+ return {**_DEFAULT_SAMPLING, **{k: v for k, v in declared.items() if v is not None}}+++def default_model_id() -> str:+ """Catalog entry tagged "default", falling back to a known-good id if the+ catalog has no such tag (keeps old behavior if llm_catalog.json changes)."""+ for entry in load_catalog():+ if "default" in (entry.get("tags") or []):+ return entry["id"]+ return _FALLBACK_DEFAULT_MODEL+++def mmproj_local_name(entry: dict) -> str:+ """Local filename for a vision projector. HF repos all name it mmproj-F16.gguf,+ which would collide across models in the shared models dir."""+ return f"mmproj-{entry['id']}.gguf"+++def list_models() -> list[dict]:+ """Catalog entries with a `downloaded` flag + custom GGUFs found on disk."""+ catalog = load_catalog()+ known_files = set()+ for entry in catalog:+ path = LLM_MODELS_DIR / entry["hf_filename"]+ downloaded = path.exists()+ if entry.get("hf_mmproj_filename"):+ downloaded = downloaded and (LLM_MODELS_DIR / mmproj_local_name(entry)).exists()+ known_files.add(mmproj_local_name(entry))+ # Show the real download size (weights + vision projector)+ entry["size_bytes"] = (entry.get("size_bytes") or 0) + (entry.get("mmproj_size_bytes") or 0)+ entry["downloaded"] = downloaded+ entry["source"] = "catalog"+ known_files.add(entry["hf_filename"])++ custom = [+ {+ "id": f"custom:{f.name}",+ "name": f.stem,+ "description": "Custom model found in the models folder.",+ "hf_filename": f.name,+ "size_bytes": f.stat().st_size,+ "downloaded": True,+ "source": "custom",+ "ctx": DEFAULT_CTX,+ "ngl_suggestion": DEFAULT_NGL,+ "tags": ["custom"],+ }+ for f in sorted(LLM_MODELS_DIR.glob("*.gguf"))+ if f.name not in known_files and not f.name.lower().startswith("mmproj")+ ]+ return catalog + custom+++def estimate_vram_mb(entry: dict) -> int:+ """How much VRAM this model is expected to hold, in MiB.++ Catalog entries declare it. A user's own GGUF doesn't, so it is derived from+ the file: weights land in VRAM about 1:1, plus the KV cache and compute+ buffers for a 16k context. Measured against the catalog's own numbers, whose+ declared/file ratio runs 1.22–1.32, so 1.25 + 500 MiB sits in the middle."""+ declared = entry.get("vram_estimate_mb")+ if isinstance(declared, (int, float)) and declared > 0:+ return int(declared)+ size_mb = (entry.get("size_bytes") or 0) / (1024 * 1024)+ return int(size_mb * 1.25 + 500) if size_mb else 0+++def vram_budget_mb() -> int:+ """VRAM the LLM pool may fill, in MiB — total minus what the desktop needs.+ 0 when no NVIDIA GPU is detected, which disables budgeting entirely."""+ total = detect_vram_gb() * 1024+ if total <= 0:+ return 0+ reserve = _env_int("MODLY_LLM_VRAM_RESERVE_MB", 768)+ return max(0, int(total) - reserve)+++def _env_int(name: str, default: int) -> int:+ try:+ return int(os.environ.get(name) or default)+ except ValueError:+ return default+++def resolve_model(model_id: str) -> dict:+ """Return {gguf_path, mmproj_path, ngl, ctx, vision, vram_mb} for a catalog id+ or a custom:<file> id."""+ if model_id.startswith("custom:"):+ # The name is user/agent-supplied and this path is both loaded and+ # DELETEd (DELETE /llm/models/{model_id}). Confine it to the models dir:+ # on Windows a backslash is a separator too, so "custom:..\..\x.gguf"+ # would otherwise resolve — and unlink — outside it.+ name = model_id[len("custom:"):]+ path = (LLM_MODELS_DIR / name).resolve()+ root = LLM_MODELS_DIR.resolve()+ if path.parent != root or not path.exists() or path.suffix != ".gguf":+ raise KeyError(f"Custom model not found: {model_id}")+ return {+ "gguf_path": path, "mmproj_path": None, "ngl": DEFAULT_NGL,+ "ctx": DEFAULT_CTX, "vision": False,+ "vram_mb": estimate_vram_mb({"size_bytes": path.stat().st_size}),+ }+ for entry in load_catalog():+ if entry["id"] == model_id:+ has_mmproj = bool(entry.get("hf_mmproj_filename"))+ return {+ "gguf_path": LLM_MODELS_DIR / entry["hf_filename"],+ "mmproj_path": LLM_MODELS_DIR / mmproj_local_name(entry) if has_mmproj else None,+ "ngl": entry.get("ngl_suggestion", DEFAULT_NGL),+ "ctx": entry.get("ctx", DEFAULT_CTX),+ "vision": "vision" in (entry.get("tags") or []),+ "vram_mb": estimate_vram_mb(entry),+ }+ raise KeyError(f"Unknown model id: {model_id}")+++def binary_path() -> Path:+ return BIN_DIR / _BINARY_NAME+++def binary_installed() -> bool:+ return binary_path().exists()+++def has_nvidia_gpu() -> bool:+ return shutil.which("nvidia-smi") is not None+++# ─── Binary bootstrap ─────────────────────────────────────────────────────────++def _fetch_release() -> dict:+ with urlopen(Request(_RELEASES_API, headers=_UA), timeout=30) as r:+ return _json.loads(r.read())+++def _cuda_ver(name: str) -> tuple[int, int]:+ m = re.search(r"cuda-(?:cu)?(\d+)[._](\d+)", name.lower())+ return (int(m.group(1)), int(m.group(2))) if m else (0, 0)+++def _driver_cuda_version() -> tuple[int, int]:+ """Highest CUDA version the installed NVIDIA driver supports (0,0 if unknown)."""+ try:+ out = subprocess.run(["nvidia-smi"], capture_output=True, text=True, timeout=10).stdout+ m = re.search(r"CUDA Version:\s*(\d+)\.(\d+)", out)+ return (int(m.group(1)), int(m.group(2))) if m else (0, 0)+ except Exception:+ return (0, 0)+++def _pick_assets(assets: list[dict]) -> list[dict]:+ """Ordered list of assets to install for this machine.++ Windows + NVIDIA: the CUDA build (self-contained, includes CPU fallback)+ plus its matching `cudart-…` runtime package. Otherwise Vulkan, then CPU.+ macOS / Linux: the platform tarball (Vulkan variant preferred on Linux).+ """+ import platform as _platform++ def matching(ext: tuple[str, ...], *needles: str) -> list[dict]:+ return [+ a for a in assets+ if a["name"].endswith(ext) and all(n in a["name"].lower() for n in needles)+ ]++ if sys.platform == "win32":+ if has_nvidia_gpu():+ builds = matching((".zip",), "win", "x64", "cuda")+ builds = [b for b in builds if not b["name"].startswith("cudart")]+ if builds:+ driver = _driver_cuda_version()+ # Newest build the driver can run; if the driver version is+ # unknown, the oldest build has the widest compatibility.+ supported = [b for b in builds if _cuda_ver(b["name"]) <= driver]+ pool = supported or builds+ pick = max(pool, key=lambda b: _cuda_ver(b["name"])) if supported else \+ min(pool, key=lambda b: _cuda_ver(b["name"]))+ ver = _cuda_ver(pick["name"])+ cudart = [+ a for a in assets+ if a["name"].startswith("cudart") and _cuda_ver(a["name"]) == ver+ ]+ return [pick, *cudart[:1]]+ return (matching((".zip",), "win", "x64", "vulkan")+ or matching((".zip",), "win", "x64", "cpu")+ or matching((".zip",), "win", "x64", "avx2"))[:1]++ if sys.platform == "darwin":+ arch = "arm64" if _platform.machine().lower() in ("arm64", "aarch64") else "x64"+ exts = (".zip", ".tar.gz")+ return (matching(exts, "macos", arch) or matching(exts, "macos"))[:1]++ exts = (".zip", ".tar.gz")+ return (matching(exts, "ubuntu", "vulkan", "x64")+ or matching(exts, "ubuntu", "x64")+ or matching(exts, "linux", "x64"))[:1]+++def _download_asset(asset: dict, progress_cb: Callable[[dict], None], control_check: Callable[[], None], label: str) -> Path:+ suffix = ".tar.gz" if asset["name"].endswith(".tar.gz") else ".zip"+ fd, tmp_name = tempfile.mkstemp(suffix=suffix)+ os.close(fd)+ tmp = Path(tmp_name)+ sha256 = hashlib.sha256()+ try:+ with urlopen(Request(asset["browser_download_url"], headers=_UA), timeout=30) as resp:+ total = int(resp.headers.get("Content-Length", 0)) or asset.get("size", 0)+ done = 0+ last_emit = 0.0+ with open(tmp, "wb") as fh:+ while chunk := resp.read(1 << 20):+ control_check()+ fh.write(chunk)+ sha256.update(chunk)+ done += len(chunk)+ now = time.monotonic()+ if now - last_emit >= 0.5:+ progress_cb({+ "status": f"Downloading {label} ({asset['name']})",+ "bytesDownloaded": done,+ "totalBytes": total,+ "percent": round(done / total * 100) if total else 0,+ })+ last_emit = now+ _verify_digest(asset, sha256.hexdigest())+ except BaseException:+ tmp.unlink(missing_ok=True) # never leave a partial or rejected archive behind+ raise+ return tmp+++def _verify_digest(asset: dict, actual_sha256: str) -> None:+ """Refuse an archive whose bytes differ from what GitHub published for it.++ The files extracted from it are executed (llama-server and its DLLs), so a+ corrupted or tampered download must not get that far. GitHub reports a+ `digest` ("sha256:<hex>") for every release asset; one without it (older+ uploads) cannot be checked and is accepted as before."""+ expected = asset.get("digest") or ""+ if not expected.startswith("sha256:"):+ return+ if actual_sha256.lower() != expected[len("sha256:"):].lower():+ raise RuntimeError(+ f"Checksum mismatch for {asset['name']}: the download does not match the "+ "published llama.cpp release. Try installing the engine again."+ )+++_LIB_SUFFIXES = (".so", ".dylib", ".metal")+++def _extract_archive(tmp: Path, asset_name: str) -> int:+ """Extract runtime files flat into BIN_DIR (exe/dll on Windows, bin/* + libs elsewhere)."""+ BIN_DIR.mkdir(parents=True, exist_ok=True)+ count = 0++ def wanted(member_path: str, fname_low: str) -> bool:+ if sys.platform == "win32":+ return fname_low.endswith((".exe", ".dll"))+ return "/bin/" in member_path.replace("\\", "/") or fname_low.endswith(_LIB_SUFFIXES)++ if asset_name.endswith(".tar.gz"):+ import tarfile+ with tarfile.open(tmp, "r:gz") as tf:+ for m in tf.getmembers():+ if not m.isfile():+ continue+ fname = Path(m.name).name+ if not fname or not wanted(m.name, fname.lower()):+ continue+ src = tf.extractfile(m)+ if src is None:+ continue+ dest = BIN_DIR / fname+ with open(dest, "wb") as dst:+ shutil.copyfileobj(src, dst)+ if not fname.lower().endswith(_LIB_SUFFIXES):+ dest.chmod(0o755)+ count += 1+ return count++ with zipfile.ZipFile(tmp) as zf:+ for item in zf.infolist():+ if item.is_dir():+ continue+ fname = Path(item.filename).name+ if not fname or not wanted(item.filename, fname.lower()):+ continue+ dest = BIN_DIR / fname+ with zf.open(item) as src, open(dest, "wb") as dst:+ shutil.copyfileobj(src, dst)+ if sys.platform != "win32" and not fname.lower().endswith(_LIB_SUFFIXES):+ dest.chmod(0o755)+ count += 1+ return count+++def install_binary(progress_cb: Callable[[dict], None], control_check: Callable[[], None]) -> None:+ """Download and install the best llama-server build for this machine."""+ progress_cb({"status": "Fetching latest llama.cpp release…", "percent": 0})+ release = _fetch_release()+ progress_cb({"status": f"Release {release['tag_name']} — selecting build for this machine…", "percent": 1})++ assets = _pick_assets(release["assets"])+ if not assets:+ raise RuntimeError("No compatible llama.cpp build found for this platform.")++ for i, asset in enumerate(assets):+ label = "engine" if i == 0 else "CUDA runtime"+ tmp = _download_asset(asset, progress_cb, control_check, label)+ try:+ count = _extract_archive(tmp, asset["name"])+ progress_cb({"status": f"Extracted {count} files from {asset['name']}"})+ finally:+ tmp.unlink(missing_ok=True)++ if not binary_installed():+ raise RuntimeError("Install finished but llama-server binary is missing.")+ progress_cb({"status": "done", "percent": 100})+++# ─── Orphan prevention ────────────────────────────────────────────────────────+# If Modly is force-killed, a plain child process would keep its model in+# memory forever. On Windows we put llama-server in a Job object with+# KILL_ON_JOB_CLOSE (the OS kills it when Modly dies); on Linux we ask the+# kernel to deliver SIGKILL on parent death.++_win_job_handle = None+++def _windows_job() -> Optional[int]:+ global _win_job_handle+ if _win_job_handle is not None:+ return _win_job_handle+ try:+ import ctypes+ from ctypes import wintypes++ class JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):+ _fields_ = [+ ("PerProcessUserTimeLimit", ctypes.c_int64),+ ("PerJobUserTimeLimit", ctypes.c_int64),+ ("LimitFlags", wintypes.DWORD),+ ("MinimumWorkingSetSize", ctypes.c_size_t),+ ("MaximumWorkingSetSize", ctypes.c_size_t),+ ("ActiveProcessLimit", wintypes.DWORD),+ ("Affinity", ctypes.c_size_t),+ ("PriorityClass", wintypes.DWORD),+ ("SchedulingClass", wintypes.DWORD),+ ]++ class IO_COUNTERS(ctypes.Structure):+ _fields_ = [(n, ctypes.c_uint64) for n in (+ "ReadOperationCount", "WriteOperationCount", "OtherOperationCount",+ "ReadTransferCount", "WriteTransferCount", "OtherTransferCount")]++ class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure):+ _fields_ = [+ ("BasicLimitInformation", JOBOBJECT_BASIC_LIMIT_INFORMATION),+ ("IoInfo", IO_COUNTERS),+ ("ProcessMemoryLimit", ctypes.c_size_t),+ ("JobMemoryLimit", ctypes.c_size_t),+ ("PeakProcessMemoryUsed", ctypes.c_size_t),+ ("PeakJobMemoryUsed", ctypes.c_size_t),+ ]++ kernel32 = ctypes.windll.kernel32+ job = kernel32.CreateJobObjectW(None, None)+ info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION()+ info.BasicLimitInformation.LimitFlags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE+ kernel32.SetInformationJobObject(job, 9, ctypes.byref(info), ctypes.sizeof(info)) # JobObjectExtendedLimitInformation+ _win_job_handle = job+ return job+ except Exception:+ return None+++def _tie_to_parent(process: subprocess.Popen) -> None:+ if sys.platform == "win32":+ job = _windows_job()+ if job is not None:+ try:+ import ctypes+ ctypes.windll.kernel32.AssignProcessToJobObject(job, int(process._handle)) # type: ignore[attr-defined]+ except Exception:+ pass+++def _linux_preexec():+ try:+ import ctypes+ import signal as _signal+ libc = ctypes.CDLL("libc.so.6", use_errno=True)+ libc.prctl(1, _signal.SIGKILL) # PR_SET_PDEATHSIG+ except Exception:+ pass+++def _kill_stale_server(port: int = SERVER_PORT) -> None:+ """Kill a leftover llama-server holding `port` (e.g. after a force-kill of Modly)."""+ try:+ with urlopen(Request(f"http://127.0.0.1:{port}/health", headers=_UA), timeout=1) as r:+ if r.status != 200:+ return+ except Exception:+ return # nothing listening — the normal case+ try:+ if sys.platform == "win32":+ out = subprocess.run(+ ["netstat", "-ano", "-p", "tcp"], capture_output=True, text=True, timeout=10,+ ).stdout+ for line in out.splitlines():+ if f":{port}" in line and "LISTENING" in line.upper():+ pid = line.split()[-1]+ name = subprocess.run(+ ["tasklist", "/FI", f"PID eq {pid}", "/FO", "CSV", "/NH"],+ capture_output=True, text=True, timeout=10,+ ).stdout.lower()+ if "llama-server" in name:+ subprocess.run(["taskkill", "/PID", pid, "/F"], capture_output=True, timeout=10)+ break+ else:+ out = subprocess.run(+ ["lsof", "-ti", f"tcp:{port}"], capture_output=True, text=True, timeout=10,+ ).stdout+ for pid in out.split():+ name = subprocess.run(+ ["ps", "-p", pid, "-o", "comm="], capture_output=True, text=True, timeout=10,+ ).stdout.lower()+ if "llama-server" in name:+ subprocess.run(["kill", "-9", pid], capture_output=True, timeout=10)+ except Exception:+ pass+++# ─── Managed server ───────────────────────────────────────────────────────────++class LlamaServerManager:+ """One llama-server slot — a single loaded GGUF on a dedicated port.++ Slots are owned by LlamaPool, which decides how many run at once, evicts+ idle ones (IDLE_TTL_SECONDS), and unloads everything when the 3D pipeline+ needs the VRAM.+ """++ def __init__(self, port: int = SERVER_PORT) -> None:+ self.port = port+ self._lock = threading.Lock()+ self._process: Optional[subprocess.Popen] = None+ self._current_id: Optional[str] = None+ self._started_at: Optional[float] = None+ self._last_used: float = 0.0+ self._log_file = None+ # Requests currently being answered by this slot. Guarded by its own+ # lock: _lock is held for the whole of a cold start (up to 180 s), and a+ # request must never wait on that to declare itself in flight.+ self._inflight: int = 0+ self._inflight_lock = threading.Lock()+ # Expected VRAM of whatever this slot is serving, for the pool's budget.+ self.vram_mb: int = 0++ @property+ def base_url(self) -> str:+ return f"http://127.0.0.1:{self.port}/v1"++ def _alive(self) -> bool:+ return self._process is not None and self._process.poll() is None++ def ensure(self, model_id: str, spec: dict) -> None:+ """Blocking: make sure `model_id` is loaded, swapping the server if needed.+ `spec` comes from resolve_model()."""+ with self._lock:+ self._last_used = time.monotonic()+ if self._current_id == model_id and self._alive():+ return+ if not binary_installed():+ raise RuntimeError("llama-server is not installed. Install the engine in Settings → Agent.")+ if not spec["gguf_path"].exists():+ raise RuntimeError(f"Model file not found: {spec['gguf_path'].name}. Download it in Settings → Agent.")++ self._terminate_locked()+ _kill_stale_server(self.port)+ self._spawn(spec)+ self._current_id = model_id+ self._started_at = time.monotonic()+ self._last_used = time.monotonic()++ def touch(self) -> None:+ """Mark the server as recently used (postpones idle eviction)."""+ self._last_used = time.monotonic()++ @property+ def busy_count(self) -> int:+ with self._inflight_lock:+ return self._inflight++ def hold(self) -> None:+ """Claim the slot for a request that is about to start."""+ with self._inflight_lock:+ self._inflight += 1+ self._last_used = time.monotonic()++ def release(self) -> None:+ with self._inflight_lock:+ self._inflight -= 1+ self._last_used = time.monotonic()++ @contextlib.contextmanager+ def busy(self):+ """Hold the slot for the duration of one request.++ _last_used only moved when a completion *finished*, so a generation+ longer than IDLE_TTL_SECONDS — a Text-to-CAD node parked on /llm/chat,+ or an agent round on a 14B running on CPU — looked idle to the reaper,+ which terminated the server mid-answer: truncated stream, node failed+ with no message. Marking the request in flight covers the whole call,+ including the prompt-eval stall before the first token."""+ self.hold()+ try:+ yield self+ finally:+ self.release()++ def _spawn(self, spec: dict) -> None:+ n_threads = max(1, int((os.cpu_count() or 4) * 0.8))+ cmd = [+ str(binary_path()),+ "-m", str(spec["gguf_path"]),+ "--port", str(self.port),+ "--host", "127.0.0.1",+ "-c", str(spec["ctx"]),+ "-ngl", str(spec["ngl"]),+ "--jinja",+ "-np", "1",+ "--threads", str(n_threads),+ "--threads-batch", str(n_threads),+ ]+ if spec.get("mmproj_path"):+ cmd += ["--mmproj", str(spec["mmproj_path"])]+ if has_nvidia_gpu():+ # Halve KV-cache VRAM so the larger context still fits 12 GB cards.+ # V-cache quantization requires flash attention (fine on CUDA).+ cmd += ["-fa", "on", "-ctk", "q8_0", "-ctv", "q8_0"]+ # llama-server resolves its plugin DLLs (ggml-cuda, ggml-cpu-*) relative+ # to cwd, not the exe path — running from bin/ is required.+ env = {**os.environ, "PATH": str(BIN_DIR) + os.pathsep + os.environ.get("PATH", "")}+ kwargs: dict = {}+ if sys.platform.startswith("linux"):+ kwargs["preexec_fn"] = _linux_preexec++ # Overwritten on every spawn (one log per slot/port) so a crash at+ # startup (OOM, corrupt GGUF) can be diagnosed instead of vanishing+ # into DEVNULL.+ LOGS_DIR.mkdir(parents=True, exist_ok=True)+ self._log_file = open(LOGS_DIR / f"slot-{self.port}.log", "w", encoding="utf-8")++ self._process = subprocess.Popen(+ cmd,+ stdout=self._log_file,+ stderr=subprocess.STDOUT,+ cwd=str(BIN_DIR),+ env=env,+ **kwargs,+ )+ _tie_to_parent(self._process)+ self._wait_for_health()++ def _wait_for_health(self, timeout: float = 180.0, interval: float = 1.0) -> None:+ url = f"http://127.0.0.1:{self.port}/health"+ deadline = time.time() + timeout+ while time.time() < deadline:+ if not self._alive():+ raise RuntimeError("llama-server exited during startup (bad model file or out of memory?).")+ try:+ with urlopen(Request(url, headers=_UA), timeout=2) as r:+ if r.status == 200:+ return+ except Exception:+ pass+ time.sleep(interval)+ self._terminate_locked()+ raise TimeoutError(f"llama-server did not become ready within {timeout:.0f}s")++ def unload(self) -> None:+ with self._lock:+ self._terminate_locked()++ def _terminate_locked(self) -> None:+ if self._process is None:+ return+ try:+ self._process.terminate()+ try:+ self._process.wait(timeout=10)+ except subprocess.TimeoutExpired:+ self._process.kill()+ except Exception:+ pass+ finally:+ self._process = None+ self._current_id = None+ self._started_at = None+ if self._log_file is not None:+ self._log_file.close()+ self._log_file = None++ def snapshot(self) -> dict:+ alive = self._alive()+ return {+ "alive": alive,+ "model_id": self._current_id if alive else None,+ "port": self.port,+ "uptime_seconds": round(time.monotonic() - self._started_at, 1) if alive and self._started_at else None,+ "vram_mb": self.vram_mb if alive else None,+ }+++class LlamaPool:+ """Pool of llama-server slots — one process per loaded model, each on its+ own port, capped by BOTH resolve_max_models() and vram_budget_mb()+ (LRU eviction).++ The idle reaper and unload_all() keep the old guarantees: models are+ evicted after IDLE_TTL_SECONDS unused, and the 3D pipeline can reclaim all+ VRAM at once.+ """++ def __init__(self) -> None:+ self._lock = threading.Lock()+ self._slots: dict[str, LlamaServerManager] = {}+ # Ports held by a load in flight. A reserved slot has no process yet, so+ # _alive() cannot tell it apart from a dead one; tracking the port rather+ # than the model_id keeps the reservation valid even if unload() drops+ # the slot from _slots while it is still starting.+ self._loading_ports: set[int] = set()+ # Signalled whenever a load lands, so callers held back by a concurrent+ # cold start can re-run the limit check instead of loading on top of it.+ self._cond = threading.Condition(self._lock)+ self._reaper_started = False++ def ensure(self, model_id: str, spec: dict, hold: bool = False) -> LlamaServerManager:+ """Blocking: return a ready slot serving `model_id`, starting it (and+ evicting the least-recently-used slots) if needed.++ With `hold`, the slot is returned already claimed for one request and the+ caller MUST call slot.release() when done (see busy()). Without it there+ is a window between "loaded" and "in flight" in which a competing load+ can evict the slot, and the caller then posts to a dead server: with+ max_models = 1, two nodes asking for different models had one of them+ answer 500 Internal Server Error.++ The slot is reserved under the pool lock but LOADED outside it. A cold+ start blocks in _wait_for_health for up to 180 s, and holding the pool+ lock that long froze every other caller: /llm/status, polled by an open+ Settings → Agent page, hung for the whole load, and switch_model's+ unload_all() — which exists to reclaim VRAM before a 3D model — queued+ behind the very LLM competing for it.++ Loading outside the lock means two callers can be starting different+ models at the same time (an agent turn plus a workflow LLM node). A slot+ being started holds no process, so it cannot be evicted to make room:+ when only such loads keep the pool over its limit, this waits for one to+ land — it then becomes an ordinary eviction candidate — instead of+ putting a second model on a card sized for one.+ """+ incoming_mb = spec.get("vram_mb") or 0+ # A last resort, not a policy: past this the thing we are waiting for is+ # stuck, and blocking forever would be worse than loading on top of it.+ deadline = time.monotonic() + 300.0+ with self._lock:+ while True:+ slot = self._slots.get(model_id)+ if slot is not None and slot._alive():+ break+ if slot is not None and slot.port not in self._loading_ports:+ # A server that crashed (OOM, CUDA error) leaves its slot+ # behind, and its port is free for the next model. Respawning+ # in place would then find that model's server healthy on+ # "our" port and kill it. Start over on a fresh port instead.+ self._drop_dead_locked(model_id, slot)+ slot = None+ # Also for a dead slot respawned in place, so reviving one+ # cannot push the pool past the limit. Only alive slots that are+ # not answering a request are eviction candidates, so this never+ # evicts our own — nor anyone's live stream.+ self._enforce_limit_locked(reserve=1, incoming_mb=incoming_mb)+ remaining = deadline - time.monotonic()+ if (not self._over_capacity_locked(incoming_mb)+ or not self._transient_blockers_locked()+ or remaining <= 0):+ break+ # Re-checked about once a second: capacity also frees up when a+ # request finishes, which is not a load event and so notifies+ # nothing.+ self._cond.wait(min(1.0, remaining))+ if slot is None:+ used_ports = {s.port for s in self._slots.values() if s._alive()} | self._loading_ports+ port = next(+ (SERVER_PORT + i for i in range(MAX_SLOT_PORTS)+ if SERVER_PORT + i not in used_ports),+ None,+ )+ if port is None:+ # A bare next() raised StopIteration here, which surfaced to+ # the caller as "Could not start the local LLM: " — an empty+ # message. Say what actually happened.+ raise RuntimeError(+ f"All {MAX_SLOT_PORTS} local-LLM slots are in use or starting up. "+ "Wait for a run to finish, or lower the model limit in Settings → Agent."+ )+ slot = LlamaServerManager(port)+ self._slots[model_id] = slot+ slot.vram_mb = incoming_mb+ self._loading_ports.add(slot.port)+ if hold:+ # Claimed BEFORE the load, not after: a caller woken by this load+ # landing would otherwise find the slot idle and evict it, and+ # two racing callers spent their time killing each other's+ # freshly loaded model until one gave up.+ slot.hold()+ self._start_reaper()++ # Outside the pool lock. LlamaServerManager holds its own, so concurrent+ # callers for the same model serialise here and the later ones no-op.+ try:+ slot.ensure(model_id, spec)+ except Exception:+ if hold:+ slot.release() # nothing to answer with — do not pin the slot+ with self._lock:+ if self._slots.get(model_id) is slot and not slot._alive():+ self._slots.pop(model_id, None)+ raise+ finally:+ with self._lock:+ self._loading_ports.discard(slot.port)+ self._cond.notify_all() # waiters can re-run the limit check+ return slot++ def _evictable_locked(self, slot: LlamaServerManager) -> bool:+ """May this slot be unloaded to make room? Shared by the limit check and+ the idle reaper, which both unload while holding the pool lock — a rule+ applied to only one of them is a rule that does not hold.++ A slot answering a request is spared because terminating it truncates+ the caller's stream mid-generation. A slot another thread is loading is+ spared for a harder reason: from the moment Popen returns it is _alive()+ (the long wait is _wait_for_health, up to 180 s) while its own lock is+ held by the loader, so unload() would block on that lock and freeze the+ whole pool with it — /llm/status, every ensure(), and the unload_all()+ the 3D pipeline needs to reclaim VRAM. Its cost is still counted, it+ just cannot be the victim."""+ return slot.busy_count == 0 and slot.port not in self._loading_ports++ def _enforce_limit_locked(self, reserve: int = 0, incoming_mb: int = 0) -> None:+ """Evict LRU slots until the pool fits BOTH limits: the configured model+ count, and the VRAM budget.++ The count alone was not enough. `max_models: 2` let any two models in,+ so a 9 GB custom model plus a vision model on a 12 GB card oversubscribed+ the card; Windows spills to shared memory instead of failing, so nothing+ errored — a cold start just went from 5 s to 24 s with no explanation.+ Budgeting on declared estimates keeps the pairs that actually fit (a 4B+ and a 7B come to 10.4 of 11.5 GiB) and refuses the ones that never did.++ The incoming model is never rejected: if it does not fit even alone,+ everything else is evicted and it loads by itself."""+ alive = [(mid, s) for mid, s in self._slots.items() if s._alive()]+ alive.sort(key=lambda kv: kv[1]._last_used) # oldest first+ # Slots reserved by a concurrent ensure() hold no process yet, so+ # _alive() cannot see them. Counting only live slots let two concurrent+ # ensure() calls — an agent turn plus a workflow LLM node — each+ # conclude the pool was empty and both load, which on an 8 GB card+ # (max_models = 1) is exactly the oversubscription this rule prevents.+ loading = [s for s in self._slots.values()+ if s.port in self._loading_ports and not s._alive()]+ candidates = [kv for kv in alive if self._evictable_locked(kv[1])]++ def _evict_oldest() -> None:+ mid, slot = candidates.pop(0)+ alive.remove((mid, slot))+ slot.unload()+ self._slots.pop(mid, None)++ max_n = resolve_max_models()+ while len(alive) + len(loading) + reserve > max_n and candidates:+ _evict_oldest()++ budget = vram_budget_mb()+ if not budget or not incoming_mb:+ return # no GPU detected, or an unknown estimate — count rule only++ def _committed_mb() -> int:+ return sum(s.vram_mb for _mid, s in alive) + sum(s.vram_mb for s in loading)++ while candidates and _committed_mb() + incoming_mb > budget:+ _evict_oldest()++ def _transient_blockers_locked(self) -> bool:+ """Is the pool full only of things that end on their own — a load in+ flight, or a slot answering a request? Those are worth waiting for; a+ merely idle slot is not (it gets evicted instead)."""+ return bool(self._loading_ports) or any(+ s.busy_count for s in self._slots.values() if s._alive()+ )++ def _over_capacity_locked(self, incoming_mb: int) -> bool:+ """Would loading one more model break either limit, counting the slots+ another thread is starting right now?"""+ alive = [s for s in self._slots.values() if s._alive()]+ loading = [s for s in self._slots.values()+ if s.port in self._loading_ports and not s._alive()]+ if len(alive) + len(loading) + 1 > resolve_max_models():+ return True+ budget = vram_budget_mb()+ if not budget or not incoming_mb:+ return False # no GPU detected, or an unknown estimate+ committed = sum(s.vram_mb for s in alive) + sum(s.vram_mb for s in loading)+ return committed + incoming_mb > budget++ def enforce_limit(self) -> None:+ """Apply the configured limit right away (used when the user lowers it)."""+ with self._lock:+ self._enforce_limit_locked()++ def is_loaded(self, model_id: str) -> bool:+ with self._lock:+ slot = self._slots.get(model_id)+ return slot is not None and slot._alive()++ def touch(self, model_id: str) -> None:+ with self._lock:+ slot = self._slots.get(model_id)+ if slot is not None:+ slot.touch()++ def unload(self, model_id: str) -> None:+ with self._lock:+ slot = self._slots.pop(model_id, None)+ if slot is not None:+ slot.unload()++ def unload_all(self, force: bool = False) -> None:+ """Free the pool's VRAM. Slots answering a request or being started are+ spared (see _evictable_locked): killing one cut a Text-to-CAD stream off+ mid-answer when a 3D model loaded, and a cold start in another thread+ handed its caller a dead slot. `force` is for shutdown only."""+ if force:+ with self._lock:+ slots = list(self._slots.values())+ self._slots.clear()+ for slot in slots:+ slot.unload()+ return+ with self._lock:+ for mid, slot in list(self._slots.items()):+ if self._evictable_locked(slot):+ slot.unload()+ self._slots.pop(mid, None)++ def _drop_dead_locked(self, model_id: str, slot: LlamaServerManager) -> None:+ self._slots.pop(model_id, None)+ slot.unload() # reaps the exited process and closes its log++ def _start_reaper(self) -> None:+ if self._reaper_started or IDLE_TTL_SECONDS <= 0:+ return+ self._reaper_started = True+ threading.Thread(target=self._reap_idle, daemon=True, name="llm-idle-reaper").start()++ def _reap_idle(self) -> None:+ while True:+ time.sleep(15)+ self._reap_once()++ def _reap_once(self, now: Optional[float] = None) -> None:+ now = time.monotonic() if now is None else now+ with self._lock:+ for mid, slot in list(self._slots.items()):+ if not self._evictable_locked(slot):+ continue # answering right now, or being loaded — never idle+ if not slot._alive():+ self._drop_dead_locked(mid, slot)+ elif now - slot._last_used > IDLE_TTL_SECONDS:+ slot.unload()+ self._slots.pop(mid, None)++ def snapshot(self) -> dict:+ with self._lock:+ slots = list(self._slots.values())+ servers = [s.snapshot() for s in slots if s._alive()]+ first = servers[0] if servers else {"alive": False, "model_id": None, "port": SERVER_PORT, "uptime_seconds": None}+ return {+ **first, # legacy single-server shape+ "servers": servers,+ "max_models": resolve_max_models(),+ "vram_gb": detect_vram_gb() or None,+ "vram_budget_mb": vram_budget_mb() or None,+ "vram_used_mb": sum(s.get("vram_mb") or 0 for s in servers) or None,+ }+++llama_pool = LlamaPool()diff --git a/apps/forge-desktop/api/services/mesh_ops/__init__.py b/apps/forge-desktop/api/services/mesh_ops/__init__.pynew file mode 100644index 000000000..40f9e61c3--- /dev/null+++ b/apps/forge-desktop/api/services/mesh_ops/__init__.py@@ -0,0 +1,26 @@+"""Unified mesh operation registry used by the API and workflow nodes."""++from .builtin import BUILTIN_MESH_OPS+from .registry import MeshOpsRegistry+from .types import (+ MeshOp,+ MeshOpContext,+ MeshOpExecutionError,+ MeshOpNotFoundError,+ MeshOpResult,+ MeshOpUnavailableError,+)+++mesh_ops_registry = MeshOpsRegistry(BUILTIN_MESH_OPS)++__all__ = [+ "MeshOp",+ "MeshOpContext",+ "MeshOpExecutionError",+ "MeshOpNotFoundError",+ "MeshOpResult",+ "MeshOpsRegistry",+ "MeshOpUnavailableError",+ "mesh_ops_registry",+]diff --git a/apps/forge-desktop/api/services/mesh_ops/builtin.py b/apps/forge-desktop/api/services/mesh_ops/builtin.pynew file mode 100644index 000000000..900bd1933--- /dev/null+++ b/apps/forge-desktop/api/services/mesh_ops/builtin.py@@ -0,0 +1,131 @@+"""Built-in mesh operation definitions."""++from .operations import decimate_mesh, repair_mesh, smooth_mesh+from .types import MeshOp+++REPAIR_PARAMS = (+ {+ "id": "remove_duplicates",+ "label": "Remove Duplicates",+ "type": "boolean",+ "default": True,+ "tooltip": "Remove duplicate vertices and faces.",+ },+ {+ "id": "remove_degenerate",+ "label": "Remove Degenerate Faces",+ "type": "boolean",+ "default": True,+ "tooltip": "Remove zero-area faces and collapsed edges.",+ },+ {+ "id": "fix_non_manifold",+ "label": "Fix Non-Manifold",+ "type": "boolean",+ "default": True,+ "tooltip": "Detach faces causing non-manifold edges.",+ },+ {+ "id": "fill_holes",+ "label": "Fill Holes",+ "type": "boolean",+ "default": True,+ "tooltip": (+ "Fill simple boundary holes. Structural holes from AI generation "+ "may not be fillable in post-processing."+ ),+ },+ {+ "id": "max_hole_size",+ "label": "Max Hole Size",+ "type": "int",+ "default": 2000,+ "min": 10,+ "max": 10000,+ "tooltip": (+ "Maximum number of boundary edges of a hole to be filled. "+ "Increase if large holes remain open."+ ),+ },+)++DECIMATE_PARAMS = (+ {+ "id": "target_faces",+ "label": "Target Triangles",+ "type": "int",+ "default": 10000,+ "min": 100,+ "max": 1000000,+ "tooltip": "Target number of triangles after simplification.",+ },+)++SMOOTH_PARAMS = (+ {+ "id": "iterations",+ "label": "Iterations",+ "type": "int",+ "default": 5,+ "min": 1,+ "max": 50,+ "tooltip": (+ "Number of smoothing passes. More iterations = smoother result "+ "but may lose fine details."+ ),+ },+ {+ "id": "lambda_",+ "label": "Smoothing Strength",+ "type": "float",+ "default": 0.5,+ "min": 0.1,+ "max": 1.0,+ "step": 0.05,+ "tooltip": (+ "Controls how far each vertex moves toward its neighbours per "+ "iteration. Lower = more conservative."+ ),+ },+ {+ "id": "mode",+ "label": "Mode",+ "type": "select",+ "default": "taubin",+ "options": [+ {"value": "taubin", "label": "Taubin (volume-preserving)"},+ {"value": "laplacian", "label": "Laplacian (stronger, may shrink)"},+ ],+ "tooltip": (+ "Taubin alternates positive/negative steps to prevent mesh "+ "shrinkage. Laplacian is simpler but tends to shrink the mesh over "+ "many iterations."+ ),+ },+)+++BUILTIN_MESH_OPS = (+ MeshOp(+ id="repair",+ label="Repair Mesh",+ params_schema=REPAIR_PARAMS,+ fn=repair_mesh,+ category="repair",+ ),+ MeshOp(+ id="decimate",+ label="Optimize Mesh",+ params_schema=DECIMATE_PARAMS,+ fn=decimate_mesh,+ category="optimization",+ ),+ MeshOp(+ id="smooth",+ label="Smooth Mesh",+ params_schema=SMOOTH_PARAMS,+ fn=smooth_mesh,+ category="optimization",+ ),+)diff --git a/apps/forge-desktop/api/services/mesh_ops/meshopt_runner.cjs b/apps/forge-desktop/api/services/mesh_ops/meshopt_runner.cjsnew file mode 100644index 000000000..3436be44d--- /dev/null+++ b/apps/forge-desktop/api/services/mesh_ops/meshopt_runner.cjs@@ -0,0 +1,120 @@+/**+ * meshoptimizer backend for the Python mesh-op registry.+ *+ * Dependencies are resolved from the built-in mesh-optimizer extension so the+ * packaged app keeps one copy of glTF Transform and meshoptimizer.+ */+const fs = require('fs')+const path = require('path')+const Module = require('module')++function emit(message) {+ process.stdout.write(`${JSON.stringify(message)}\n`)+}++function progress(percent, label) {+ emit({ type: 'progress', percent, label })+}++function log(message) {+ emit({ type: 'log', message: String(message) })+}++function countTriangles(document) {+ let count = 0+ for (const mesh of document.getRoot().listMeshes()) {+ for (const primitive of mesh.listPrimitives()) {+ const indices = primitive.getIndices()+ if (indices) {+ count += Math.round(indices.getCount() / 3)+ } else {+ const positions = primitive.getAttribute('POSITION')+ if (positions) count += Math.round(positions.getCount() / 3)+ }+ }+ }+ return count+}++async function run(payload) {+ const requireExtension = Module.createRequire(+ path.join(payload.dependencyDir, 'package.json'),+ )+ const { NodeIO } = requireExtension('@gltf-transform/core')+ const { ALL_EXTENSIONS } = requireExtension('@gltf-transform/extensions')+ const { simplify, weld } = requireExtension('@gltf-transform/functions')+ const { MeshoptSimplifier } = requireExtension('meshoptimizer')++ const targetFaces = Math.max(+ 100,+ Math.round(Number(payload.params?.target_faces ?? 10000)),+ )+ log(`Target: ${targetFaces} triangles — input: ${payload.inputPath}`)++ await MeshoptSimplifier.ready++ progress(10, 'Loading mesh…')+ const io = new NodeIO().registerExtensions(ALL_EXTENSIONS)+ const document = await io.read(payload.inputPath)+ const currentFaces = countTriangles(document)+ log(`Current triangles: ${currentFaces}`)++ if (currentFaces <= targetFaces) {+ log('Already within target — skipping simplification')+ if (!payload.outputPath) {+ progress(100, 'Done')+ return { filePath: payload.inputPath, faceCount: currentFaces }+ }++ fs.mkdirSync(path.dirname(payload.outputPath), { recursive: true })+ progress(85, 'Writing output…')+ await io.write(payload.outputPath, document)+ progress(100, 'Done')+ log(`Output: ${payload.outputPath}`)+ return { filePath: payload.outputPath, faceCount: currentFaces }+ }++ const ratio = Math.min(1, targetFaces / currentFaces)+ log(+ `Simplification ratio: ${ratio.toFixed(4)} `+ + `(~${Math.round(currentFaces * ratio)} triangles)`,+ )+ const error = Math.max(0.001, 1 - ratio)++ if (currentFaces < 500000) {+ progress(25, 'Welding vertices…')+ await document.transform(weld())+ } else {+ log(`Skipping weld (${currentFaces} faces > 500k threshold)`)+ }++ progress(55, 'Simplifying mesh…')+ await document.transform(+ simplify({ simplifier: MeshoptSimplifier, ratio, error, lockBorder: false }),+ )++ progress(85, 'Writing output…')+ const outputPath = payload.outputPath || path.join(+ payload.workspaceDir,+ 'Workflows',+ `mesh-optimizer-${Date.now()}.glb`,+ )+ fs.mkdirSync(path.dirname(outputPath), { recursive: true })+ await io.write(outputPath, document)++ progress(100, 'Done')+ log(`Output: ${outputPath}`)+ return { filePath: outputPath, faceCount: countTriangles(document) }+}++async function main() {+ const raw = fs.readFileSync(0, 'utf8').trim()+ if (!raw) throw new Error('mesh-optimizer: missing request payload')+ const result = await run(JSON.parse(raw))+ emit({ type: 'done', result })+}++main().catch((error) => {+ emit({ type: 'error', message: String(error) })+ process.exitCode = 1+})diff --git a/apps/forge-desktop/api/services/mesh_ops/operations.py b/apps/forge-desktop/api/services/mesh_ops/operations.pynew file mode 100644index 000000000..7fae38459--- /dev/null+++ b/apps/forge-desktop/api/services/mesh_ops/operations.py@@ -0,0 +1,419 @@+"""Canonical implementations for Modly's built-in mesh operations."""++import json+import os+import re+import shutil+import subprocess+import tempfile+import time+from pathlib import Path+from typing import Any, Mapping++from .types import (+ MeshOpContext,+ MeshOpExecutionError,+ MeshOpResult,+ MeshOpUnavailableError,+)+++def _output_path(context: MeshOpContext, prefix: str) -> Path:+ if context.output_path is not None:+ output = Path(context.output_path)+ else:+ output = (+ context.workspace_dir+ / "Workflows"+ / f"{prefix}-{int(time.time() * 1000)}.glb"+ )+ output.parent.mkdir(parents=True, exist_ok=True)+ return output+++def _load_single_mesh(input_path: Path, trimesh_module):+ loaded = trimesh_module.load(str(input_path))+ if isinstance(loaded, trimesh_module.Scene):+ geometries = list(loaded.geometry.values())+ return (+ trimesh_module.util.concatenate(geometries)+ if len(geometries) > 1+ else geometries[0]+ )+ return loaded+++def _raw_geometry(mesh, trimesh_module):+ loaded = trimesh_module.load(mesh, process=False)+ if isinstance(loaded, trimesh_module.Scene):+ geometries = list(loaded.geometry.values())+ loaded = (+ geometries[0]+ if len(geometries) == 1+ else trimesh_module.util.concatenate(geometries)+ )+ return trimesh_module.Trimesh(+ vertices=loaded.vertices,+ faces=loaded.faces,+ process=False,+ )+++def _face_count(mesh, trimesh_module) -> int:+ if isinstance(mesh, trimesh_module.Scene):+ return sum(len(geometry.faces) for geometry in mesh.geometry.values())+ return int(len(mesh.faces))+++def _has_texture(geometry, trimesh_module) -> bool:+ if not isinstance(geometry.visual, trimesh_module.visual.TextureVisuals):+ return False+ material = geometry.visual.material+ if material is None:+ return False+ return (+ getattr(material, "image", None) is not None+ or getattr(material, "baseColorTexture", None) is not None+ )+++def _texture_image(geometry):+ material = geometry.visual.material+ image = getattr(material, "image", None)+ return image if image is not None else getattr(material, "baseColorTexture", None)+++def _point_mtl_at_texture(mtl_path: str) -> None:+ path = Path(mtl_path)+ if not path.exists():+ return+ contents = path.read_text(encoding="utf-8")+ path.write_text(+ re.sub(r"map_Kd\s+\S+", "map_Kd texture.png", contents),+ encoding="utf-8",+ )+++def _mesh_libraries(operation_name: str):+ try:+ import pymeshlab+ except ImportError as exc:+ raise MeshOpUnavailableError(+ f"{operation_name}: pymeshlab is not available on this system"+ ) from exc++ try:+ import trimesh+ except ImportError as exc:+ raise MeshOpUnavailableError(+ f"{operation_name}: trimesh is not available on this system"+ ) from exc++ return pymeshlab, trimesh+++def repair_mesh(+ input_path: Path,+ params: Mapping[str, Any],+ context: MeshOpContext,+) -> MeshOpResult:+ """Run the exact repair pipeline previously owned by mesh-repair."""+ pymeshlab, trimesh = _mesh_libraries("mesh-repair")++ remove_duplicates = bool(params.get("remove_duplicates", True))+ fix_non_manifold = bool(params.get("fix_non_manifold", True))+ remove_degenerate = bool(params.get("remove_degenerate", True))+ fill_holes = bool(params.get("fill_holes", True))+ max_hole_size = int(params.get("max_hole_size", 2000))+ output_path = _output_path(context, "mesh-repair")++ context.progress(10, "Loading mesh…")+ geometry = _load_single_mesh(input_path, trimesh)++ temporary_dir = tempfile.mkdtemp()+ try:+ ply_input = os.path.join(temporary_dir, "input.ply")+ ply_output = os.path.join(temporary_dir, "output.ply")+ geometry.export(ply_input)++ mesh_set = pymeshlab.MeshSet()+ mesh_set.load_new_mesh(ply_input)++ current = mesh_set.current_mesh()+ context.log(+ f"Input: {current.vertex_number()} verts, "+ f"{current.face_number()} faces"+ )++ if remove_duplicates:+ context.progress(20, "Removing duplicates…")+ mesh_set.meshing_remove_duplicate_vertices()+ mesh_set.meshing_remove_duplicate_faces()++ if remove_degenerate:+ context.progress(40, "Removing degenerate faces…")+ mesh_set.meshing_remove_null_faces()+ mesh_set.meshing_remove_folded_faces()++ if fix_non_manifold:+ context.progress(60, "Fixing non-manifold edges…")+ try:+ mesh_set.meshing_repair_non_manifold_edges(method=0)+ except Exception as exc:+ context.log(f"Non-manifold edge repair skipped: {exc}")+ try:+ mesh_set.meshing_repair_non_manifold_vertices()+ except Exception as exc:+ context.log(f"Non-manifold vertex repair skipped: {exc}")++ if fill_holes:+ context.progress(75, "Filling holes…")+ try:+ mesh_set.meshing_close_holes(+ maxholesize=max_hole_size,+ newfaceselected=False,+ selfintersection=False,+ )+ except Exception as exc:+ context.log(+ "Hole fill skipped (mesh may still be non-manifold): "+ f"{exc}"+ )++ current = mesh_set.current_mesh()+ context.log(+ f"Output: {current.vertex_number()} verts, "+ f"{current.face_number()} faces"+ )++ context.progress(85, "Exporting…")+ mesh_set.save_current_mesh(ply_output)+ result = _raw_geometry(ply_output, trimesh)+ finally:+ shutil.rmtree(temporary_dir, ignore_errors=True)++ result.export(str(output_path))+ context.progress(100, "Done")+ return MeshOpResult(+ file_path=output_path,+ details={"face_count": int(len(result.faces))},+ )+++def smooth_mesh(+ input_path: Path,+ params: Mapping[str, Any],+ context: MeshOpContext,+) -> MeshOpResult:+ """Run the exact Taubin/Laplacian pipeline previously owned by mesh-smoother."""+ pymeshlab, trimesh = _mesh_libraries("mesh-smoother")++ iterations = int(params.get("iterations", 5))+ strength = float(params.get("lambda_", 0.5))+ mode = str(params.get("mode", "taubin"))+ output_path = _output_path(context, "mesh-smoother")++ context.log(+ f"Mode: {mode}, iterations: {iterations}, strength: {strength}"+ )+ context.progress(10, "Loading mesh…")+ geometry = _load_single_mesh(input_path, trimesh)++ temporary_dir = tempfile.mkdtemp()+ try:+ mesh_set = pymeshlab.MeshSet()+ if context.preserve_visuals:+ context.progress(30, "Smoothing (laplacian)…")+ if _has_texture(geometry, trimesh):+ obj_input = os.path.join(temporary_dir, "input.obj")+ texture_input = os.path.join(temporary_dir, "texture.png")+ obj_output = os.path.join(temporary_dir, "output.obj")++ _texture_image(geometry).save(texture_input)+ geometry.export(obj_input)+ _point_mtl_at_texture(os.path.join(temporary_dir, "input.mtl"))++ mesh_set.load_new_mesh(obj_input)+ mesh_set.apply_coord_laplacian_smoothing(+ stepsmoothnum=iterations,+ )+ context.progress(80, "Exporting…")+ mesh_set.save_current_mesh(obj_output)+ _point_mtl_at_texture(obj_output.replace(".obj", ".mtl"))+ result = trimesh.load(obj_output)+ else:+ ply_input = os.path.join(temporary_dir, "input.ply")+ ply_output = os.path.join(temporary_dir, "output.ply")+ geometry.export(ply_input)+ mesh_set.load_new_mesh(ply_input)+ mesh_set.apply_coord_laplacian_smoothing(+ stepsmoothnum=iterations,+ )+ context.progress(80, "Exporting…")+ mesh_set.save_current_mesh(ply_output)+ result = trimesh.load(ply_output, force="mesh")+ else:+ ply_input = os.path.join(temporary_dir, "input.ply")+ ply_output = os.path.join(temporary_dir, "output.ply")+ geometry.export(ply_input)++ mesh_set.load_new_mesh(ply_input)+ context.progress(30, f"Smoothing ({mode})…")++ if mode == "taubin":+ mesh_set.apply_coord_taubin_smoothing(+ lambda_=strength,+ mu=-strength - 0.01,+ stepsmoothnum=iterations,+ )+ else:+ mesh_set.apply_coord_laplacian_smoothing(+ stepsmoothnum=iterations,+ cotangentweight=False,+ )++ context.progress(80, "Exporting…")+ mesh_set.save_current_mesh(ply_output)+ result = _raw_geometry(ply_output, trimesh)+ finally:+ shutil.rmtree(temporary_dir, ignore_errors=True)++ result.export(str(output_path))+ face_count = _face_count(result, trimesh)+ context.log(f"Output: {output_path} ({face_count} faces)")+ context.progress(100, "Done")+ return MeshOpResult(+ file_path=output_path,+ details={"face_count": face_count},+ )+++def _node_executable() -> tuple[str, bool]:+ configured = os.environ.get("MODLY_NODE_EXECUTABLE")+ if configured:+ executable = Path(configured)+ if not executable.is_file():+ raise MeshOpUnavailableError(+ f"Configured Node runtime does not exist: {configured}"+ )+ return str(executable), True++ executable = shutil.which("node") or shutil.which("nodejs")+ if executable is None:+ raise MeshOpUnavailableError(+ "mesh-optimizer requires Node.js (or Modly's Electron runtime)"+ )+ return executable, False+++def _meshopt_dependency_dir() -> Path:+ candidates: list[Path] = []+ extension_dir = os.environ.get("EXTENSION_DIR")+ if extension_dir:+ candidates.append(Path(extension_dir))++ app_root = Path(__file__).resolve().parents[3]+ candidates.extend(+ [+ app_root / "builtin-extensions" / "mesh-optimizer",+ app_root / "out" / "builtin-extensions" / "mesh-optimizer",+ app_root / "src" / "areas" / "workflows" / "nodes" / "mesh-optimizer",+ ]+ )++ for candidate in candidates:+ if (candidate / "node_modules" / "meshoptimizer").exists():+ return candidate++ raise MeshOpUnavailableError(+ "mesh-optimizer dependencies are unavailable; run `npm run build` "+ "before starting Modly from source"+ )+++def decimate_mesh(+ input_path: Path,+ params: Mapping[str, Any],+ context: MeshOpContext,+) -> MeshOpResult:+ """Run the existing glTF Transform + meshoptimizer implementation."""+ executable, electron_runtime = _node_executable()+ dependency_dir = _meshopt_dependency_dir()+ runner_path = Path(__file__).with_name("meshopt_runner.cjs")++ environment = os.environ.copy()+ if electron_runtime:+ environment["ELECTRON_RUN_AS_NODE"] = "1"++ payload = {+ "inputPath": str(input_path),+ "params": dict(params),+ "workspaceDir": str(context.workspace_dir),+ "dependencyDir": str(dependency_dir),+ "outputPath": (+ str(context.output_path) if context.output_path is not None else None+ ),+ }++ process = subprocess.Popen(+ [executable, str(runner_path)],+ cwd=str(dependency_dir),+ env=environment,+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ encoding="utf-8",+ errors="replace",+ bufsize=1,+ )+ if process.stdin is None or process.stdout is None or process.stderr is None:+ process.kill()+ raise MeshOpExecutionError("mesh-optimizer failed to open its I/O pipes")++ process.stdin.write(json.dumps(payload) + "\n")+ process.stdin.close()++ result_payload: dict[str, Any] | None = None+ backend_error: str | None = None+ for raw_line in process.stdout:+ line = raw_line.strip()+ if not line:+ continue+ try:+ message = json.loads(line)+ except json.JSONDecodeError:+ context.log(line)+ continue++ message_type = message.get("type")+ if message_type == "progress":+ context.progress(+ int(message.get("percent", 0)),+ str(message.get("label", "")),+ )+ elif message_type == "log":+ context.log(str(message.get("message", "")))+ elif message_type == "done":+ result_payload = message.get("result") or {}+ elif message_type == "error":+ backend_error = str(message.get("message", "Unknown error"))++ stderr = process.stderr.read().strip()+ return_code = process.wait()+ if backend_error is not None:+ raise MeshOpExecutionError(backend_error)+ if return_code != 0:+ raise MeshOpExecutionError(+ stderr or f"mesh-optimizer exited with code {return_code}"+ )+ if result_payload is None or not result_payload.get("filePath"):+ raise MeshOpExecutionError("mesh-optimizer returned no output file")++ details: dict[str, Any] = {}+ if result_payload.get("faceCount") is not None:+ details["face_count"] = int(result_payload["faceCount"])+ return MeshOpResult(+ file_path=Path(result_payload["filePath"]),+ details=details,+ )diff --git a/apps/forge-desktop/api/services/mesh_ops/processor.py b/apps/forge-desktop/api/services/mesh_ops/processor.pynew file mode 100644index 000000000..9af04353c--- /dev/null+++ b/apps/forge-desktop/api/services/mesh_ops/processor.py@@ -0,0 +1,71 @@+"""Adapter between workflow process-node NDJSON and the mesh-op registry."""++import json+import os+import sys+import tempfile+import traceback+from pathlib import Path++from . import MeshOpContext, mesh_ops_registry+++def _emit(message: dict) -> None:+ print(json.dumps(message), flush=True)+++def run_processor(operation_id: str, processor_id: str) -> None:+ """Read one workflow request, run a registered op, and emit its result."""+ try:+ raw = sys.stdin.readline()+ if not raw:+ raise ValueError(f"{processor_id}: missing request payload")+ data = json.loads(raw)+ input_data = data.get("input") or {}+ input_path = input_data.get("filePath")+ if not input_path or not Path(input_path).is_file():+ if processor_id == "mesh-optimizer":+ raise FileNotFoundError(+ "mesh-optimizer: input.filePath is required"+ )+ raise FileNotFoundError(+ f"{processor_id}: input file not found: {input_path}"+ )++ workspace_dir = Path(+ data.get("workspaceDir")+ or os.environ.get("WORKSPACE_DIR")+ or Path.home() / ".modly" / "workspace"+ )+ temp_dir = Path(+ data.get("tempDir")+ or os.environ.get("TEMP_DIR")+ or tempfile.gettempdir()+ )+ context = MeshOpContext(+ workspace_dir=workspace_dir,+ temp_dir=temp_dir,+ progress_cb=lambda percent, label: _emit(+ {"type": "progress", "percent": percent, "label": label}+ ),+ log_cb=lambda message: _emit({"type": "log", "message": message}),+ )+ result = mesh_ops_registry.run(+ operation_id,+ Path(input_path),+ data.get("params") or {},+ context,+ )+ _emit(+ {+ "type": "done",+ "result": {"filePath": str(result.file_path)},+ }+ )+ except Exception as exc:+ _emit(+ {+ "type": "error",+ "message": f"{exc}\n{traceback.format_exc()}",+ }+ )diff --git a/apps/forge-desktop/api/services/mesh_ops/registry.py b/apps/forge-desktop/api/services/mesh_ops/registry.pynew file mode 100644index 000000000..5d7553400--- /dev/null+++ b/apps/forge-desktop/api/services/mesh_ops/registry.py@@ -0,0 +1,116 @@+"""Registry and dispatcher for mesh-editing operations."""++import re+from copy import deepcopy+from math import isfinite+from pathlib import Path+from typing import Any, Iterable, Mapping, Optional++from .types import MeshOp, MeshOpContext, MeshOpNotFoundError, MeshOpResult+++_OP_ID = re.compile(r"^[a-z][a-z0-9_-]*$")+++def _apply_numeric_bounds(+ parameter_id: str,+ value: Any,+ schema: Mapping[str, Any],+) -> Any:+ """Clamp a supplied numeric value to the bounds declared by its schema."""+ minimum = schema.get("min")+ maximum = schema.get("max")+ if minimum is None and maximum is None:+ return value++ if isinstance(value, bool) or not isinstance(value, (int, float)):+ raise TypeError(f"Parameter {parameter_id!r} must be numeric")+ if isinstance(value, float) and not isfinite(value):+ raise ValueError(f"Parameter {parameter_id!r} must be finite")++ if minimum is not None:+ value = max(minimum, value)+ if maximum is not None:+ value = min(maximum, value)+ return value+++def _validate_param(+ parameter_id: str,+ value: Any,+ schema: Mapping[str, Any],+) -> Any:+ """Validate (and where applicable, clamp) a supplied param against its schema."""+ param_type = schema.get("type")++ if param_type == "boolean":+ if not isinstance(value, bool):+ raise TypeError(f"Parameter {parameter_id!r} must be a boolean")+ return value++ if param_type == "select":+ allowed = {option["value"] for option in schema.get("options", [])}+ if allowed and value not in allowed:+ raise ValueError(+ f"Parameter {parameter_id!r} must be one of {sorted(allowed)}"+ )+ return value++ return _apply_numeric_bounds(parameter_id, value, schema)+++class MeshOpsRegistry:+ """Stores mesh operations and provides one invocation path for every caller."""++ def __init__(self, operations: Iterable[MeshOp] = ()) -> None:+ self._operations: dict[str, MeshOp] = {}+ for operation in operations:+ self.register(operation)++ def register(self, operation: MeshOp) -> None:+ if not _OP_ID.fullmatch(operation.id):+ raise ValueError(f"Invalid mesh operation id: {operation.id!r}")+ if operation.id in self._operations:+ raise ValueError(f"Duplicate mesh operation id: {operation.id!r}")+ self._operations[operation.id] = operation++ def get(self, operation_id: str) -> MeshOp:+ try:+ return self._operations[operation_id]+ except KeyError as exc:+ raise MeshOpNotFoundError(operation_id) from exc++ def describe(self) -> list[dict[str, Any]]:+ return [operation.describe() for operation in self._operations.values()]++ def run(+ self,+ operation_id: str,+ input_path: Path,+ params: Optional[Mapping[str, Any]],+ context: MeshOpContext,+ ) -> MeshOpResult:+ operation = self.get(operation_id)+ path = Path(input_path)+ if not path.is_file():+ raise FileNotFoundError(f"Input mesh not found: {path}")++ resolved_params = {+ schema["id"]: deepcopy(schema["default"])+ for schema in operation.params_schema+ if "id" in schema and "default" in schema+ }+ if params:+ resolved_params.update(params)++ for schema in operation.params_schema:+ parameter_id = schema.get("id")+ if parameter_id not in resolved_params:+ continue+ resolved_params[parameter_id] = _validate_param(+ parameter_id,+ resolved_params[parameter_id],+ schema,+ )++ return operation.fn(path, resolved_params, context)diff --git a/apps/forge-desktop/api/services/mesh_ops/types.py b/apps/forge-desktop/api/services/mesh_ops/types.pynew file mode 100644index 000000000..5951bfe12--- /dev/null+++ b/apps/forge-desktop/api/services/mesh_ops/types.py@@ -0,0 +1,77 @@+"""Shared types for Modly mesh operations."""++from copy import deepcopy+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Callable, Mapping, Optional+++ProgressCallback = Callable[[int, str], None]+LogCallback = Callable[[str], None]+++class MeshOpNotFoundError(LookupError):+ """Raised when a caller requests an operation that is not registered."""+++class MeshOpUnavailableError(RuntimeError):+ """Raised when an operation's runtime dependency is unavailable."""+++class MeshOpExecutionError(RuntimeError):+ """Raised when an operation backend fails while processing a mesh."""+++@dataclass(frozen=True)+class MeshOpContext:+ """Runtime paths and optional workflow-protocol callbacks for an operation."""++ workspace_dir: Path+ temp_dir: Path+ output_path: Optional[Path] = None+ preserve_visuals: bool = False+ progress_cb: Optional[ProgressCallback] = None+ log_cb: Optional[LogCallback] = None++ def progress(self, percent: int, label: str) -> None:+ if self.progress_cb is not None:+ self.progress_cb(percent, label)++ def log(self, message: str) -> None:+ if self.log_cb is not None:+ self.log_cb(message)+++@dataclass(frozen=True)+class MeshOpResult:+ """The file produced by an operation and optional JSON-safe measurements."""++ file_path: Path+ details: Mapping[str, Any] = field(default_factory=dict)+++MeshOpFn = Callable[[Path, Mapping[str, Any], MeshOpContext], MeshOpResult]+++@dataclass(frozen=True)+class MeshOp:+ """One callable operation and the metadata consumed by the UI and agent."""++ id: str+ label: str+ params_schema: tuple[Mapping[str, Any], ...]+ fn: MeshOpFn+ category: str+ destructive: bool = False+ undoable: bool = True++ def describe(self) -> dict[str, Any]:+ """Return the public, serializable part of this registry entry."""+ return {+ "id": self.id,+ "label": self.label,+ "params_schema": deepcopy(list(self.params_schema)),+ "destructive": self.destructive,+ "undoable": self.undoable,+ "category": self.category,+ }diff --git a/apps/forge-desktop/api/services/model_sources.py b/apps/forge-desktop/api/services/model_sources.pynew file mode 100644index 000000000..677a9bfc5--- /dev/null+++ b/apps/forge-desktop/api/services/model_sources.py@@ -0,0 +1,592 @@+"""Validation and readiness helpers for manifest-declared Hugging Face sources."""++from __future__ import annotations++import math+import re+import unicodedata+from pathlib import Path+from typing import Any+++_SAFE_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")+_WINDOWS_DEVICE = re.compile(+ r"^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$", re.IGNORECASE+)+_WINDOWS_UNSAFE = re.compile(r'[<>"|?*\x00-\x1f]')+++def _portable_segment(value: str, field: str) -> str:+ if (+ not value+ or value in {".", ".."}+ or value.endswith((".", " "))+ or ":" in value+ or _WINDOWS_UNSAFE.search(value)+ or _WINDOWS_DEVICE.fullmatch(value)+ ):+ raise ValueError(f'{field} contains unsafe path segment "{value}"')+ return value+++def safe_source_id(value: Any, field: str = "model source id") -> str:+ if (+ not isinstance(value, str)+ or not value+ or value != value.strip()+ or _SAFE_ID.fullmatch(value) is None+ ):+ raise ValueError(f"{field} must be a safe non-empty identifier")+ return _portable_segment(value, field)+++def safe_relative_path(value: Any, field: str, *, allow_dot: bool = False) -> str:+ if not isinstance(value, str) or not value or value != value.strip():+ raise ValueError(f"{field} must be a non-empty relative path")+ if allow_dot and value == ".":+ return value+ if value == "." or value.startswith("/") or "\\" in value:+ raise ValueError(f"{field} must be a safe relative POSIX path")+ for part in value.split("/"):+ _portable_segment(part, field)+ return value+++def _safe_prefix(value: Any, field: str) -> str:+ path = value[:-1] if isinstance(value, str) and value.endswith("/") else value+ safe_relative_path(path, field)+ return value+++def _prefixes(value: Any, field: str) -> list[str] | None:+ if not isinstance(value, list):+ raise ValueError(f"{field} must be an array")+ return [_safe_prefix(entry, f"{field}[{index}]") for index, entry in enumerate(value)]+++def _safe_repo_id(value: Any, field: str) -> str:+ if not isinstance(value, str) or not value or value != value.strip() or "\\" in value:+ raise ValueError(f"{field} must be a non-empty Hugging Face repository id")+ parts = value.split("/")+ if len(parts) > 2 or any(+ part in {"", ".", ".."} or _SAFE_ID.fullmatch(part) is None for part in parts+ ):+ raise ValueError(f"{field} is not a safe Hugging Face repository id")+ return value+++def _safe_revision(value: Any, field: str) -> str | None:+ if value is None:+ return None+ if (+ not isinstance(value, str)+ or not value+ or value != value.strip()+ or value.startswith("/")+ or "\\" in value+ or "\0" in value+ or any(part in {"", ".", ".."} for part in value.split("/"))+ ):+ raise ValueError(f"{field} must be a safe non-empty revision")+ return value+++def normalize_model_sources(+ node: dict[str, Any], *, field_name: str = "model_sources"+) -> list[dict[str, Any]] | None:+ """Validate only the new contract; legacy fields remain untouched."""+ if "model_sources" not in node:+ return None+ raw_sources = node["model_sources"]+ if not isinstance(raw_sources, list) or not raw_sources:+ raise ValueError(f"{field_name} must be a non-empty array")++ aliases: dict[str, str] = {}+ sources: list[dict[str, Any]] = []+ for index, raw in enumerate(raw_sources):+ field = f"{field_name}[{index}]"+ if not isinstance(raw, dict):+ raise ValueError(f"{field} must be an object")+ source_id = safe_source_id(raw.get("id"), f"{field}.id")+ alias = unicodedata.normalize("NFC", source_id).casefold()+ if alias in aliases:+ raise ValueError(+ f'model source ids "{aliases[alias]}" and "{source_id}" are not portable-unique'+ )+ aliases[alias] = source_id+ if raw.get("provider") != "huggingface":+ raise ValueError(f'{field}.provider must be "huggingface"')+ checks = raw.get("checks")+ if not isinstance(checks, list) or not checks:+ raise ValueError(f"{field}.checks must be a non-empty array")++ source: dict[str, Any] = {+ "id": source_id,+ "provider": "huggingface",+ "repo_id": _safe_repo_id(raw.get("repo_id"), f"{field}.repo_id"),+ "destination": safe_relative_path(+ raw.get("destination"), f"{field}.destination", allow_dot=True+ ),+ "checks": [+ safe_relative_path(check, f"{field}.checks[{check_index}]")+ for check_index, check in enumerate(checks)+ ],+ }+ revision = (+ _safe_revision(raw["revision"], f"{field}.revision")+ if "revision" in raw+ else None+ )+ if "revision" in raw and revision is None:+ raise ValueError(f"{field}.revision must be a safe non-empty revision")+ include = (+ _prefixes(raw["include_prefixes"], f"{field}.include_prefixes")+ if "include_prefixes" in raw+ else None+ )+ skip = (+ _prefixes(raw["skip_prefixes"], f"{field}.skip_prefixes")+ if "skip_prefixes" in raw+ else None+ )+ if revision is not None:+ source["revision"] = revision+ if include is not None:+ source["include_prefixes"] = include+ if skip is not None:+ source["skip_prefixes"] = skip+ sources.append(source)+ return sources+++def validate_model_node_ids(nodes: list[dict[str, Any]]) -> None:+ """Managed node roots must be unique on case-insensitive filesystems too."""+ seen: set[str] = set()+ for node in nodes:+ if not isinstance(node, dict):+ raise ValueError("model node must be an object")+ if isinstance(node.get("id"), str) and node["id"].casefold() == "_shared":+ raise ValueError('model node id "_shared" is reserved')+ node_id = safe_source_id(node.get("id"), "model node id")+ alias = node_id.casefold()+ if alias in seen:+ raise ValueError(f'model node id "{node_id}" is not portable-unique')+ seen.add(alias)+++def normalize_weight_groups(manifest: dict[str, Any]) -> list[dict[str, Any]] | None:+ if "weight_groups" not in manifest:+ return None+ raw_groups = manifest["weight_groups"]+ if not isinstance(raw_groups, list) or not raw_groups:+ raise ValueError("weight_groups must be a non-empty array")++ aliases: dict[str, str] = {}+ groups: list[dict[str, Any]] = []+ for index, raw in enumerate(raw_groups):+ field = f"weight_groups[{index}]"+ if not isinstance(raw, dict):+ raise ValueError(f"{field} must be an object")+ raw_group_id = raw.get("id")+ if isinstance(raw_group_id, str) and raw_group_id.casefold() == "_shared":+ raise ValueError(f'{field}.id uses the reserved identifier "_shared"')+ group_id = safe_source_id(raw_group_id, f"{field}.id")+ alias = unicodedata.normalize("NFC", group_id).casefold()+ if alias in aliases:+ raise ValueError(+ f'weight group ids "{aliases[alias]}" and "{group_id}" '+ "are not portable-unique"+ )+ aliases[alias] = group_id+ sources = normalize_model_sources(+ {"model_sources": raw.get("model_sources")},+ field_name=f"{field}.model_sources",+ )+ groups.append({"id": group_id, "model_sources": sources})+ return groups+++def normalize_weight_group_references(+ node: dict[str, Any],+ groups: list[dict[str, Any]] | None,+ *,+ field_name: str = "weight_groups",+) -> list[str] | None:+ if "weight_groups" not in node:+ return None+ raw_refs = node["weight_groups"]+ if not isinstance(raw_refs, list) or not raw_refs:+ raise ValueError(f"{field_name} must be a non-empty array of weight group ids")++ available = {+ unicodedata.normalize("NFC", group["id"]).casefold(): group["id"]+ for group in groups or []+ }+ aliases: dict[str, str] = {}+ refs: list[str] = []+ for index, raw in enumerate(raw_refs):+ group_id = safe_source_id(raw, f"{field_name}[{index}]")+ alias = unicodedata.normalize("NFC", group_id).casefold()+ if alias in aliases:+ raise ValueError(+ f'weight group references "{aliases[alias]}" and "{group_id}" '+ "are not portable-unique"+ )+ aliases[alias] = group_id+ canonical = available.get(alias)+ if canonical is None:+ raise ValueError(+ f'{field_name}[{index}] references unknown weight group "{group_id}"'+ )+ refs.append(canonical)+ return refs+++def _path_has_symlink(root: Path, candidate: Path) -> bool:+ root = root.absolute()+ candidate = candidate.absolute()+ try:+ relative = candidate.relative_to(root)+ except ValueError:+ return True+ current = root+ if current.exists() and current.is_symlink():+ return True+ for part in relative.parts:+ current /= part+ if current.exists() and current.is_symlink():+ return True+ return False+++def resolve_model_root(models_dir: Path, model_id: str) -> Path:+ if not isinstance(model_id, str):+ raise ValueError("Model id must be a string")+ parts = model_id.split("/")+ if len(parts) != 2:+ raise ValueError("Model id must identify one extension node")+ extension_id = safe_source_id(parts[0], "extension id")+ if parts[1].casefold() == "_shared":+ raise ValueError('Model node id "_shared" is reserved')+ node_id = safe_source_id(parts[1], "model node id")+ root = models_dir.absolute()+ candidate = root / extension_id / node_id+ if _path_has_symlink(root, candidate):+ raise ValueError("Model path resolves through a symlink")+ try:+ candidate.resolve().relative_to(root.resolve())+ except ValueError as exc:+ raise ValueError("Model path escapes the models directory") from exc+ return candidate+++def resolve_weight_group_root(models_dir: Path, extension_id: str, group_id: str) -> Path:+ safe_extension_id = safe_source_id(extension_id, "extension id")+ if isinstance(group_id, str) and group_id.casefold() == "_shared":+ raise ValueError('Weight group id "_shared" is reserved')+ safe_group_id = safe_source_id(group_id, "weight group id")+ root = models_dir.absolute()+ candidate = root / safe_extension_id / "_shared" / safe_group_id+ if _path_has_symlink(root, candidate):+ raise ValueError("Weight group path resolves through a symlink")+ try:+ candidate.resolve().relative_to(root.resolve())+ except ValueError as exc:+ raise ValueError("Weight group path escapes the models directory") from exc+ return candidate+++def resolve_weight_storage_root(models_dir: Path, target_id: str) -> Path:+ if not isinstance(target_id, str):+ raise ValueError("Weight target id must be a string")+ parts = target_id.split("/")+ if len(parts) == 2:+ return resolve_model_root(models_dir, target_id)+ if len(parts) == 3 and parts[1] == "_shared":+ return resolve_weight_group_root(models_dir, parts[0], parts[2])+ raise ValueError(+ "Weight target id must identify one model node or extension weight group"+ )+++def resolve_source_destination(models_dir: Path, model_id: str, destination: str) -> Path:+ model_root = resolve_model_root(models_dir, model_id)+ safe_destination = safe_relative_path(destination, "destination", allow_dot=True)+ candidate = model_root if safe_destination == "." else model_root.joinpath(*safe_destination.split("/"))+ if _path_has_symlink(model_root, candidate):+ raise ValueError("Source destination resolves through a symlink")+ return candidate+++def resolve_source_destination_at_root(model_root: Path, destination: str) -> Path:+ safe_destination = safe_relative_path(destination, "destination", allow_dot=True)+ candidate = (+ model_root+ if safe_destination == "."+ else model_root.joinpath(*safe_destination.split("/"))+ )+ if _path_has_symlink(model_root, candidate):+ raise ValueError("Source destination resolves through a symlink")+ return candidate+++def resolve_download_path(destination: Path, filename: str) -> Path:+ safe_filename = safe_relative_path(filename, "Hugging Face repository file")+ candidate = destination.joinpath(*safe_filename.split("/"))+ if _path_has_symlink(destination, candidate):+ raise ValueError("Download target resolves through a symlink")+ return candidate+++def model_sources_are_downloaded(+ models_dir: Path, model_id: str, sources: list[dict[str, Any]]+) -> bool:+ try:+ model_root = resolve_model_root(models_dir, model_id)+ return model_sources_are_downloaded_at_root(model_root, sources)+ except (KeyError, OSError, TypeError, ValueError):+ return False+++def model_sources_are_downloaded_at_root(+ model_root: Path, sources: list[dict[str, Any]]+) -> bool:+ try:+ if not model_root.is_dir():+ return False+ for source in sources:+ destination = resolve_source_destination_at_root(+ model_root, source["destination"]+ )+ if not destination.is_dir():+ return False+ for check in source["checks"]:+ candidate = resolve_download_path(destination, check)+ if (+ not candidate.is_file()+ or candidate.stat().st_size <= 0+ or _path_has_symlink(model_root, candidate)+ ):+ return False+ return bool(sources)+ except (KeyError, OSError, TypeError, ValueError):+ return False+++def weight_group_sources_are_downloaded(+ models_dir: Path, extension_id: str, group: dict[str, Any]+) -> bool:+ try:+ return model_sources_are_downloaded_at_root(+ resolve_weight_group_root(models_dir, extension_id, group["id"]),+ group["model_sources"],+ )+ except (KeyError, OSError, TypeError, ValueError):+ return False+++def validate_source_file_plan(+ sources: list[dict[str, Any]], files_by_source: dict[str, list[str]]+) -> None:+ """Reject cross-source aliases before the first file is written."""+ aliases: dict[str, tuple[str, str]] = {}+ for source in sources:+ source_id = source["id"]+ destination = source["destination"]+ source_files = {+ safe_relative_path(filename, f'model source "{source_id}" file')+ for filename in files_by_source[source_id]+ }+ missing_checks = [check for check in source["checks"] if check not in source_files]+ if missing_checks:+ raise ValueError(+ f'Model source "{source_id}" checks files excluded from its download plan: '+ + ", ".join(missing_checks)+ )+ for safe_filename in source_files:+ target = safe_filename if destination == "." else f"{destination}/{safe_filename}"+ for value in (target, f"{target}.part"):+ alias = unicodedata.normalize("NFC", value).casefold()+ for previous_alias, (previous_source, previous_target) in aliases.items():+ if previous_source == source_id:+ continue+ if (+ alias == previous_alias+ or alias.startswith(f"{previous_alias}/")+ or previous_alias.startswith(f"{alias}/")+ ):+ raise ValueError(+ "Model sources have a portable target collision: "+ f'"{previous_source}:{previous_target}" and "{source_id}:{value}"'+ )+ aliases[alias] = (source_id, value)+++def _prefixes_overlap(left: list[str], right: list[str]) -> bool:+ return any(+ a.lower().startswith(b.lower()) or b.lower().startswith(a.lower())+ for a in left+ for b in right+ )+++def _assert_param_offers_variants(param: str, params_schema: Any, ids: list[str]) -> None:+ """Variant ids must be selectable, so the param they key has to exist and offer them."""+ entry = next(+ (p for p in params_schema if isinstance(p, dict) and p.get("id") == param),+ None,+ ) if isinstance(params_schema, list) else None+ if entry is None:+ raise ValueError(f'weight_variants.param must name a params_schema entry ("{param}")')+ options = entry.get("options")+ if not isinstance(options, list):+ return+ values = {+ str(option.get("value")) if isinstance(option, dict) else str(option)+ for option in options+ }+ missing = [variant_id for variant_id in ids if variant_id not in values]+ if missing:+ raise ValueError(+ f'the "{param}" param must offer every weight variant id '+ f'(missing: {", ".join(missing)})'+ )+++def normalize_weight_variants(+ node: dict[str, Any], params_schema: Any = None+) -> dict[str, Any] | None:+ """Validate a node's separately installable weight variants (e.g. quantizations)."""+ if "weight_variants" not in node:+ return None+ if "model_sources" in node:+ raise ValueError("weight_variants cannot be combined with model_sources")+ if "weight_groups" in node:+ raise ValueError("weight_variants cannot be combined with weight_groups")+ if not isinstance(node.get("hf_repo"), str) or not node["hf_repo"]:+ raise ValueError("weight_variants requires hf_repo on the same node")+ raw = node["weight_variants"]+ if not isinstance(raw, dict):+ raise ValueError("weight_variants must be an object")+ param = safe_source_id(raw.get("param"), "weight_variants.param")+ raw_options = raw.get("options")+ if not isinstance(raw_options, list) or not raw_options:+ raise ValueError("weight_variants.options must be a non-empty array")++ aliases: dict[str, str] = {}+ options: list[dict[str, Any]] = []+ for index, raw_option in enumerate(raw_options):+ field = f"weight_variants.options[{index}]"+ if not isinstance(raw_option, dict):+ raise ValueError(f"{field} must be an object")+ variant_id = safe_source_id(raw_option.get("id"), f"{field}.id")+ alias = unicodedata.normalize("NFC", variant_id).casefold()+ if alias in aliases:+ raise ValueError(+ f'weight variant ids "{aliases[alias]}" and "{variant_id}" are not portable-unique'+ )+ aliases[alias] = variant_id+ label = raw_option.get("label", variant_id)+ if not isinstance(label, str) or not label.strip():+ raise ValueError(f"{field}.label must be a non-empty string")+ size_gb = raw_option.get("size_gb")+ if size_gb is not None and (+ isinstance(size_gb, bool)+ or not isinstance(size_gb, (int, float))+ or not math.isfinite(size_gb)+ or size_gb <= 0+ ):+ raise ValueError(f"{field}.size_gb must be a positive number")+ vram_gb = raw_option.get("vram_gb")+ if vram_gb is not None and (+ isinstance(vram_gb, bool)+ or not isinstance(vram_gb, (int, float))+ or not math.isfinite(vram_gb)+ or vram_gb <= 0+ ):+ raise ValueError(f"{field}.vram_gb must be a positive number")+ include = _prefixes(raw_option.get("include_prefixes"), f"{field}.include_prefixes")+ if not include:+ raise ValueError(f"{field}.include_prefixes must be a non-empty array")+ checks = raw_option.get("checks")+ if not isinstance(checks, list) or not checks:+ raise ValueError(f"{field}.checks must be a non-empty array")+ safe_checks: list[str] = []+ for check_index, check in enumerate(checks):+ path = safe_relative_path(check, f"{field}.checks[{check_index}]")+ if not any(path.startswith(prefix) for prefix in include):+ raise ValueError(+ f"{field}.checks[{check_index}] is not covered by its include_prefixes"+ )+ safe_checks.append(path)+ option: dict[str, Any] = {+ "id": variant_id,+ "label": label,+ "include_prefixes": include,+ "checks": safe_checks,+ }+ if size_gb is not None:+ option["size_gb"] = size_gb+ if vram_gb is not None:+ option["vram_gb"] = vram_gb+ options.append(option)++ for index, option in enumerate(options):+ for other in options[index + 1:]:+ if _prefixes_overlap(option["include_prefixes"], other["include_prefixes"]):+ raise ValueError(+ f'weight variants "{option["id"]}" and "{other["id"]}" share files'+ )+ download_check = node.get("download_check")+ if isinstance(download_check, str) and any(+ _prefixes_overlap([download_check], option["include_prefixes"]) for option in options+ ):+ raise ValueError("download_check must name a file outside every weight variant")+ default = raw.get("default", options[0]["id"])+ if not any(option["id"] == default for option in options):+ raise ValueError("weight_variants.default must name one of its options")+ _assert_param_offers_variants(+ param,+ node.get("params_schema") if params_schema is None else params_schema,+ [option["id"] for option in options],+ )+ return {"param": param, "default": default, "options": options}+++def installed_weight_variants(+ models_dir: Path, model_id: str, variants: dict[str, Any]+) -> list[str]:+ try:+ model_root = resolve_model_root(models_dir, model_id)+ except ValueError:+ return []++ def _present(check: str) -> bool:+ try:+ candidate = resolve_download_path(model_root, check)+ return candidate.is_file() and candidate.stat().st_size > 0+ except (OSError, ValueError):+ return False++ return [+ option["id"]+ for option in variants["options"]+ if all(_present(check) for check in option["checks"])+ ]+++def missing_weight_variant(+ models_dir: Path,+ model_id: str,+ variants: dict[str, Any] | None,+ params: dict[str, Any],+) -> dict[str, Any] | None:+ """The variant selected by params when its files are not installed, else None."""+ if not variants:+ return None+ selected = params.get(variants["param"])+ selected_id = variants["default"] if selected is None else str(selected)+ option = next((o for o in variants["options"] if o["id"] == selected_id), None)+ if option is None or option["id"] in installed_weight_variants(models_dir, model_id, variants):+ return None+ return optiondiff --git a/apps/forge-desktop/api/services/scene_input.py b/apps/forge-desktop/api/services/scene_input.pynew file mode 100644index 000000000..c53950502--- /dev/null+++ b/apps/forge-desktop/api/services/scene_input.py@@ -0,0 +1,138 @@+"""Validation shared by the API and isolated model runner for scene inputs."""+import json+import math+import re+import stat+from pathlib import Path, PurePosixPath, PureWindowsPath++SCHEMA = "modly.scene-manifest.v1"+MANIFEST = "scene-manifest.json"+MAX_MANIFEST_BYTES = 1024 * 1024+MAX_REFERENCES = 4096+MAX_REFERENCED_FILE_BYTES = 16 * 1024**3+MAX_REFERENCED_TOTAL_BYTES = 64 * 1024**3+++def _relative(value: str, *, allow_dot: bool = False) -> Path:+ if not isinstance(value, str) or not value or value != value.strip() or "\x00" in value:+ raise ValueError("Scene path must be a nonempty workspace-relative path")+ value = value.replace("\\", "/")+ if value == "." and allow_dot:+ return Path(".")+ if (PurePosixPath(value).is_absolute() or PureWindowsPath(value).is_absolute()+ or re.match(r"^[A-Za-z][A-Za-z0-9+.-]*:", value)+ or re.search(r"%(?:25|2e|2f|5c|00)", value, re.I)+ or re.search(r"%(?![0-9a-f]{2})", value, re.I)+ or any(part in ("", ".", "..") for part in value.split("/"))):+ raise ValueError("Scene path must be a safe workspace-relative path")+ return Path(*value.split("/"))+++def _inside(path: Path, root: Path) -> Path:+ try:+ relative = path.relative_to(root)+ except ValueError as exc:+ raise ValueError("Scene path escapes its allowed root") from exc+ current = root+ for part in relative.parts:+ current = current / part+ try:+ info = current.lstat()+ except OSError as exc:+ raise ValueError("Scene referenced path is missing or unreadable") from exc+ is_reparse = bool(getattr(info, "st_file_attributes", 0) & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0))+ if current.is_symlink() or is_reparse:+ raise ValueError("Scene referenced path must not use symlinks or reparse points")+ try:+ resolved = path.resolve(strict=True)+ except OSError as exc:+ raise ValueError("Scene referenced path is missing or unreadable") from exc+ if not resolved.is_relative_to(root):+ raise ValueError("Scene path escapes its allowed root")+ return resolved+++def validate_scene_input(workspace: Path, scene_path: str) -> Path:+ """Return a canonical manifest Path, rejecting traversal and symlink escapes.++ V1 sceneRoot is workspace-relative, except '.' denotes the manifest directory.+ An asset's path and preview references are sceneRoot-relative; workspacePath+ is always workspace-relative. Existence never determines which base applies.+ """+ root = workspace.resolve(strict=True)+ relative = _relative(scene_path)+ requested = root / relative+ if requested.name != MANIFEST:+ if requested.suffix.lower() == ".json":+ raise ValueError(f"Scene input accepts a directory or {MANIFEST}")+ requested = requested / MANIFEST+ try:+ manifest_path = _inside(requested, root)+ if not manifest_path.is_file():+ raise ValueError("Scene manifest is not a file")+ if manifest_path.stat().st_size > MAX_MANIFEST_BYTES:+ raise ValueError("Scene manifest exceeds the 1 MiB limit")+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:+ raise ValueError("Scene manifest is missing or invalid JSON") from exc+ if not isinstance(manifest, dict) or manifest.get("schema") != SCHEMA:+ raise ValueError(f"Scene manifest schema must be {SCHEMA}")+ scene_root = _relative(manifest.get("sceneRoot"), allow_dot=True)+ # v1 sceneRoot is workspace-relative; only '.' means the manifest's directory.+ # Never select a base according to which unrelated path happens to exist.+ scene_root_candidate = manifest_path.parent if scene_root == Path(".") else root / scene_root+ root_path = _inside(scene_root_candidate, root)+ if not root_path.is_dir():+ raise ValueError("Scene root is not a directory")+ if not isinstance(manifest.get("assets"), list):+ raise ValueError("Scene manifest assets must be an array")+ if len(manifest["assets"]) > MAX_REFERENCES:+ raise ValueError("Scene manifest contains too many asset references")+ total_bytes = 0+ for asset in manifest["assets"]:+ # Assets may be opaque extension metadata. Validate only references the+ # host understands; never silently resolve a supplied path outside workspace.+ if isinstance(asset, dict):+ for field, base in (("workspacePath", root), ("path", root_path)):+ if field not in asset:+ continue+ target = _inside(base / _relative(asset[field]), root)+ if not target.is_file():+ raise ValueError(f"Scene asset {field} is not a file")+ size = target.stat().st_size+ if size > MAX_REFERENCED_FILE_BYTES:+ raise ValueError("Scene referenced file exceeds the size limit")+ total_bytes += size+ if total_bytes > MAX_REFERENCED_TOTAL_BYTES:+ raise ValueError("Scene referenced files exceed the total size limit")+ preview = manifest.get("preview", {})+ if not isinstance(preview, dict):+ raise ValueError("Scene preview must be an object")+ for name in ("image", "video"):+ if name in preview:+ relative_preview = _relative(preview[name])+ target = _inside(root_path / relative_preview, root)+ if not target.is_file():+ raise ValueError(f"Scene preview {name} is not a file")+ view = manifest.get("initialView")+ if view is not None:+ if not isinstance(view, dict):+ raise ValueError("Scene initialView must be an object")+ for field in ("position", "target", "up"):+ triple = view.get(field)+ if triple is None and field == "up":+ continue+ if (not isinstance(triple, list) or len(triple) != 3+ or any(not isinstance(n, (int, float)) or isinstance(n, bool)+ or not math.isfinite(n) for n in triple)):+ raise ValueError(f"Scene initialView {field} must be a finite numeric triple")+ if view["position"] == view["target"] or view.get("up") == [0, 0, 0]:+ raise ValueError("Scene initialView has degenerate camera vectors")+ return manifest_path+++def revalidate_scene_manifest(workspace: Path, manifest_path: Path) -> Path:+ """Recheck the file immediately before model invocation in the worker."""+ root = workspace.resolve(strict=True)+ candidate = _inside(manifest_path, root)+ return validate_scene_input(root, candidate.relative_to(root).as_posix())diff --git a/apps/forge-desktop/api/services/stdio_utf8.py b/apps/forge-desktop/api/services/stdio_utf8.pynew file mode 100644index 000000000..b0cb7219a--- /dev/null+++ b/apps/forge-desktop/api/services/stdio_utf8.py@@ -0,0 +1,23 @@+"""+Force UTF-8 stdio regardless of the OS locale.++Windows embedded Python defaults stdout/stderr/stdin to the active console+codepage (cp1252, cp932, ...). Any print() containing non-ASCII characters+(e.g. "→", "…") then crashes with UnicodeEncodeError, and reading UTF-8+output under a legacy codepage can kill pipe reader threads. Reconfiguring+all three streams to UTF-8 makes Modly and extension workers agree with the+UTF-8 pipe readers used on the Electron side.+"""+import sys+++def ensure_utf8_stdio() -> None:+ """Reconfigure stdin/stdout/stderr to UTF-8 when the streams support it."""+ for stream in (sys.stdin, sys.stdout, sys.stderr):+ reconfigure = getattr(stream, "reconfigure", None)+ if reconfigure is None:+ continue+ try:+ reconfigure(encoding="utf-8", errors="replace")+ except (ValueError, OSError):+ pass\ No newline at end of filediff --git a/apps/forge-desktop/api/tests/test_agent_router.py b/apps/forge-desktop/api/tests/test_agent_router.pynew file mode 100644index 000000000..ecd2ed7c1--- /dev/null+++ b/apps/forge-desktop/api/tests/test_agent_router.py@@ -0,0 +1,53 @@+import asyncio+import unittest+from unittest import mock++import httpx++import routers.agent as agent+++class _MockClientFactory:+ """Builds real AsyncClients wired to a MockTransport, so execute_tool talks to+ a fake Modly API instead of the network."""++ def __init__(self, handler) -> None:+ self._handler = handler+ self._real = httpx.AsyncClient++ def __call__(self, *args, **kwargs):+ kwargs["transport"] = httpx.MockTransport(self._handler)+ return self._real(*args, **kwargs)+++def _run_tool(name: str, handler) -> tuple[str, object]:+ factory = _MockClientFactory(handler)+ with mock.patch.object(agent.httpx, "AsyncClient", factory):+ return asyncio.run(agent.execute_tool(name, {}, {}))+++class UnloadModelsErrorTests(unittest.TestCase):+ """unload_models must report a failed unload, not claim success (like every+ other POST tool and like the MCP server's modly_unload_models)."""++ def test_http_error_is_surfaced(self) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(500, text="boom")++ text, payload = _run_tool("unload_models", handler)+ # Before the fix the response was discarded and the success string was+ # returned even on a 500; now the shared HTTPStatusError handler runs.+ self.assertTrue(text.startswith("API error 500"), text)+ self.assertIsNone(payload)++ def test_success_still_reports_unloaded(self) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json={"ok": True})++ text, payload = _run_tool("unload_models", handler)+ self.assertIn("unloaded", text.lower())+ self.assertIsNone(payload)+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_agent_workflow_unload.py b/apps/forge-desktop/api/tests/test_agent_workflow_unload.pynew file mode 100644index 000000000..665ea90d5--- /dev/null+++ b/apps/forge-desktop/api/tests/test_agent_workflow_unload.py@@ -0,0 +1,181 @@+import asyncio+import json+import unittest+from unittest import mock++import httpx++import routers.agent as agent+++class _ScriptedServer:+ """MockTransport wiring: serves a scripted /chat/completions sequence and+ records every request body agent_chat sends."""++ def __init__(self, chat_bodies) -> None:+ self._chat = list(chat_bodies)+ self.requests: list[dict] = []+ self._real = httpx.AsyncClient++ def _handler(self, request: httpx.Request) -> httpx.Response:+ if request.url.path.endswith("/chat/completions"):+ self.requests.append({"headers": dict(request.headers), "body": json.loads(request.content)})+ return httpx.Response(200, json=self._chat.pop(0))+ return httpx.Response(404, json={})++ def __call__(self, *args, **kwargs):+ kwargs["transport"] = httpx.MockTransport(self._handler)+ return self._real(*args, **kwargs)+++class _FakeSlot:+ base_url = "http://127.0.0.1:8791/v1"++ def __init__(self) -> None:+ self.released = 0++ def release(self) -> None:+ self.released += 1+++def _assistant(content: str = "", tool_calls=None) -> dict:+ msg: dict = {"role": "assistant", "content": content}+ if tool_calls:+ msg["tool_calls"] = tool_calls+ return {"choices": [{"message": msg}]}+++_RUN_WF1 = {"id": "call_1", "type": "function", "function": {"name": "run_workflow", "arguments": '{"workflow_id": "wf1"}'}}+_SPEC = {"vision": False}+++def _run_local(chat_bodies, context):+ scripted = _ScriptedServer(chat_bodies)+ slot = _FakeSlot()+ request = agent.AgentChatRequest(+ messages=[agent.ChatMessage(role="user", content="make me a thing")],+ model="qwen3-4b",+ context=context,+ )+ with mock.patch.object(agent.httpx, "AsyncClient", scripted), \+ mock.patch.object(agent.llm_server, "resolve_model", return_value=_SPEC), \+ mock.patch.object(agent.llama_pool, "ensure", return_value=slot), \+ mock.patch.object(agent.llama_pool, "unload_all") as unload_all:+ response = asyncio.run(agent.agent_chat(request))+ return scripted, slot, unload_all, response+++class WorkflowVramUnloadTests(unittest.TestCase):+ def test_llm_unloaded_on_the_normal_return_after_a_workflow(self) -> None:+ # Round 1 dispatches a workflow; round 2 is the final answer (no tools) and+ # returns early. The VRAM unload must still fire on that path.+ chat = [_assistant(tool_calls=[_RUN_WF1]), _assistant(content="Running your workflow now.")]+ _, slot, unload_all, response = _run_local(chat, {"workflows": [{"id": "wf1", "name": "My Workflow"}]})+ unload_all.assert_called_once()+ self.assertEqual(slot.released, 1)+ self.assertEqual([a.tool for a in response.actions], ["run_workflow"])++ def test_slot_is_released_before_the_unload(self) -> None:+ # unload_all() spares held slots, so unloading before the release kept+ # the agent's own model on the GPU through the whole workflow.+ chat = [_assistant(tool_calls=[_RUN_WF1]), _assistant(content="ok")]+ released_at_unload: list[int] = []+ slot = _FakeSlot()+ request = agent.AgentChatRequest(+ messages=[agent.ChatMessage(role="user", content="go")],+ model="qwen3-4b",+ context={"workflows": [{"id": "wf1", "name": "My Workflow"}]},+ )+ with mock.patch.object(agent.httpx, "AsyncClient", _ScriptedServer(chat)), \+ mock.patch.object(agent.llm_server, "resolve_model", return_value=_SPEC), \+ mock.patch.object(agent.llama_pool, "ensure", return_value=slot), \+ mock.patch.object(agent.llama_pool, "unload_all", lambda: released_at_unload.append(slot.released)):+ asyncio.run(agent.agent_chat(request))+ self.assertEqual(released_at_unload, [1])++ def test_no_unload_when_no_workflow_was_dispatched(self) -> None:+ _, slot, unload_all, _ = _run_local([_assistant(content="Here is some info.")], {})+ unload_all.assert_not_called()+ self.assertEqual(slot.released, 1)++ def test_a_single_system_message_leads_the_conversation(self) -> None:+ # Qwen3.5's template rejects a system message anywhere but first (HTTP 400).+ context = {"currentMeshPath": "/tmp/a.glb", "extensions": [{"id": "remesh", "name": "Remesh"}]}+ scripted, *_ = _run_local([_assistant(content="ok")], context)+ roles = [m["role"] for m in scripted.requests[0]["body"]["messages"]]+ self.assertEqual(roles, ["system", "user"])+ system = scripted.requests[0]["body"]["messages"][0]["content"]+ self.assertIn("Current mesh path: /tmp/a.glb", system)+ self.assertIn("remesh", system)++ def test_tool_result_answers_its_call_id(self) -> None:+ chat = [_assistant(tool_calls=[_RUN_WF1]), _assistant(content="done")]+ scripted, *_ = _run_local(chat, {"workflows": [{"id": "wf1", "name": "My Workflow"}]})+ tool_msgs = [m for m in scripted.requests[1]["body"]["messages"] if m["role"] == "tool"]+ self.assertEqual(tool_msgs[0]["tool_call_id"], "call_1")+++class ExternalProviderTests(unittest.TestCase):+ def test_external_provider_sends_the_key_and_never_touches_the_local_pool(self) -> None:+ scripted = _ScriptedServer([_assistant(tool_calls=[_RUN_WF1]), _assistant(content="ok")])+ request = agent.AgentChatRequest(+ messages=[agent.ChatMessage(role="user", content="hi")],+ model="gpt-test",+ provider=agent.ProviderConfig(type="external", base_url="https://llm.test/v1/", api_key="sk-test"),+ context={"workflows": [{"id": "wf1", "name": "My Workflow"}]},+ )+ with mock.patch.object(agent.httpx, "AsyncClient", scripted), \+ mock.patch.object(agent.llama_pool, "ensure") as ensure, \+ mock.patch.object(agent.llama_pool, "unload_all") as unload_all:+ response = asyncio.run(agent.agent_chat(request))+ self.assertEqual(response.message, "ok")+ self.assertEqual(scripted.requests[0]["headers"]["authorization"], "Bearer sk-test")+ ensure.assert_not_called()+ unload_all.assert_not_called()++ def test_text_only_provider_gets_a_retry_without_the_image(self) -> None:+ bodies: list[dict] = []++ def handler(request: httpx.Request) -> httpx.Response:+ body = json.loads(request.content)+ bodies.append(body)+ if isinstance(body["messages"][1]["content"], list):+ return httpx.Response(400, json={"error": {"message": "image input not supported"}})+ return httpx.Response(200, json=_assistant(content="ok"))++ real = httpx.AsyncClient+ request = agent.AgentChatRequest(+ messages=[agent.ChatMessage(role="user", content="what is this", images=["data:image/png;base64,AAAA"])],+ model="text-only",+ provider=agent.ProviderConfig(type="external", base_url="https://llm.test/v1", api_key="k"),+ )+ with mock.patch.object(agent.httpx, "AsyncClient", lambda *a, **k: real(*a, transport=httpx.MockTransport(handler), **k)):+ response = asyncio.run(agent.agent_chat(request))+ self.assertEqual(response.message, "ok")+ self.assertEqual(len(bodies), 2)+ self.assertIn("what is this", bodies[1]["messages"][1]["content"])++ def test_provider_error_shows_its_message_not_raw_json(self) -> None:+ def handler(_: httpx.Request) -> httpx.Response:+ return httpx.Response(401, json={"error": {"message": "Incorrect API key provided.", "type": "invalid_request_error"}})++ real = httpx.AsyncClient+ request = agent.AgentChatRequest(+ messages=[agent.ChatMessage(role="user", content="hi")],+ provider=agent.ProviderConfig(type="external", base_url="https://llm.test/v1", api_key="bad"),+ )+ with mock.patch.object(agent.httpx, "AsyncClient", lambda *a, **k: real(*a, transport=httpx.MockTransport(handler), **k)):+ response = asyncio.run(agent.agent_chat(request))+ self.assertEqual(response.message, "LLM error (401): Incorrect API key provided.")++ def test_missing_provider_url_is_reported(self) -> None:+ request = agent.AgentChatRequest(+ messages=[agent.ChatMessage(role="user", content="hi")],+ provider=agent.ProviderConfig(type="external"),+ )+ response = asyncio.run(agent.agent_chat(request))+ self.assertIn("No provider URL", response.message)+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_base_generator.py b/apps/forge-desktop/api/tests/test_base_generator.pynew file mode 100644index 000000000..9adfe00cf--- /dev/null+++ b/apps/forge-desktop/api/tests/test_base_generator.py@@ -0,0 +1,54 @@+import io+import sys+import tempfile+import types+import unittest+from contextlib import redirect_stdout+from pathlib import Path+from unittest.mock import patch++from services.generators.base import BaseGenerator+++class _DownloadGen(BaseGenerator):+ MODEL_ID = "download-test"++ def load(self) -> None:+ pass++ def generate(self, image_bytes, params, progress_cb=None, cancel_event=None) -> Path:+ raise NotImplementedError+++class AutoDownloadPrintTests(unittest.TestCase):+ def test_download_progress_print_is_ascii_safe(self) -> None:+ """Regression: Unicode in the print crashes on cp1252/cp932 Windows."""+ fake_hub = types.ModuleType("huggingface_hub")+ fake_hub.snapshot_download = lambda **kwargs: None++ with tempfile.TemporaryDirectory() as tmp:+ gen = _DownloadGen(Path(tmp) / "model", Path(tmp) / "out")+ gen.hf_repo = "org/repo"++ out = io.StringIO()+ with (+ patch.dict(sys.modules, {"huggingface_hub": fake_hub}),+ redirect_stdout(out),+ ):+ gen._auto_download()++ printed = out.getvalue()+ first_line = printed.splitlines()[0]+ self.assertTrue(first_line.startswith("[_DownloadGen] Downloading org/repo ->"))+ self.assertTrue(first_line.endswith("..."))+ self.assertTrue(all(ord(ch) < 128 for ch in printed))++ def test_typed_artifact_generation_requires_an_explicit_override(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ gen = _DownloadGen(Path(tmp) / "model", Path(tmp) / "out")+ with self.assertRaisesRegex(NotImplementedError, "scene artifact generation"):+ gen.generate_artifact("scene", Path(tmp) / "scene-manifest.json", {})+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_export_router.py b/apps/forge-desktop/api/tests/test_export_router.pynew file mode 100644index 000000000..2bed2a687--- /dev/null+++ b/apps/forge-desktop/api/tests/test_export_router.py@@ -0,0 +1,208 @@+import base64+import io+import tempfile+import unittest+from pathlib import Path++from fastapi import HTTPException++# The export router imports trimesh at module load; skip the whole suite (rather+# than breaking `unittest discover`) in minimal environments without it.+try:+ import numpy as np+ import trimesh++ import routers.export as export_router+ from services import imported_sources++ HAVE_TRIMESH = True+except Exception: # noqa: BLE001+ HAVE_TRIMESH = False+++def _token(rel_path: str) -> str:+ return base64.urlsafe_b64encode(rel_path.encode("utf-8")).decode("ascii").rstrip("=")+++def _load_stl(resp) -> "trimesh.Trimesh":+ return trimesh.load(io.BytesIO(resp.body), file_type="stl")++[email protected](HAVE_TRIMESH, "trimesh not installed")+class ExportForSlicerTests(unittest.TestCase):+ def setUp(self) -> None:+ self._tmp = tempfile.TemporaryDirectory()+ self.workspace = Path(self._tmp.name).resolve()+ self._orig_workspace = export_router.registry.WORKSPACE_DIR+ export_router.registry.WORKSPACE_DIR = self.workspace+ # A box that is tallest along Y (glTF up-axis) and unit-sized, matching+ # what image-to-3D generators emit. Exported to GLB, it reloads as a+ # Scene so the flatten path is exercised too.+ box = trimesh.creation.box(extents=[0.3, 1.0, 0.3])+ self.rel = "Workflows/hero.glb"+ (self.workspace / "Workflows").mkdir(parents=True, exist_ok=True)+ box.export(str(self.workspace / self.rel))++ def tearDown(self) -> None:+ export_router.registry.WORKSPACE_DIR = self._orig_workspace+ self._tmp.cleanup()++ def test_converts_glb_to_stl_with_download_filename(self) -> None:+ resp = export_router.export_for_slicer("stl", _token(self.rel), "model.stl")+ self.assertEqual(resp.media_type, "model/stl")+ self.assertIn('filename="model.stl"', resp.headers["content-disposition"])+ mesh = _load_stl(resp)+ self.assertGreater(len(mesh.faces), 0)++ def test_reorients_y_up_to_z_up(self) -> None:+ # The box is tallest in Y; after the Y->Z rotation it must be tallest in+ # Z so it imports standing upright on the slicer bed.+ resp = export_router.export_for_slicer("stl", _token(self.rel), "model.stl")+ ex = _load_stl(resp).extents+ self.assertEqual(int(np.argmax(ex)), 2, f"expected Z to be the tallest axis, got extents {ex}")++ def test_normalizes_longest_edge_to_default_print_size(self) -> None:+ resp = export_router.export_for_slicer("stl", _token(self.rel), "model.stl")+ longest = float(max(_load_stl(resp).extents))+ self.assertAlmostEqual(longest, export_router.DEFAULT_PRINT_LONGEST_MM, places=3)++ def test_leaves_a_real_world_sized_mesh_alone(self) -> None:+ # A mesh that already carries a physical size is the user's own: silently+ # shrinking a 180 mm part to 50 mm would waste a print.+ big = trimesh.creation.box(extents=[40.0, 180.0, 40.0])+ rel = "Workflows/part.glb"+ big.export(str(self.workspace / rel))+ resp = export_router.export_for_slicer("stl", _token(rel), "model.stl")+ self.assertAlmostEqual(float(max(_load_stl(resp).extents)), 180.0, places=2)++ def test_does_not_rotate_a_z_up_stl_source(self) -> None:+ # STL is conventionally Z-up already; the glTF Y->Z rotation would lay an+ # upright model on its side.+ rel = "Workflows/upright.stl"+ trimesh.creation.box(extents=[10.0, 10.0, 30.0]).export(str(self.workspace / rel))+ resp = export_router.export_for_slicer("stl", _token(rel), "model.stl")+ ex = _load_stl(resp).extents+ self.assertEqual(int(np.argmax(ex)), 2, f"expected Z to stay the tallest axis, got extents {ex}")++ def test_rejects_unsupported_format(self) -> None:+ with self.assertRaises(HTTPException) as ctx:+ export_router.export_for_slicer("glb", _token(self.rel), "model.glb")+ self.assertEqual(ctx.exception.status_code, 400)++ def test_rejects_filename_extension_mismatch(self) -> None:+ with self.assertRaises(HTTPException) as ctx:+ export_router.export_for_slicer("stl", _token(self.rel), "model.obj")+ self.assertEqual(ctx.exception.status_code, 400)++ def test_rejects_malformed_token(self) -> None:+ with self.assertRaises(HTTPException) as ctx:+ export_router.export_for_slicer("stl", "!!!not-base64!!!", "model.stl")+ self.assertEqual(ctx.exception.status_code, 400)++ def test_rejects_path_traversal(self) -> None:+ with self.assertRaises(HTTPException) as ctx:+ export_router.export_for_slicer("stl", _token("../escape.glb"), "model.stl")+ self.assertEqual(ctx.exception.status_code, 400)++ def test_rejects_sibling_prefix_escape(self) -> None:+ # A sibling dir whose name starts with the workspace dir name must not be+ # reachable — the old str.startswith containment guard would allow it.+ sibling = self.workspace.parent / (self.workspace.name + "-secret")+ sibling.mkdir(parents=True, exist_ok=True)+ (sibling / "x.glb").write_bytes(b"nope")+ rel = f"../{self.workspace.name}-secret/x.glb"+ with self.assertRaises(HTTPException) as ctx:+ export_router.export_for_slicer("stl", _token(rel), "model.stl")+ self.assertEqual(ctx.exception.status_code, 400)++ def test_missing_file_is_404(self) -> None:+ with self.assertRaises(HTTPException) as ctx:+ export_router.export_for_slicer("stl", _token("Workflows/nope.glb"), "model.stl")+ self.assertEqual(ctx.exception.status_code, 404)++[email protected](HAVE_TRIMESH, "trimesh not installed")+class FlattenAndScaleHelperTests(unittest.TestCase):+ def test_flatten_bakes_scene_node_transforms(self) -> None:+ # Two boxes placed at different positions via scene-graph transforms.+ # util.concatenate(geometry.values()) would ignore the transforms; the+ # scene-level flatten must reflect them in the combined bounds.+ scene = trimesh.Scene()+ scene.add_geometry(trimesh.creation.box(extents=[2, 2, 2]), transform=trimesh.transformations.translation_matrix([0, 0, 0]))+ scene.add_geometry(trimesh.creation.box(extents=[2, 2, 2]), transform=trimesh.transformations.translation_matrix([100, 0, 0]))+ mesh = export_router._to_single_mesh(scene)+ self.assertIsInstance(mesh, trimesh.Trimesh)+ # Combined X extent spans both boxes: ~101 (from -1 to 101).+ self.assertGreater(mesh.extents[0], 100.0)++ def test_scale_to_print_size(self) -> None:+ mesh = trimesh.creation.box(extents=[1.0, 2.0, 4.0])+ export_router._scale_to_print_size(mesh, longest_mm=80.0)+ self.assertAlmostEqual(float(max(mesh.extents)), 80.0, places=3)++ def test_scale_ignores_degenerate_mesh(self) -> None:+ # A single point cloud has zero extent; scaling must not divide by zero.+ mesh = trimesh.Trimesh(vertices=[[0, 0, 0]], faces=[])+ export_router._scale_to_print_size(mesh) # must not raise++[email protected](HAVE_TRIMESH, "trimesh not installed")+class ImportedSourceSlicerTests(unittest.TestCase):+ """Meshes imported from outside the workspace are sliceable — but only the+ exact files the user picked, and never with the wrong up-axis."""++ def setUp(self) -> None:+ self._tmp = tempfile.TemporaryDirectory()+ self.outside = Path(self._tmp.name).resolve()+ self._orig_workspace = export_router.registry.WORKSPACE_DIR+ # A workspace elsewhere, so nothing here is reachable as a relative path.+ self._ws_tmp = tempfile.TemporaryDirectory()+ export_router.registry.WORKSPACE_DIR = Path(self._ws_tmp.name).resolve()+ imported_sources.clear()+ # Unit-sized and tallest along Y, as a glTF export would be.+ self.mesh_path = self.outside / "imported.glb"+ trimesh.creation.box(extents=[0.3, 1.0, 0.3]).export(str(self.mesh_path))++ def tearDown(self) -> None:+ export_router.registry.WORKSPACE_DIR = self._orig_workspace+ imported_sources.clear()+ self._tmp.cleanup()+ self._ws_tmp.cleanup()++ def test_rejects_an_absolute_path_that_was_never_imported(self) -> None:+ # The whole point of the registry: an absolute path alone buys nothing.+ with self.assertRaises(HTTPException) as ctx:+ export_router.export_for_slicer("stl", _token(str(self.mesh_path)), "model.stl")+ self.assertEqual(ctx.exception.status_code, 400)++ def test_serves_a_registered_import(self) -> None:+ imported_sources.register(self.mesh_path, self.mesh_path)+ resp = export_router.export_for_slicer("stl", _token(str(self.mesh_path)), "model.stl")+ self.assertEqual(resp.media_type, "model/stl")+ self.assertGreater(len(_load_stl(resp).faces), 0)++ def test_rotates_a_registered_gltf_import(self) -> None:+ imported_sources.register(self.mesh_path, self.mesh_path)+ resp = export_router.export_for_slicer("stl", _token(str(self.mesh_path)), "model.stl")+ ex = _load_stl(resp).extents+ self.assertEqual(int(np.argmax(ex)), 2, f"expected Z to be the tallest axis, got extents {ex}")++ def test_does_not_rotate_an_import_that_was_stl_before_conversion(self) -> None:+ # `import-by-path` converts STL/OBJ/PLY to GLB without touching the axes,+ # so the .glb container here still holds Z-up data. Rotating it would be+ # exactly the bug the rotation exists to prevent.+ imported_sources.register(self.mesh_path, self.outside / "original.stl")+ resp = export_router.export_for_slicer("stl", _token(str(self.mesh_path)), "model.stl")+ ex = _load_stl(resp).extents+ self.assertEqual(int(np.argmax(ex)), 1, f"expected Y to stay the tallest axis, got extents {ex}")++ def test_registered_but_deleted_file_is_404(self) -> None:+ imported_sources.register(self.mesh_path, self.mesh_path)+ self.mesh_path.unlink()+ with self.assertRaises(HTTPException) as ctx:+ export_router.export_for_slicer("stl", _token(str(self.mesh_path)), "model.stl")+ self.assertEqual(ctx.exception.status_code, 404)+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_extension_process.py b/apps/forge-desktop/api/tests/test_extension_process.pynew file mode 100644index 000000000..29602cd68--- /dev/null+++ b/apps/forge-desktop/api/tests/test_extension_process.py@@ -0,0 +1,268 @@+import io+import json+import platform+import queue+import unittest+import json+import tempfile+from unittest.mock import patch+from pathlib import Path++from services.extension_process import ExtensionProcess, _venv_python+++def _make_proc() -> ExtensionProcess:+ return ExtensionProcess(ext_dir=None, manifest={"id": "demo"}) # type: ignore[arg-type]+++class ExtensionProcessTests(unittest.TestCase):+ def test_generation_envelope_pins_worker_model_id(self) -> None:+ proc = _make_proc()+ sent = []+ proc._send = sent.append+ proc._receive_generation = lambda *args: Path("result.glb")+ proc._generate_request({"image_b64": ""}, {}, None, None)+ self.assertEqual(sent[0]["model_id"], "demo")++ def test_generate_artifact_sends_typed_scene_without_image_bytes(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ workspace = Path(tmp) / "workspace"+ scene = workspace / "Workflows" / "room"+ scene.mkdir(parents=True)+ manifest = scene / "scene-manifest.json"+ manifest.write_text(json.dumps({+ "schema": "modly.scene-manifest.v1", "sceneRoot": ".", "assets": [],+ }))+ proc = _make_proc()+ calls = []+ proc._generate_request = lambda payload, params, progress, cancel: calls.append((payload, params)) or manifest+ with patch("services.generator_registry.WORKSPACE_DIR", workspace):+ result = proc.generate_artifact("scene", manifest, {"quality": "high"})+ self.assertEqual(result, manifest)+ self.assertEqual(calls, [({"input": {"kind": "scene", "path": str(manifest.resolve())}}, {"quality": "high"})])++ def test_read_loop_writes_sentinel_to_own_queue_only(self) -> None:+ proc = _make_proc()++ old_queue: queue.Queue = queue.Queue()+ new_queue: queue.Queue = queue.Queue()+ proc._queue = new_queue++ fake_proc = type("FakeProc", (), {"stdout": io.StringIO("")})()++ proc._read_loop(fake_proc, old_queue)++ self.assertFalse(old_queue.empty())+ self.assertTrue(new_queue.empty())++ def test_stop_kills_and_verifies_subprocess_exit(self) -> None:+ proc = _make_proc()++ class FakeProcess:+ def __init__(self) -> None:+ self.alive = True+ self.kill_called = False+ self.wait_called = False++ def poll(self):+ return None if self.alive else -9++ def kill(self) -> None:+ self.kill_called = True+ self.alive = False++ def wait(self, timeout: float):+ self.wait_called = True+ return -9++ child = FakeProcess()+ proc._proc = child # type: ignore[assignment]+ proc._loaded = True++ proc.stop()++ self.assertTrue(child.kill_called)+ self.assertTrue(child.wait_called)+ self.assertIsNone(proc._proc)+ self.assertFalse(proc._loaded)++ def test_stop_failure_keeps_live_process_reference_and_raises(self) -> None:+ proc = _make_proc()++ class StuckProcess:+ def poll(self):+ return None++ def kill(self) -> None:+ raise PermissionError("cannot kill")++ def wait(self, timeout: float):+ raise AssertionError("wait must not run after kill failure")++ child = StuckProcess()+ proc._proc = child # type: ignore[assignment]+ proc._loaded = True++ with self.assertRaisesRegex(RuntimeError, "Could not stop"):+ proc.stop()++ self.assertIs(proc._proc, child)+ self.assertFalse(proc._loaded)+++class VenvPythonTests(unittest.TestCase):+ def test_resolves_interpreter_path_for_current_platform(self) -> None:+ result = _venv_python(Path("/tmp/ext"))+ if platform.system() == "Windows":+ self.assertEqual(result, Path("/tmp/ext") / "venv" / "Scripts" / "python.exe")+ else:+ self.assertEqual(result, Path("/tmp/ext") / "venv" / "bin" / "python")+++class BuildEnvTests(unittest.TestCase):+ def test_forces_utf8_stdio_on_worker(self) -> None:+ proc = _make_proc()+ env = proc._build_env()+ self.assertEqual(env.get("PYTHONUTF8"), "1")++ def test_sets_worker_model_dir_when_known(self) -> None:+ proc = _make_proc()+ proc.model_dir = Path("/tmp/models/ext/node")+ env = proc._build_env()+ self.assertEqual(env.get("MODEL_DIR"), str(Path("/tmp/models/ext/node")))++ def test_sets_explicit_node_identity_and_shared_weight_dirs(self) -> None:+ proc = ExtensionProcess(+ ext_dir=Path("/tmp/extensions/ext"),+ manifest={"id": "ext/quality", "node_id": "quality"},+ )+ proc.model_dir = Path("/tmp/models/ext/quality")+ proc.shared_model_dirs = {"base": Path("/tmp/models/ext/_shared/base")}++ env = proc._build_env()++ self.assertEqual(env["MODEL_ID"], "ext/quality")+ self.assertEqual(env["MODEL_NODE_ID"], "quality")+ self.assertEqual(+ json.loads(env["SHARED_MODEL_DIRS"]),+ {"base": str(Path("/tmp/models/ext/_shared/base"))},+ )+++class MissingModuleExtractionTests(unittest.TestCase):+ def test_extracts_module_name_from_message(self) -> None:+ proc = _make_proc()+ name = proc._extract_missing_module({"message": "No module named 'PIL'"})+ self.assertEqual(name, "PIL")++ def test_extracts_module_name_from_traceback(self) -> None:+ proc = _make_proc()+ name = proc._extract_missing_module(+ {"message": "boom", "traceback": "...\nModuleNotFoundError: No module named \"numpy\"\n"}+ )+ self.assertEqual(name, "numpy")++ def test_returns_none_when_no_missing_module(self) -> None:+ proc = _make_proc()+ self.assertIsNone(proc._extract_missing_module({"message": "some other error"}))+++class AutoRepairPackageTests(unittest.TestCase):+ """Safety: only known modules map to a package; never guess arbitrary names."""++ def test_maps_known_module_to_package(self) -> None:+ proc = _make_proc()+ self.assertEqual(proc._resolve_auto_repair_package("PIL"), "Pillow")++ def test_maps_known_module_via_root_package(self) -> None:+ proc = _make_proc()+ self.assertEqual(proc._resolve_auto_repair_package("PIL.Image"), "Pillow")++ def test_returns_none_for_unknown_module(self) -> None:+ proc = _make_proc()+ self.assertIsNone(proc._resolve_auto_repair_package("totally_unknown_pkg"))+++class StderrDecodingTests(unittest.TestCase):+ """tqdm draws partial blocks with U+258D/U+258F, whose UTF-8 bytes are+ undefined in cp1252. Decoding the child's pipes with the locale codec killed+ _stderr_loop mid-run; nothing then drained stderr and the child blocked+ forever on write once the pipe filled (a 3D generation froze at 80%)."""++ def test_tqdm_partial_blocks_survive_the_loop(self) -> None:+ proc = _make_proc()+ bar = "Volume Decoding: 1%|█▍▏| 123/13827\r"+ fake_proc = type("FakeProc", (), {"stderr": io.StringIO(bar)})()++ proc._stderr_loop(fake_proc) # must not raise++ def test_child_is_told_to_write_utf8(self) -> None:+ proc = _make_proc()+ self.assertEqual(proc._build_env().get("PYTHONIOENCODING"), "utf-8")+++class RecvTests(unittest.TestCase):+ def test_returns_message_from_queue(self) -> None:+ proc = _make_proc()+ proc._queue.put({"type": "ready"})+ self.assertEqual(proc._recv(timeout=1.0), {"type": "ready"})++ def test_none_sentinel_raises_runtime_error(self) -> None:+ proc = _make_proc()+ proc._queue.put(None)+ with self.assertRaises(RuntimeError):+ proc._recv(timeout=1.0)++ def test_empty_queue_raises_timeout_error(self) -> None:+ proc = _make_proc()+ with self.assertRaises(TimeoutError):+ proc._recv(timeout=0.05)+++class GenerateErrorLoadedFlagTests(unittest.TestCase):+ """+ Issue #239: a generation that fails during lazy texture setup leaves the+ worker without a model. If _loaded stays True, GeneratorRegistry.get_active()+ skips load() forever and every later run reuses the broken worker.+ """++ def _failing_generate(self, error_msg: dict) -> ExtensionProcess:+ proc = _make_proc()+ proc._loaded = True+ proc._send = lambda msg: None # type: ignore[assignment]+ proc._queue.put(error_msg)+ with self.assertRaises(RuntimeError):+ proc.generate(b"", {})+ return proc++ def test_clears_loaded_when_worker_reports_model_lost(self) -> None:+ proc = self._failing_generate(+ {"type": "error", "message": "No module named 'xatlas'", "loaded": False}+ )+ self.assertFalse(proc._loaded)++ def test_keeps_loaded_when_worker_still_has_its_model(self) -> None:+ proc = self._failing_generate(+ {"type": "error", "message": "bad input image", "loaded": True}+ )+ self.assertTrue(proc._loaded)++ def test_keeps_loaded_when_worker_reports_no_state(self) -> None:+ proc = self._failing_generate({"type": "error", "message": "boom"})+ self.assertTrue(proc._loaded)++ def test_error_still_propagates_the_original_cause(self) -> None:+ proc = _make_proc()+ proc._loaded = True+ proc._send = lambda msg: None # type: ignore[assignment]+ proc._queue.put(+ {"type": "error", "message": "short", "traceback": "full traceback here",+ "loaded": False}+ )+ with self.assertRaises(RuntimeError) as ctx:+ proc.generate(b"", {})+ self.assertIn("full traceback here", str(ctx.exception))+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_extensions_router.py b/apps/forge-desktop/api/tests/test_extensions_router.pynew file mode 100644index 000000000..8eae631d8--- /dev/null+++ b/apps/forge-desktop/api/tests/test_extensions_router.py@@ -0,0 +1,60 @@+import asyncio+import unittest++import services.generator_registry as registry_module+from routers.extensions import reload_extensions+++class _FakeRegistry:+ def __init__(self) -> None:+ self._generators = {"healthy/generate": object()}+ self.reload_calls: list[object] = []++ def reload(self, validation_capability: object = None) -> None:+ self.reload_calls.append(validation_capability)++ def load_errors(self) -> dict[str, str]:+ return {"pending/generate": "quarantined"}+++class ExtensionReloadRouteTests(unittest.TestCase):+ def setUp(self) -> None:+ self.previous_registry = registry_module.generator_registry+ self.registry = _FakeRegistry()+ registry_module.generator_registry = self.registry++ def tearDown(self) -> None:+ registry_module.generator_registry = self.previous_registry++ def test_predictable_extension_id_is_ignored_and_response_shape_is_stable(self) -> None:+ response = asyncio.run(reload_extensions({+ "validatingExtensionId": "pending",+ }))++ self.assertEqual(self.registry.reload_calls, [None])+ self.assertEqual(+ response,+ {+ "reloaded": True,+ "models": ["healthy/generate"],+ "errors": {"pending/generate": "quarantined"},+ },+ )++ def test_only_nested_validation_capability_is_forwarded(self) -> None:+ capability = {+ "extensionId": "pending",+ "destinationName": "pending",+ "stateName": ".modly-registration-pending-pending-100",+ "token": "t" * 43,+ }++ asyncio.run(reload_extensions({+ "validationCapability": capability,+ }))++ self.assertEqual(self.registry.reload_calls, [capability])+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_generation_router.py b/apps/forge-desktop/api/tests/test_generation_router.pynew file mode 100644index 000000000..3d69118c7--- /dev/null+++ b/apps/forge-desktop/api/tests/test_generation_router.py@@ -0,0 +1,174 @@+import asyncio+import tempfile+import threading+import unittest+from pathlib import Path++from fastapi import BackgroundTasks++import services.generator_registry as registry+import routers.generation as generation+from schemas.generation import JobStatus+++class _FakeGenerator:+ """Writes its output into whatever directory generation assigns it."""++ def __init__(self) -> None:+ self.outputs_dir: Path | None = None++ def generate(self, image_bytes, params, progress_cb, cancel_event=None) -> Path:+ out = Path(self.outputs_dir) / "model.glb"+ out.write_bytes(b"glb")+ return out+++class _FakeUpload:+ """Minimal UploadFile stand-in: an image content-type and readable bytes."""++ def __init__(self, content_type: str = "image/png", data: bytes = b"\x89PNG\r\n") -> None:+ self.content_type = content_type+ self._data = data++ async def read(self) -> bytes:+ return self._data+++class _FakeRegistry:+ def __init__(self, gen: _FakeGenerator) -> None:+ self._gen = gen++ def active_status(self) -> dict:+ # Report loaded so _run_generation skips the download/load thread.+ return {"loaded": True, "name": "fake", "downloaded": True}++ def assert_weight_variant_installed(self, params: dict, model_id=None) -> None:+ pass++ def get_active(self) -> _FakeGenerator:+ return self._gen++ # generate_from_image looks the model up and switches to it before filing the job.+ def get_generator(self, model_id: str) -> _FakeGenerator:+ return self._gen++ def get_manifest(self, model_id: str) -> dict:+ return {"output": "mesh"}++ def switch_model(self, model_id: str) -> None:+ pass+++class RunGenerationWorkspaceTests(unittest.TestCase):+ """A generation started after the workspace path is relocated at runtime+ (POST /settings/paths) must file its output under the *current* workspace,+ not the one captured when the module was imported."""++ def setUp(self) -> None:+ self._prev_registry = generation.generator_registry+ self._prev_ws = registry.WORKSPACE_DIR+ self._tmp = tempfile.TemporaryDirectory()+ # The user relocated the workspace: the registry global now points here.+ registry.WORKSPACE_DIR = Path(self._tmp.name) / "new_workspace"+ # Keep the test hermetic against the module's import-time binding: if the+ # stale name still exists (before the fix) redirect it into the temp tree+ # so the assertion — not a stray write to the real workspace — is what+ # catches the bug.+ self._had_stale = hasattr(generation, "WORKSPACE_DIR")+ if self._had_stale:+ generation.WORKSPACE_DIR = Path(self._tmp.name) / "old_workspace"++ def tearDown(self) -> None:+ generation.generator_registry = self._prev_registry+ registry.WORKSPACE_DIR = self._prev_ws+ if self._had_stale:+ generation.WORKSPACE_DIR = self._prev_ws+ for store in (+ generation._jobs,+ generation._cancel_events,+ generation._cancelled,+ generation._completed_at,+ ):+ store.clear()+ self._tmp.cleanup()++ def _run(self, collection: str) -> tuple[_FakeGenerator, JobStatus]:+ gen = _FakeGenerator()+ generation.generator_registry = _FakeRegistry(gen)+ job_id = "job-test"+ generation._jobs[job_id] = JobStatus(job_id=job_id, status="pending", progress=0)+ generation._cancel_events[job_id] = threading.Event()+ asyncio.run(generation._run_generation(job_id, b"img", {}, collection))+ return gen, generation._jobs[job_id]++ def test_output_lands_under_the_current_workspace(self) -> None:+ gen, job = self._run("MyColl")+ self.assertEqual(Path(gen.outputs_dir), registry.WORKSPACE_DIR / "MyColl")+ self.assertEqual(job.status, "done")+ self.assertEqual(job.output_url, "/workspace/MyColl/model.glb")++ def test_missing_weight_variant_fails_the_job_before_generation(self) -> None:+ class _MissingVariantRegistry(_FakeRegistry):+ def assert_weight_variant_installed(self, params: dict, model_id=None) -> None:+ raise RuntimeError(f'{params["gguf_quant"]} weights for trellis2/generate are not installed.')++ gen = _FakeGenerator()+ generation.generator_registry = _MissingVariantRegistry(gen)+ job_id = "job-missing-variant"+ generation._jobs[job_id] = JobStatus(job_id=job_id, status="pending", progress=0)+ generation._cancel_events[job_id] = threading.Event()+ asyncio.run(generation._run_generation(job_id, b"img", {"gguf_quant": "Q6_K"}, "MyColl"))++ job = generation._jobs[job_id]+ self.assertEqual(job.status, "error")+ self.assertIn("Q6_K weights for trellis2/generate are not installed", job.error)+ self.assertIsNone(gen.outputs_dir)+++class GenerateFromImageWorkspaceTests(unittest.TestCase):+ """The request path must survive the relocation too, not just the worker:+ sanitize_collection() checks the name's containment against the workspace+ root before the job is filed, so it has to read the same live binding -- a+ stale (or missing) module-level name there fails every POST+ /generate/from-image, whatever _run_generation does afterwards."""++ def setUp(self) -> None:+ self._prev_registry = generation.generator_registry+ self._prev_ws = registry.WORKSPACE_DIR+ self._tmp = tempfile.TemporaryDirectory()+ registry.WORKSPACE_DIR = Path(self._tmp.name) / "new_workspace"+ generation.generator_registry = _FakeRegistry(_FakeGenerator())++ def tearDown(self) -> None:+ generation.generator_registry = self._prev_registry+ registry.WORKSPACE_DIR = self._prev_ws+ for store in (+ generation._jobs,+ generation._cancel_events,+ generation._cancelled,+ generation._completed_at,+ ):+ store.clear()+ self._tmp.cleanup()++ def test_request_is_filed_after_the_workspace_moves(self) -> None:+ background = BackgroundTasks()+ response = asyncio.run(+ generation.generate_from_image(+ background,+ image=_FakeUpload(),+ model_id="sf3d",+ collection="MyColl",+ remesh="quad",+ enable_texture=False,+ texture_resolution=1024,+ params="{}",+ )+ )+ self.assertIn(response["job_id"], generation._jobs)+ # add_task(_run_generation, job_id, image_bytes, full_params, collection)+ self.assertEqual(background.tasks[0].args[3], "MyColl")+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_generator_registry.py b/apps/forge-desktop/api/tests/test_generator_registry.pynew file mode 100644index 000000000..b21253b7c--- /dev/null+++ b/apps/forge-desktop/api/tests/test_generator_registry.py@@ -0,0 +1,896 @@+import json+import importlib+import inspect+import os+import sys+import tempfile+import threading+import unittest+from pathlib import Path++import services.generator_registry as registry_module+from services.extension_process import ExtensionProcess+from services.generator_registry import GeneratorRegistry+++class GeneratorRegistryDiscoveryTests(unittest.TestCase):+ def setUp(self) -> None:+ self._tempdir = tempfile.TemporaryDirectory(prefix="modly-registry-test-")+ self.root = Path(self._tempdir.name)+ self.extensions_dir = self.root / "extensions"+ self.models_dir = self.root / "models"+ self.workspace_dir = self.root / "workspace"+ self.extensions_dir.mkdir()+ self.models_dir.mkdir()+ self.workspace_dir.mkdir()++ self._old_extensions_dir = registry_module.EXTENSIONS_DIR+ self._old_models_dir = registry_module.MODELS_DIR+ self._old_workspace_dir = registry_module.WORKSPACE_DIR+ registry_module.EXTENSIONS_DIR = self.extensions_dir+ registry_module.MODELS_DIR = self.models_dir+ registry_module.WORKSPACE_DIR = self.workspace_dir+ self.registry = GeneratorRegistry()++ def tearDown(self) -> None:+ self.registry._remove_legacy_paths()+ registry_module.EXTENSIONS_DIR = self._old_extensions_dir+ registry_module.MODELS_DIR = self._old_models_dir+ registry_module.WORKSPACE_DIR = self._old_workspace_dir+ for module_name in [+ "registry_eager_helper",+ "registry_lazy_helper",+ "extensions.class-failure.generator",+ "extensions.host-owned-path.generator",+ "extensions.legacy-imports.generator",+ ]:+ sys.modules.pop(module_name, None)+ self._tempdir.cleanup()++ def _write_manifest(+ self,+ directory: Path,+ *,+ extension_id: str,+ extension_type: str = "model",+ node_ids: tuple[str, ...] = ("generate",),+ ) -> None:+ manifest = {+ "id": extension_id,+ "name": extension_id,+ "type": extension_type,+ "nodes": [{"id": node_id} for node_id in node_ids],+ }+ if extension_type == "model":+ manifest["generator_class"] = "TestGenerator"+ else:+ manifest["entry"] = "processor.py"+ (directory / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")++ def _make_extension(self, extension_id: str) -> Path:+ directory = self.extensions_dir / extension_id+ directory.mkdir()+ return directory++ def _write_registration_capability(+ self,+ extension_id: str,+ *,+ suffix: str = "100",+ token: str = "t" * 43,+ ) -> dict[str, str]:+ state_name = (+ f".modly-registration-pending-{extension_id}-{suffix}"+ )+ state_path = self.extensions_dir / state_name+ state_path.write_text(+ json.dumps({+ "version": 1,+ "extensionId": extension_id,+ "destinationName": extension_id,+ "token": token,+ "consumed": False,+ }),+ encoding="utf-8",+ )+ state_path.chmod(0o600)+ return {+ "extensionId": extension_id,+ "destinationName": extension_id,+ "stateName": state_name,+ "token": token,+ }++ def _make_loadable_pending_extension(self, extension_id: str) -> dict[str, str]:+ extension = self._make_extension(extension_id)+ self._write_manifest(extension, extension_id=extension_id)+ (extension / "generator.py").write_text(+ "\n".join(+ [+ "from services.generators.base import BaseGenerator",+ "class TestGenerator(BaseGenerator):",+ " def load(self): pass",+ " def generate(self, image_bytes, params, progress_cb=None, cancel_event=None):",+ " return self.outputs_dir / 'result.glb'",+ ]+ ),+ encoding="utf-8",+ )+ return self._write_registration_capability(extension_id)++ def test_legacy_generator_supports_eager_and_lazy_sibling_imports(self) -> None:+ extension = self._make_extension("legacy-imports")+ self._write_manifest(extension, extension_id="legacy-imports")+ (extension / "registry_eager_helper.py").write_text("VALUE = 'eager'\n", encoding="utf-8")+ (extension / "registry_lazy_helper.py").write_text("VALUE = 'lazy'\n", encoding="utf-8")+ (extension / "generator.py").write_text(+ "\n".join(+ [+ "from services.generators.base import BaseGenerator",+ "from registry_eager_helper import VALUE as EAGER_VALUE",+ "",+ "class TestGenerator(BaseGenerator):",+ " def load(self):",+ " self._model = object()",+ "",+ " def generate(self, image_bytes, params, progress_cb=None, cancel_event=None):",+ " return self.outputs_dir / 'result.glb'",+ "",+ " def sibling_values(self):",+ " from registry_lazy_helper import VALUE as lazy_value",+ " return EAGER_VALUE, lazy_value",+ ]+ ),+ encoding="utf-8",+ )++ self.registry.initialize()++ generator = self.registry.get_generator("legacy-imports/generate")+ self.assertEqual(generator.sibling_values(), ("eager", "lazy"))+ self.assertNotIn(str(extension.resolve()), sys.path)+ self.assertIn("cancel_event", inspect.signature(generator.generate).parameters)++ registry_module.EXTENSIONS_DIR = self.root / "empty-extensions"+ registry_module.EXTENSIONS_DIR.mkdir()+ self.registry.reload()+ self.assertNotIn(str(extension.resolve()), sys.path)++ def test_scene_and_existing_custom_io_types_are_registered(self) -> None:+ for extension_id, input_kind in (("scene-io", "scene"), ("capture-io", "capture"), ("video-io", "video")):+ extension = self._make_extension(extension_id)+ manifest = {+ "id": extension_id, "name": extension_id, "type": "model",+ "generator_class": "TestGenerator",+ "nodes": [{"id": "generate", "input": input_kind, "output": "scene"}],+ }+ (extension / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")+ (extension / "generator.py").write_text(+ "from services.generators.base import BaseGenerator\n"+ "class TestGenerator(BaseGenerator):\n"+ " def load(self): self._model = object()\n"+ " def generate(self, value, params, progress_cb=None, cancel_event=None): return self.outputs_dir\n",+ encoding="utf-8",+ )++ self.registry.initialize()+ self.assertEqual(self.registry.get_manifest("scene-io/generate")["input"], "scene")+ self.assertEqual(self.registry.get_manifest("capture-io/generate")["input"], "capture")+ self.assertEqual(self.registry.get_manifest("video-io/generate")["input"], "video")++ def test_scene_input_rejects_multi_input_shapes_but_image_multi_can_output_scene(self) -> None:+ cases = {+ "scene-mixed": {"input": "scene", "inputs": ["scene", "text"], "output": "mesh"},+ "scene-array": {"input": "scene", "inputs": ["scene"], "output": "mesh"},+ "images-scene": {"input": "image", "inputs": ["image", "image"], "output": "scene"},+ }+ for extension_id, node in cases.items():+ extension = self._make_extension(extension_id)+ (extension / "manifest.json").write_text(json.dumps({+ "id": extension_id, "name": extension_id, "type": "model",+ "generator_class": "TestGenerator",+ "nodes": [{"id": "generate", **node}],+ }), encoding="utf-8")+ (extension / "generator.py").write_text(+ "from services.generators.base import BaseGenerator\n"+ "class TestGenerator(BaseGenerator):\n"+ " def load(self): self._model = object()\n"+ " def generate(self, value, params, progress_cb=None, cancel_event=None): return self.outputs_dir\n",+ encoding="utf-8",+ )+ self.registry.initialize()+ self.assertIn("scene-mixed/generate", self.registry.load_errors())+ self.assertIn("scene-array/generate", self.registry.load_errors())+ self.assertIn("images-scene/generate", self.registry._generators)++ def test_declared_sources_block_generation_even_when_generator_overrides_readiness(self) -> None:+ extension = self._make_extension("multi-source")+ manifest = {+ "id": "multi-source",+ "name": "multi-source",+ "type": "model",+ "generator_class": "TestGenerator",+ "nodes": [{+ "id": "generate",+ "model_sources": [+ {+ "id": "primary",+ "provider": "huggingface",+ "repo_id": "org/main",+ "destination": ".",+ "checks": ["main.bin"],+ },+ {+ "id": "encoder",+ "provider": "huggingface",+ "repo_id": "org/encoder",+ "destination": "auxiliary/encoder",+ "checks": ["encoder.bin"],+ },+ ],+ }],+ }+ (extension / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")+ (extension / "generator.py").write_text(+ "\n".join([+ "from services.generators.base import BaseGenerator",+ "class TestGenerator(BaseGenerator):",+ " def is_downloaded(self): return True",+ " def load(self): self._model = object()",+ " def generate(self, image_bytes, params, progress_cb=None, cancel_event=None):",+ " return self.outputs_dir / 'result.glb'",+ ]),+ encoding="utf-8",+ )++ self.registry.initialize()+ self.registry._active_id = "multi-source/generate"+ with self.assertRaisesRegex(RuntimeError, "Model sources are incomplete"):+ self.registry.get_active()+ self.assertFalse(self.registry.all_status()[0]["downloaded"])++ model_root = self.models_dir / "multi-source" / "generate"+ (model_root / "auxiliary" / "encoder").mkdir(parents=True)+ (model_root / "main.bin").write_bytes(b"main")+ (model_root / "auxiliary" / "encoder" / "encoder.bin").write_bytes(b"encoder")+ self.assertIsNotNone(self.registry.get_active())+ self.assertTrue(self.registry.all_status()[0]["downloaded"])+ (model_root / "main.bin").unlink()+ with self.assertRaisesRegex(RuntimeError, "Model sources are incomplete"):+ self.registry.get_active()++ def test_shared_groups_gate_all_dependents_and_keep_private_dirs_separate(self) -> None:+ extension = self._make_extension("shared-model")+ manifest = {+ "id": "shared-model",+ "name": "shared-model",+ "type": "model",+ "generator_class": "TestGenerator",+ "weight_groups": [{+ "id": "base",+ "model_sources": [{+ "id": "base",+ "provider": "huggingface",+ "repo_id": "org/base",+ "destination": ".",+ "checks": ["base.bin"],+ }],+ }],+ "nodes": [+ {"id": "generate", "weight_groups": ["base"]},+ {+ "id": "adapter",+ "weight_groups": ["base"],+ "model_sources": [{+ "id": "adapter",+ "provider": "huggingface",+ "repo_id": "org/adapter",+ "destination": ".",+ "checks": ["adapter.bin"],+ }],+ },+ ],+ }+ (extension / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")+ (extension / "generator.py").write_text(+ "\n".join([+ "from services.generators.base import BaseGenerator",+ "class TestGenerator(BaseGenerator):",+ " def load(self): self._model = object()",+ " def generate(self, image_bytes, params, progress_cb=None, cancel_event=None):",+ " return self.outputs_dir / 'result.glb'",+ ]),+ encoding="utf-8",+ )++ self.registry.initialize()+ base_root = self.models_dir / "shared-model" / "_shared" / "base"+ generate = self.registry.get_generator("shared-model/generate")+ adapter = self.registry.get_generator("shared-model/adapter")+ self.assertEqual(generate.shared_model_dirs, {"base": base_root})+ self.assertEqual(adapter.shared_model_dirs, {"base": base_root})+ self.assertEqual(generate.MODEL_ID, "shared-model/generate")+ self.assertEqual(generate.MODEL_NODE_ID, "generate")+ self.assertEqual(adapter.MODEL_ID, "shared-model/adapter")+ self.assertEqual(adapter.MODEL_NODE_ID, "adapter")+ self.assertFalse(self.registry._is_downloaded("shared-model/generate", generate))+ self.assertFalse(self.registry._is_downloaded("shared-model/adapter", adapter))++ base_root.mkdir(parents=True)+ (base_root / "base.bin").write_bytes(b"base")+ self.assertTrue(self.registry._is_downloaded("shared-model/generate", generate))+ self.assertFalse(self.registry._is_downloaded("shared-model/adapter", adapter))++ private_root = self.models_dir / "shared-model" / "adapter"+ private_root.mkdir(parents=True)+ (private_root / "adapter.bin").write_bytes(b"adapter")+ self.assertTrue(self.registry._is_downloaded("shared-model/adapter", adapter))+ relocated = self.root / "relocated-models"+ self.registry.update_paths(relocated, None)+ self.assertEqual(adapter.model_dir, relocated / "shared-model/adapter")+ self.assertEqual(adapter.shared_model_dirs, {"base": relocated / "shared-model/_shared/base"})+ self.assertEqual(adapter.MODEL_NODE_ID, "adapter")+ self.assertFalse(self.registry._is_downloaded("shared-model/adapter", adapter))++ def test_selected_weight_variant_must_be_installed_before_generation(self) -> None:+ def variant(quant: str) -> dict:+ return {+ "id": quant,+ "include_prefixes": [f"dit_{quant}.gguf"],+ "checks": [f"dit_{quant}.gguf"],+ }++ extension = self._make_extension("quantized")+ manifest = {+ "id": "quantized",+ "name": "quantized",+ "type": "model",+ "generator_class": "TestGenerator",+ "params_schema": [+ {"id": "quant", "type": "select", "options": [{"value": "Q4"}, {"value": "Q5"}]}+ ],+ "nodes": [{+ "id": "generate",+ "hf_repo": "org/model-gguf",+ "download_check": "pipeline.json",+ "weight_variants": {+ "param": "quant",+ "default": "Q5",+ "options": [variant("Q4"), variant("Q5")],+ },+ }],+ }+ (extension / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")+ (extension / "generator.py").write_text(+ "\n".join([+ "from services.generators.base import BaseGenerator",+ "class TestGenerator(BaseGenerator):",+ " def is_downloaded(self): return True",+ " def load(self): self._model = object()",+ " def generate(self, image_bytes, params, progress_cb=None, cancel_event=None):",+ " return self.outputs_dir / 'result.glb'",+ ]),+ encoding="utf-8",+ )++ self.registry.initialize()+ manifest_variants = self.registry.get_manifest("quantized/generate")["weight_variants"]+ self.assertEqual([option["id"] for option in manifest_variants["options"]], ["Q4", "Q5"])++ model_root = self.models_dir / "quantized" / "generate"+ model_root.mkdir(parents=True)+ (model_root / "dit_Q5.gguf").write_bytes(b"q5")+ # The job's model is checked, not whichever model is still active: the+ # switch to the job's model only happens once the job starts running.+ self.registry._active_id = "other/generate"+ model_id = "quantized/generate"+ self.registry.assert_weight_variant_installed({}, model_id)+ self.registry.assert_weight_variant_installed({"quant": "Q5"}, model_id)+ self.registry.assert_weight_variant_installed({"quant": "fp16"}, model_id)+ with self.assertRaisesRegex(RuntimeError, "Q4 weights for quantized/generate are not installed"):+ self.registry.assert_weight_variant_installed({"quant": "Q4"}, model_id)++ # Without an explicit model id the active one is used (legacy callers).+ self.registry._active_id = model_id+ with self.assertRaisesRegex(RuntimeError, "Q4 weights"):+ self.registry.assert_weight_variant_installed({"quant": "Q4"})+++ def test_activate_ready_generator_switches_before_loading_exact_model(self) -> None:+ class Generator:+ DISPLAY_NAME = "test"+ def __init__(self):+ self.loaded = False+ self.unloads = 0+ def is_downloaded(self): return True+ def is_loaded(self): return self.loaded+ def load(self): self.loaded = True+ def unload(self):+ self.loaded = False+ self.unloads += 1++ first = Generator()+ second = Generator()+ first.loaded = True+ self.registry._generators = {"demo/a": first, "demo/b": second}+ self.registry._manifests = {+ "demo/a": {"name": "A"},+ "demo/b": {"name": "B"},+ }+ self.registry._active_id = "demo/a"++ selected = self.registry.activate_ready_generator("demo/b")++ self.assertIs(selected, second)+ self.assertEqual(self.registry._active_id, "demo/b")+ self.assertFalse(first.loaded)+ self.assertEqual(first.unloads, 1)+ self.assertTrue(second.loaded)++ def test_reload_preserves_legacy_path_owned_by_the_host(self) -> None:+ extension = self._make_extension("host-owned-path")+ self._write_manifest(extension, extension_id="host-owned-path")+ (extension / "generator.py").write_text(+ "\n".join(+ [+ "from services.generators.base import BaseGenerator",+ "class TestGenerator(BaseGenerator):",+ " def load(self): pass",+ " def generate(self, image_bytes, params, progress_cb=None, cancel_event=None):",+ " return self.outputs_dir / 'result.glb'",+ ]+ ),+ encoding="utf-8",+ )+ host_path = str(extension.resolve())+ sys.path.insert(0, host_path)+ try:+ self.registry.initialize()+ registry_module.EXTENSIONS_DIR = self.root / "empty-host-owned"+ registry_module.EXTENSIONS_DIR.mkdir()+ self.registry.reload()+ self.assertIn(host_path, sys.path)+ finally:+ sys.path.remove(host_path)++ def test_reload_stops_subprocess_runtime_instead_of_only_unloading_model(self) -> None:+ process = ExtensionProcess(+ self.extensions_dir / "subprocess-runtime",+ {"id": "subprocess-runtime"},+ )+ calls: list[str] = []+ process.stop = lambda: calls.append("stop") # type: ignore[method-assign]+ process.unload = lambda: calls.append("unload") # type: ignore[method-assign]+ self.registry._generators["subprocess-runtime/generate"] = process++ self.registry.reload()++ self.assertEqual(calls, ["stop"])++ def test_reload_evicts_owned_helper_modules_and_reads_updated_source(self) -> None:+ extension = self._make_extension("reload-helper")+ self._write_manifest(extension, extension_id="reload-helper")+ helper_path = extension / "reload_owned_helper.py"+ helper_path.write_text("VALUE = 1\n", encoding="utf-8")+ (extension / "generator.py").write_text(+ "\n".join(+ [+ "from services.generators.base import BaseGenerator",+ "class TestGenerator(BaseGenerator):",+ " def load(self): pass",+ " def generate(self, image_bytes, params, progress_cb=None, cancel_event=None):",+ " return self.outputs_dir / 'result.glb'",+ " def helper_value(self):",+ " import reload_owned_helper",+ " return reload_owned_helper.VALUE",+ ]+ ),+ encoding="utf-8",+ )++ self.registry.initialize()+ self.assertEqual(+ self.registry.get_generator("reload-helper/generate").helper_value(),+ 1,+ )++ # Same-size edit in the same timestamp window exercises stale .pyc and+ # sys.modules eviction rather than relying on filesystem mtime changes.+ helper_path.write_text("VALUE = 2\n", encoding="utf-8")+ self.registry.reload()++ self.assertEqual(+ self.registry.get_generator("reload-helper/generate").helper_value(),+ 2,+ )+ self.assertNotIn("reload_owned_helper", sys.modules)++ def test_legacy_extensions_with_same_helper_name_remain_isolated(self) -> None:+ for extension_id, value in (("collision-a", "alpha"), ("collision-b", "beta")):+ extension = self._make_extension(extension_id)+ self._write_manifest(extension, extension_id=extension_id)+ (extension / "shared_collision_helper.py").write_text(+ f"VALUE = {value!r}\n",+ encoding="utf-8",+ )+ (extension / "generator.py").write_text(+ "\n".join(+ [+ "from services.generators.base import BaseGenerator",+ "class TestGenerator(BaseGenerator):",+ " def load(self): pass",+ " def generate(self, image_bytes, params, progress_cb=None, cancel_event=None):",+ " return self.outputs_dir / 'result.glb'",+ " def helper_value(self):",+ " import shared_collision_helper",+ " return shared_collision_helper.VALUE",+ ]+ ),+ encoding="utf-8",+ )++ self.registry.initialize()+ first = self.registry.get_generator("collision-a/generate")+ second = self.registry.get_generator("collision-b/generate")++ self.assertEqual(first.helper_value(), "alpha")+ self.assertEqual(second.helper_value(), "beta")+ self.assertEqual(first.helper_value(), "alpha")+ self.assertNotIn("shared_collision_helper", sys.modules)+ with self.assertRaises(ModuleNotFoundError):+ importlib.import_module("shared_collision_helper")++ def test_setup_script_without_platform_venv_surfaces_repair_error_per_node(self) -> None:+ extension = self._make_extension("needs-setup")+ self._write_manifest(+ extension,+ extension_id="needs-setup",+ node_ids=("fast", "quality"),+ )+ (extension / "setup.py").write_text("raise SystemExit('must not run in registry')\n", encoding="utf-8")+ (extension / "generator.py").write_text(+ "raise AssertionError('generator.py must not be imported before setup')\n",+ encoding="utf-8",+ )++ self.registry.initialize()++ self.assertEqual(self.registry._generators, {})+ errors = self.registry.load_errors()+ self.assertEqual(set(errors), {"needs-setup/fast", "needs-setup/quality"})+ self.assertTrue(all("Repair" in message and "venv not found" in message for message in errors.values()))++ def test_discovery_failures_remain_visible_under_actionable_keys(self) -> None:+ missing_manifest = self._make_extension("missing-manifest")+ (missing_manifest / "generator.py").write_text("", encoding="utf-8")++ invalid_manifest = self._make_extension("invalid-manifest")+ (invalid_manifest / "manifest.json").write_text("{invalid", encoding="utf-8")++ non_object_manifest = self._make_extension("non-object-manifest")+ (non_object_manifest / "manifest.json").write_text("[]", encoding="utf-8")++ missing_generator = self._make_extension("missing-generator")+ self._write_manifest(missing_generator, extension_id="missing-generator")++ import_failure = self._make_extension("import-failure")+ self._write_manifest(import_failure, extension_id="import-failure")+ (import_failure / "generator.py").write_text(+ "raise RuntimeError('intentional discovery failure')\n",+ encoding="utf-8",+ )++ class_failure = self._make_extension("class-failure")+ self._write_manifest(class_failure, extension_id="class-failure")+ (class_failure / "generator.py").write_text(+ "class DifferentGenerator:\n pass\n",+ encoding="utf-8",+ )++ self.registry.initialize()++ errors = self.registry.load_errors()+ self.assertIn("missing-manifest", errors)+ self.assertIn("invalid-manifest", errors)+ self.assertIn("non-object-manifest", errors)+ self.assertIn("missing-generator/generate", errors)+ self.assertIn("import-failure/generate", errors)+ self.assertIn("class-failure/generate", errors)+ self.assertIn("missing manifest.json", errors["missing-manifest"])+ self.assertIn("invalid manifest.json", errors["invalid-manifest"])+ self.assertIn("expected an object", errors["non-object-manifest"])+ self.assertIn("missing generator.py", errors["missing-generator/generate"])+ self.assertIn("intentional discovery failure", errors["import-failure/generate"])+ self.assertIn("TestGenerator", errors["class-failure/generate"])++ def test_incomplete_model_install_is_reported_for_each_node(self) -> None:+ extension = self._make_extension("interrupted")+ self._write_manifest(extension, extension_id="interrupted", node_ids=("one", "two"))+ (extension / "generator.py").write_text("", encoding="utf-8")+ (extension / ".modly-incomplete").write_text("installing", encoding="utf-8")++ self.registry.initialize()++ errors = self.registry.load_errors()+ self.assertEqual(set(errors), {"interrupted/one", "interrupted/two"})+ self.assertTrue(all("incomplete installation" in message for message in errors.values()))++ def test_pending_registration_is_not_loaded_when_startup_restore_cannot_finish(self) -> None:+ extension = self._make_extension("pending-registration")+ self._write_manifest(extension, extension_id="pending-registration")+ (extension / "generator.py").write_text(+ "class TestGenerator:\n"+ " def __init__(self, *args, **kwargs):\n"+ " raise AssertionError('pending extension must not be loaded')\n",+ encoding="utf-8",+ )+ (self.extensions_dir / ".modly-registration-pending-pending-registration-100").write_text(+ "validating",+ encoding="utf-8",+ )++ self.registry.initialize()++ errors = self.registry.load_errors()+ self.assertEqual(set(errors), {"pending-registration/generate"})+ self.assertIn("interrupted runtime registration", next(iter(errors.values())))++ def test_pending_sidecar_blocks_generators_that_were_already_loaded(self) -> None:+ extension = self._make_extension("live-before-repair")+ self._write_manifest(extension, extension_id="live-before-repair")+ (extension / "generator.py").write_text(+ "\n".join(+ [+ "from services.generators.base import BaseGenerator",+ "class TestGenerator(BaseGenerator):",+ " def load(self): pass",+ " def generate(self, image_bytes, params, progress_cb=None, cancel_event=None):",+ " return self.outputs_dir / 'result.glb'",+ ]+ ),+ encoding="utf-8",+ )+ self.registry.initialize()+ model_id = "live-before-repair/generate"+ self.assertIn(model_id, self.registry._generators)++ self._write_registration_capability("live-before-repair")++ with self.assertRaisesRegex(ValueError, "pending runtime registration"):+ self.registry.get_generator(model_id)+ with self.assertRaisesRegex(ValueError, "pending runtime registration"):+ self.registry.switch_model(model_id)+ with self.assertRaisesRegex(ValueError, "pending runtime registration"):+ self.registry.get_active()++ def test_valid_capability_authorizes_exact_pending_extension_once(self) -> None:+ capability = self._make_loadable_pending_extension("pending-update")++ self.registry.reload(capability)+ self.assertIn("pending-update/generate", self.registry._generators)+ self.assertEqual(self.registry.load_errors(), {})+ consumed = json.loads(+ (self.extensions_dir / capability["stateName"]).read_text(encoding="utf-8")+ )+ self.assertEqual(+ consumed,+ {+ "version": 1,+ "extensionId": "pending-update",+ "destinationName": "pending-update",+ "consumed": True,+ },+ )++ self.registry.reload(capability)+ self.assertNotIn("pending-update/generate", self.registry._generators)+ self.assertIn("pending-update/generate", self.registry.load_errors())++ @unittest.skipUnless(sys.platform == "win32", "8.3 short paths are Windows-only")+ def test_valid_capability_authorizes_extension_under_a_short_path(self) -> None:+ # GitHub's Windows runners use an 8.3 TEMP (C:\Users\RUNNER~1\...): the+ # capability destination is resolved (long form) while discovery walks+ # the configured, short-form EXTENSIONS_DIR.+ import ctypes++ capability = self._make_loadable_pending_extension("pending-short")+ buffer = ctypes.create_unicode_buffer(32768)+ if not ctypes.windll.kernel32.GetShortPathNameW(str(self.extensions_dir), buffer, len(buffer)):+ self.skipTest("short path unavailable")+ short_dir = Path(buffer.value)+ if str(short_dir) == str(self.extensions_dir):+ self.skipTest("8.3 names are disabled on this volume")+ registry_module.EXTENSIONS_DIR = short_dir++ self.registry.reload(capability)++ self.assertIn("pending-short/generate", self.registry._generators)+ self.assertEqual(self.registry.load_errors(), {})++ def test_public_reload_and_predictable_id_cannot_bypass_pending_state(self) -> None:+ self._make_loadable_pending_extension("pending-public")++ self.registry.reload()+ self.assertNotIn("pending-public/generate", self.registry._generators)+ self.assertIn("pending-public/generate", self.registry.load_errors())++ self.registry.reload({"validatingExtensionId": "pending-public"})+ self.assertNotIn("pending-public/generate", self.registry._generators)+ self.assertIn("pending-public/generate", self.registry.load_errors())++ def test_wrong_capability_token_cannot_bypass_pending_state(self) -> None:+ capability = self._make_loadable_pending_extension("pending-token")+ capability["token"] = "x" * 43++ self.registry.reload(capability)++ self.assertNotIn("pending-token/generate", self.registry._generators)+ self.assertIn("pending-token/generate", self.registry.load_errors())++ def test_capability_id_and_sidecar_path_must_match(self) -> None:+ capability = self._make_loadable_pending_extension("pending-path")+ capability["extensionId"] = "another-extension"++ self.registry.reload(capability)++ self.assertNotIn("pending-path/generate", self.registry._generators)+ self.assertIn("pending-path/generate", self.registry.load_errors())++ def test_capability_destination_folder_must_match(self) -> None:+ capability = self._make_loadable_pending_extension("pending-destination")+ capability["destinationName"] = "another-extension"++ self.registry.reload(capability)++ self.assertNotIn("pending-destination/generate", self.registry._generators)+ self.assertIn("pending-destination/generate", self.registry.load_errors())++ def test_authorization_rejects_duplicate_folder_declaring_same_manifest_id(self) -> None:+ capability = self._make_loadable_pending_extension("pixal3d")+ duplicate = self._make_extension("zzz-duplicate")+ self._write_manifest(duplicate, extension_id="pixal3d")+ (duplicate / "generator.py").write_text(+ "raise AssertionError('mismatched folder must not be imported')\n",+ encoding="utf-8",+ )++ self.registry.reload(capability)++ self.assertIn("pixal3d/generate", self.registry._generators)+ self.assertIn("zzz-duplicate", self.registry.load_errors())+ self.assertIn("must match", self.registry.load_errors()["zzz-duplicate"])++ @unittest.skipIf(os.name == "nt", "POSIX mode bits are not enforced on Windows")+ def test_capability_sidecar_with_group_or_other_permissions_is_rejected(self) -> None:+ capability = self._make_loadable_pending_extension("pending-mode")+ state_path = self.extensions_dir / capability["stateName"]+ state_path.chmod(0o644)++ self.registry.reload(capability)++ self.assertNotIn("pending-mode/generate", self.registry._generators)+ self.assertIn("pending-mode/generate", self.registry.load_errors())++ def test_hard_linked_capability_sidecar_is_rejected(self) -> None:+ capability = self._make_loadable_pending_extension("pending-hardlink")+ state_path = self.extensions_dir / capability["stateName"]+ os.link(state_path, self.extensions_dir / "capability-hardlink-copy")++ self.registry.reload(capability)++ self.assertNotIn("pending-hardlink/generate", self.registry._generators)+ self.assertIn("pending-hardlink/generate", self.registry.load_errors())++ @unittest.skipIf(os.name == "nt", "symlink creation may require privileges on Windows")+ def test_symlinked_capability_sidecar_is_rejected(self) -> None:+ capability = self._make_loadable_pending_extension("pending-symlink")+ state_path = self.extensions_dir / capability["stateName"]+ target = self.extensions_dir / "capability-symlink-target"+ state_path.rename(target)+ state_path.symlink_to(target)++ self.registry.reload(capability)++ self.assertNotIn("pending-symlink/generate", self.registry._generators)+ self.assertIn("pending-symlink/generate", self.registry.load_errors())++ def test_process_extension_is_skipped_without_model_errors(self) -> None:+ extension = self._make_extension("process-only")+ self._write_manifest(+ extension,+ extension_id="process-only",+ extension_type="process",+ )+ (extension / "processor.py").write_text("print('ok')\n", encoding="utf-8")+ (extension / ".modly-incomplete").write_text("installing", encoding="utf-8")++ self.registry.initialize()++ self.assertEqual(self.registry._generators, {})+ self.assertEqual(self.registry.load_errors(), {})+++class _StatusOnlyGenerator:+ DISPLAY_NAME = "Fake"+ VRAM_GB = 1++ def is_downloaded(self) -> bool:+ return True++ def is_loaded(self) -> bool:+ return False++ def params_schema(self) -> list:+ return [{"id": "steps"}]+++class _DirectGenerator:+ def __init__(self, sticky: bool = False) -> None:+ self.loaded = True+ self.sticky = sticky++ def unload(self) -> None:+ if not self.sticky:+ self.loaded = False++ def is_loaded(self) -> bool:+ return self.loaded+++class GeneratorRegistryUnloadTests(unittest.TestCase):+ def test_unload_all_unloads_every_model_before_reporting_a_stuck_one(self):+ registry = GeneratorRegistry()+ stuck = _DirectGenerator(sticky=True)+ other = _DirectGenerator()+ registry._generators = {"demo/stuck": stuck, "demo/other": other}++ with self.assertRaisesRegex(RuntimeError, "demo/stuck"):+ registry.unload_all()++ self.assertFalse(other.loaded)+++class GeneratorRegistryLockTests(unittest.TestCase):+ def test_status_reads_do_not_wait_for_an_in_progress_load(self):+ # A load holds the lifecycle lock for its whole duration (first-run+ # downloads included); status endpoints must keep answering meanwhile.+ registry = GeneratorRegistry()+ registry._generators["demo/generate"] = _StatusOnlyGenerator()+ registry._manifests["demo/generate"] = {"name": "Demo"}+ registry._active_id = "demo/generate"++ lock_held = threading.Event()+ release = threading.Event()++ def hold_lock() -> None:+ with registry._lifecycle_lock:+ lock_held.set()+ release.wait(5)++ holder = threading.Thread(target=hold_lock)+ holder.start()+ self.addCleanup(holder.join)+ self.addCleanup(release.set)+ self.assertTrue(lock_held.wait(5))++ results = {}++ def read_status() -> None:+ results["active"] = registry.active_status()+ results["all"] = registry.all_status()+ results["params"] = registry.params_schema("demo/generate")+ results["model"] = registry.model_status("demo/generate")++ reader = threading.Thread(target=read_status)+ reader.start()+ reader.join(2)++ self.assertFalse(reader.is_alive(), "status reads blocked on the lifecycle lock")+ self.assertEqual(results["active"]["id"], "demo/generate")+ self.assertEqual([m["id"] for m in results["all"]], ["demo/generate"])+ self.assertEqual(results["params"], [{"id": "steps"}])+ self.assertFalse(results["model"]["loaded"])+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_llm_downloads.py b/apps/forge-desktop/api/tests/test_llm_downloads.pynew file mode 100644index 000000000..31d299154--- /dev/null+++ b/apps/forge-desktop/api/tests/test_llm_downloads.py@@ -0,0 +1,121 @@+import hashlib+import importlib+import tempfile+import unittest+from pathlib import Path+from unittest import mock++llm_server = importlib.import_module("services.llm_server")+llm_router = importlib.import_module("routers.llm")++_VISION = {+ "id": "vl",+ "hf_filename": "weights.gguf",+ "hf_mmproj_filename": "mmproj-F16.gguf",+}+++class DiscardIncompleteTests(unittest.TestCase):+ """Cancelling a download has to leave nothing behind. A vision model fetches+ weights then projector, so a cancel during the second one used to leave the+ finished weights on disk under a model still reported `downloaded: false` —+ the UI offers no trash button for those, so the space was unreclaimable."""++ def setUp(self) -> None:+ self._tmp = tempfile.TemporaryDirectory()+ self._orig = llm_server.LLM_MODELS_DIR+ llm_server.LLM_MODELS_DIR = Path(self._tmp.name)++ def tearDown(self) -> None:+ llm_server.LLM_MODELS_DIR = self._orig+ self._tmp.cleanup()++ def _touch(self, name: str) -> Path:+ p = llm_server.LLM_MODELS_DIR / name+ p.write_bytes(b"x")+ return p++ def test_removes_a_part_file(self):+ self._touch("weights.gguf.part")+ removed = llm_router._discard_incomplete(_VISION)+ self.assertEqual(removed, ["weights.gguf.part"])+ self.assertEqual(list(llm_server.LLM_MODELS_DIR.iterdir()), [])++ def test_removes_a_sibling_that_finished_before_the_cancel(self):+ self._touch("weights.gguf") # done+ self._touch("mmproj-vl.gguf.part") # in flight+ removed = llm_router._discard_incomplete(_VISION)+ self.assertIn("weights.gguf", removed)+ self.assertIn("mmproj-vl.gguf.part", removed)+ self.assertEqual(list(llm_server.LLM_MODELS_DIR.iterdir()), [])++ def test_leaves_a_complete_model_alone(self):+ self._touch("weights.gguf")+ self._touch("mmproj-vl.gguf")+ self.assertEqual(llm_router._discard_incomplete(_VISION), [])+ self.assertEqual(len(list(llm_server.LLM_MODELS_DIR.iterdir())), 2)++ def test_nothing_on_disk_is_not_an_error(self):+ self.assertEqual(llm_router._discard_incomplete(_VISION), [])+++class _FakeResponse:+ def __init__(self, body: bytes) -> None:+ self._body = body+ self.headers = {"Content-Length": str(len(body))}++ def read(self, _size: int) -> bytes:+ chunk, self._body = self._body, b""+ return chunk++ def __enter__(self):+ return self++ def __exit__(self, *_exc) -> None:+ return None+++class EngineDigestTests(unittest.TestCase):+ """The engine archive's files are executed, so a download whose bytes differ+ from the digest GitHub published for the asset must be refused — and must+ not be left behind in the temp folder."""++ BODY = b"llama-server archive bytes"++ def setUp(self) -> None:+ self._tmp = tempfile.TemporaryDirectory()+ tmp_dir = self._tmp.name+ real_mkstemp = tempfile.mkstemp # llm_server.tempfile is this same module+ patches = [+ mock.patch.object(llm_server, "urlopen", lambda *_a, **_k: _FakeResponse(self.BODY)),+ mock.patch.object(llm_server.tempfile, "mkstemp", lambda suffix="": real_mkstemp(suffix=suffix, dir=tmp_dir)),+ ]+ for p in patches:+ p.start()+ self.addCleanup(p.stop)++ def tearDown(self) -> None:+ self._tmp.cleanup()++ def _download(self, digest):+ asset = {"name": "llama-bin-win-x64.zip", "browser_download_url": "https://example.invalid/a.zip"}+ if digest is not None:+ asset["digest"] = digest+ return llm_server._download_asset(asset, lambda _msg: None, lambda: None, "engine")++ def test_matching_digest_keeps_the_archive(self):+ path = self._download("sha256:" + hashlib.sha256(self.BODY).hexdigest())+ self.assertEqual(path.read_bytes(), self.BODY)++ def test_mismatching_digest_is_refused_and_removed(self):+ with self.assertRaises(RuntimeError):+ self._download("sha256:" + "0" * 64)+ self.assertEqual(list(Path(self._tmp.name).iterdir()), [])++ def test_asset_without_digest_is_still_accepted(self):+ path = self._download(None)+ self.assertEqual(path.read_bytes(), self.BODY)+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_llm_pool_budget.py b/apps/forge-desktop/api/tests/test_llm_pool_budget.pynew file mode 100644index 000000000..9bc34a950--- /dev/null+++ b/apps/forge-desktop/api/tests/test_llm_pool_budget.py@@ -0,0 +1,279 @@+import importlib+import unittest++llm_server = importlib.import_module("services.llm_server")+++class _FakeSlot:+ """Stands in for a loaded LlamaServerManager: alive, with a last-used stamp+ and a VRAM estimate."""++ def __init__(self, last_used: float, vram_mb: int, busy: int = 0, port: int = 0) -> None:+ self._last_used = last_used+ self.vram_mb = vram_mb+ self.port = port+ self.busy_count = busy+ self.unloaded = False++ def _alive(self) -> bool:+ return not self.unloaded++ def unload(self) -> None:+ self.unloaded = True+++class EstimateVramTests(unittest.TestCase):+ def test_declared_estimate_wins(self):+ self.assertEqual(llm_server.estimate_vram_mb({"vram_estimate_mb": 4200}), 4200)++ def test_custom_model_is_derived_from_file_size(self):+ # 9 GB of weights: enough on its own to fill a 12 GB card.+ mb = llm_server.estimate_vram_mb({"size_bytes": 9 * 1024**3})+ self.assertGreater(mb, 11000)+ self.assertLess(mb, 12500)++ def test_unknown_size_yields_zero(self):+ self.assertEqual(llm_server.estimate_vram_mb({}), 0)+++class PoolBudgetTests(unittest.TestCase):+ """Numbers are the ones measured on the reference machine: an RTX 5070+ reporting 11.9 GiB, so a 768 MiB reserve leaves a 11.4 GiB budget."""++ def setUp(self) -> None:+ self.pool = llm_server.LlamaPool()+ self._orig_max = llm_server.resolve_max_models+ self._orig_budget = llm_server.vram_budget_mb+ llm_server.resolve_max_models = lambda: 2+ llm_server.vram_budget_mb = lambda: int(11.9 * 1024) - 768 # 11417++ def tearDown(self) -> None:+ llm_server.resolve_max_models = self._orig_max+ llm_server.vram_budget_mb = self._orig_budget++ def _load(self, **slots) -> None:+ for i, (mid, vram) in enumerate(slots.items()):+ self.pool._slots[mid] = _FakeSlot(last_used=float(i), vram_mb=vram)++ def test_a_pair_that_fits_is_kept(self):+ # qwen3-4b (4200) already loaded, cadquery-coder-7b (6200) incoming.+ self._load(qwen4b=4200)+ self.pool._enforce_limit_locked(reserve=1, incoming_mb=6200)+ self.assertEqual(list(self.pool._slots), ["qwen4b"])++ def test_a_pair_that_does_not_fit_evicts_the_oldest(self):+ # qwen3-4b (4200) + qwen3-vl-8b (7800) = 12000 > 11417.+ self._load(qwen4b=4200)+ self.pool._enforce_limit_locked(reserve=1, incoming_mb=7800)+ self.assertEqual(list(self.pool._slots), [])++ def test_an_oversized_model_gets_the_card_to_itself(self):+ # The custom 14B alone exceeds the budget: it still loads, alone.+ self._load(qwen4b=4200, coder7b=6200)+ self.pool._enforce_limit_locked(reserve=1, incoming_mb=11700)+ self.assertEqual(list(self.pool._slots), [])++ def test_count_limit_still_applies_under_the_budget(self):+ # Three tiny models fit the VRAM budget but not `max_models: 2`.+ self._load(a=500, b=500)+ self.pool._enforce_limit_locked(reserve=1, incoming_mb=500)+ self.assertEqual(list(self.pool._slots), ["b"])++ def test_evicts_least_recently_used_first(self):+ self._load(oldest=4200, newest=4200)+ llm_server.resolve_max_models = lambda: 3+ self.pool._enforce_limit_locked(reserve=1, incoming_mb=7800)+ self.assertNotIn("oldest", self.pool._slots)++ def test_no_gpu_falls_back_to_the_count_rule(self):+ llm_server.vram_budget_mb = lambda: 0+ self._load(a=9000)+ self.pool._enforce_limit_locked(reserve=1, incoming_mb=9000)+ self.assertEqual(list(self.pool._slots), ["a"])++ def test_unknown_estimate_never_evicts(self):+ # A model with no size on disk must not push everything out.+ self._load(a=4200)+ self.pool._enforce_limit_locked(reserve=1, incoming_mb=0)+ self.assertEqual(list(self.pool._slots), ["a"])++ def test_a_concurrent_load_counts_against_the_budget(self):+ # ensure() reserves under the lock but loads outside it, so a slot being+ # started has no process yet. Counting only live slots let two callers+ # (agent turn + workflow LLM node) each load 7.8 GB on an 11.4 GB card.+ loading = _FakeSlot(last_used=0.0, vram_mb=7800, port=llm_server.SERVER_PORT)+ loading.unloaded = True # reserved: not alive yet+ self.pool._slots["incoming-a"] = loading+ self.pool._loading_ports.add(llm_server.SERVER_PORT)+ self._load(alive_one=4200)++ self.pool._enforce_limit_locked(reserve=1, incoming_mb=7800)+ # 7800 (in flight) + 7800 (incoming) already blows the budget, so the+ # live 4.2 GB model goes.+ self.assertNotIn("alive_one", self.pool._slots)++ def test_a_concurrent_load_counts_against_the_model_limit(self):+ loading = _FakeSlot(last_used=0.0, vram_mb=500, port=llm_server.SERVER_PORT)+ loading.unloaded = True+ self.pool._slots["incoming-a"] = loading+ self.pool._loading_ports.add(llm_server.SERVER_PORT)+ self._load(a=500) # 1 live + 1 loading + 1 incoming > max_models (2)++ self.pool._enforce_limit_locked(reserve=1, incoming_mb=500)+ self.assertNotIn("a", self.pool._slots)++ def test_a_slot_answering_a_request_is_never_evicted(self):+ # Evicting it would terminate llama-server mid-generation: the caller+ # gets a truncated stream and the node fails with no message.+ self.pool._slots["busy"] = _FakeSlot(last_used=0.0, vram_mb=7800, busy=1)+ self.pool._enforce_limit_locked(reserve=1, incoming_mb=7800)+ self.assertIn("busy", self.pool._slots)++ def test_a_slot_being_started_is_never_evicted(self):+ # From the moment Popen returns, a slot is _alive() while the loading+ # thread still holds its lock for the whole of _wait_for_health (up to+ # 180 s). unload() runs UNDER the pool lock, so evicting it there would+ # block every other pool operation — /llm/status, ensure(), and the+ # unload_all() the 3D pipeline calls to reclaim VRAM — for that long.+ starting = _FakeSlot(last_used=0.0, vram_mb=7800, port=llm_server.SERVER_PORT)+ self.pool._slots["starting"] = starting+ self.pool._loading_ports.add(llm_server.SERVER_PORT)++ self.pool._enforce_limit_locked(reserve=1, incoming_mb=7800)+ self.assertIn("starting", self.pool._slots)+ self.assertFalse(starting.unloaded)++ def test_over_capacity_counts_loads_in_flight(self):+ loading = _FakeSlot(last_used=0.0, vram_mb=7800, port=llm_server.SERVER_PORT)+ loading.unloaded = True # reserved, no process yet+ self.pool._slots["incoming-a"] = loading+ self.pool._loading_ports.add(llm_server.SERVER_PORT)+ # Nothing is alive, yet the card is already spoken for.+ self.assertTrue(self.pool._over_capacity_locked(7800))+ self.pool._loading_ports.clear()+ self.assertFalse(self.pool._over_capacity_locked(7800))++ def test_only_loads_and_live_requests_are_worth_waiting_for(self):+ # ensure() waits for these to end instead of loading a second model on a+ # one-model card; a merely idle slot is evicted rather than waited on.+ idle = _FakeSlot(last_used=0.0, vram_mb=4200, port=llm_server.SERVER_PORT)+ self.pool._slots["idle"] = idle+ self.assertFalse(self.pool._transient_blockers_locked())++ idle.busy_count = 1+ self.assertTrue(self.pool._transient_blockers_locked())++ idle.busy_count = 0+ self.pool._loading_ports.add(llm_server.SERVER_PORT + 1)+ self.assertTrue(self.pool._transient_blockers_locked())++ def test_a_crashed_slot_is_restarted_on_a_fresh_port(self):+ # Its port was handed to another model meanwhile; respawning in place+ # killed that model's server through _kill_stale_server.+ dead = _FakeSlot(last_used=0.0, vram_mb=500, port=llm_server.SERVER_PORT)+ dead.unloaded = True+ self.pool._slots["x"] = dead+ self.pool._slots["y"] = _FakeSlot(last_used=1.0, vram_mb=500, port=llm_server.SERVER_PORT)+ orig = llm_server.LlamaServerManager.ensure+ llm_server.LlamaServerManager.ensure = lambda self, mid, spec: None+ try:+ slot = self.pool.ensure("x", {"vram_mb": 500})+ finally:+ llm_server.LlamaServerManager.ensure = orig+ self.assertIsNot(slot, dead)+ self.assertNotEqual(slot.port, llm_server.SERVER_PORT)+ self.assertFalse(self.pool._slots["y"].unloaded)++ def test_unload_all_spares_requests_and_cold_starts(self):+ idle = _FakeSlot(last_used=0.0, vram_mb=4200, port=llm_server.SERVER_PORT)+ busy = _FakeSlot(last_used=0.0, vram_mb=4200, busy=1, port=llm_server.SERVER_PORT + 1)+ starting = _FakeSlot(last_used=0.0, vram_mb=4200, port=llm_server.SERVER_PORT + 2)+ self.pool._slots.update(idle=idle, busy=busy, starting=starting)+ self.pool._loading_ports.add(starting.port)++ self.pool.unload_all()+ self.assertEqual(sorted(self.pool._slots), ["busy", "starting"])+ self.assertTrue(idle.unloaded)++ self.pool.unload_all(force=True)+ self.assertEqual(list(self.pool._slots), [])+ self.assertTrue(busy.unloaded and starting.unloaded)++ def test_no_free_port_raises_a_readable_error(self):+ for i in range(llm_server.MAX_SLOT_PORTS):+ self.pool._loading_ports.add(llm_server.SERVER_PORT + i)+ with self.assertRaises(RuntimeError) as ctx:+ self.pool.ensure("whatever", {"vram_mb": 500})+ self.assertIn("slots", str(ctx.exception))+++class ReaperTests(unittest.TestCase):+ def setUp(self) -> None:+ self.pool = llm_server.LlamaPool()++ def test_an_idle_slot_is_unloaded(self):+ old = _FakeSlot(last_used=0.0, vram_mb=4200)+ self.pool._slots["old"] = old+ self.pool._reap_once(now=llm_server.IDLE_TTL_SECONDS + 1)+ self.assertEqual(list(self.pool._slots), [])+ self.assertTrue(old.unloaded)++ def test_a_slot_answering_a_long_request_survives(self):+ # A generation longer than the TTL (Text-to-CAD, a 14B on CPU) used to+ # be killed mid-answer: _last_used only moved once a call had finished.+ busy = _FakeSlot(last_used=0.0, vram_mb=4200, busy=1)+ self.pool._slots["busy"] = busy+ self.pool._reap_once(now=llm_server.IDLE_TTL_SECONDS * 10)+ self.assertEqual(list(self.pool._slots), ["busy"])+ self.assertFalse(busy.unloaded)++ def test_a_crashed_slot_is_dropped(self):+ dead = _FakeSlot(last_used=0.0, vram_mb=4200)+ dead.unloaded = True+ self.pool._slots["dead"] = dead+ self.pool._reap_once(now=1.0)+ self.assertEqual(list(self.pool._slots), [])+++ def test_a_slot_being_started_is_not_idle(self):+ # Same reason as the eviction case: the reaper also unloads under the+ # pool lock, so a slot mid-cold-start must not be its victim.+ starting = _FakeSlot(last_used=0.0, vram_mb=4200, port=llm_server.SERVER_PORT)+ self.pool._slots["starting"] = starting+ self.pool._loading_ports.add(llm_server.SERVER_PORT)+ self.pool._reap_once(now=llm_server.IDLE_TTL_SECONDS * 10)+ self.assertEqual(list(self.pool._slots), ["starting"])+ self.assertFalse(starting.unloaded)+++class BusyContextTests(unittest.TestCase):+ def test_busy_counts_nest_and_stamp_last_used(self):+ slot = llm_server.LlamaServerManager(port=1)+ self.assertEqual(slot.busy_count, 0)+ with slot.busy():+ self.assertEqual(slot.busy_count, 1)+ with slot.busy():+ self.assertEqual(slot.busy_count, 2)+ self.assertEqual(slot.busy_count, 1)+ self.assertEqual(slot.busy_count, 0)+ self.assertGreater(slot._last_used, 0.0)++ def test_hold_and_release_pair_up(self):+ # ensure(hold=True) claims the slot before returning it; the caller+ # releases it once the request is over.+ slot = llm_server.LlamaServerManager(port=1)+ slot.hold()+ self.assertEqual(slot.busy_count, 1)+ slot.release()+ self.assertEqual(slot.busy_count, 0)++ def test_busy_is_released_when_the_request_raises(self):+ slot = llm_server.LlamaServerManager(port=1)+ with self.assertRaises(ValueError):+ with slot.busy():+ raise ValueError("client disconnected")+ self.assertEqual(slot.busy_count, 0)+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_mesh_ops_operations.py b/apps/forge-desktop/api/tests/test_mesh_ops_operations.pynew file mode 100644index 000000000..b7ffeff06--- /dev/null+++ b/apps/forge-desktop/api/tests/test_mesh_ops_operations.py@@ -0,0 +1,323 @@+import io+import json+import shutil+import subprocess+import tempfile+import unittest+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++from services.mesh_ops import MeshOpContext+from services.mesh_ops import operations+++class _FakeGeometry:+ def __init__(self, faces=None) -> None:+ self.faces = faces if faces is not None else [1, 2, 3]+ self.vertices = [1, 2, 3, 4]+ self.exports = []++ def export(self, path) -> None:+ self.exports.append(str(path))+ Path(path).touch()+++class _FakeScene:+ pass+++class _FakeMesh:+ def vertex_number(self) -> int:+ return 4++ def face_number(self) -> int:+ return 3+++class _FakeMeshSet:+ def __init__(self) -> None:+ self.calls = []++ def current_mesh(self):+ return _FakeMesh()++ def __getattr__(self, name):+ def call(*args, **kwargs):+ self.calls.append((name, args, kwargs))+ if name == "save_current_mesh":+ Path(args[0]).touch()++ return call+++class _InputCapture:+ def __init__(self) -> None:+ self.value = ""++ def write(self, value) -> None:+ self.value += value++ def close(self) -> None:+ pass+++class _FakeProcess:+ def __init__(self, messages, return_code=0, stderr="") -> None:+ self.stdin = _InputCapture()+ self.stdout = iter(f"{json.dumps(message)}\n" for message in messages)+ self.stderr = io.StringIO(stderr)+ self.return_code = return_code+ self.killed = False++ def wait(self) -> int:+ return self.return_code++ def kill(self) -> None:+ self.killed = True+++class MeshOpOperationRegressionTests(unittest.TestCase):+ def test_meshopt_runner_is_valid_javascript(self) -> None:+ node = shutil.which("node") or shutil.which("nodejs")+ if node is None:+ self.skipTest("Node.js is unavailable")+ runner = Path(operations.__file__).with_name("meshopt_runner.cjs")+ result = subprocess.run(+ [node, "--check", str(runner)],+ capture_output=True,+ text=True,+ check=False,+ )+ self.assertEqual(result.returncode, 0, result.stderr)++ def test_repair_keeps_the_original_filter_order_and_arguments(self) -> None:+ mesh_set = _FakeMeshSet()+ source = _FakeGeometry()+ result_geometry = _FakeGeometry(faces=[1, 2])+ events = []++ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ input_path = root / "input.glb"+ output_path = root / "output.glb"+ input_path.touch()+ context = MeshOpContext(+ workspace_dir=root,+ temp_dir=root,+ output_path=output_path,+ progress_cb=lambda percent, label: events.append(+ ("progress", percent, label)+ ),+ log_cb=lambda message: events.append(("log", message)),+ )++ with (+ patch.object(+ operations,+ "_mesh_libraries",+ return_value=(+ SimpleNamespace(MeshSet=lambda: mesh_set),+ object(),+ ),+ ),+ patch.object(operations, "_load_single_mesh", return_value=source),+ patch.object(+ operations,+ "_raw_geometry",+ return_value=result_geometry,+ ),+ ):+ result = operations.repair_mesh(input_path, {}, context)++ self.assertEqual(result.file_path, output_path)+ self.assertEqual(result.details, {"face_count": 2})+ self.assertEqual(+ [call[0] for call in mesh_set.calls],+ [+ "load_new_mesh",+ "meshing_remove_duplicate_vertices",+ "meshing_remove_duplicate_faces",+ "meshing_remove_null_faces",+ "meshing_remove_folded_faces",+ "meshing_repair_non_manifold_edges",+ "meshing_repair_non_manifold_vertices",+ "meshing_close_holes",+ "save_current_mesh",+ ],+ )+ self.assertEqual(mesh_set.calls[5][2], {"method": 0})+ self.assertEqual(+ mesh_set.calls[7][2],+ {+ "maxholesize": 2000,+ "newfaceselected": False,+ "selfintersection": False,+ },+ )+ self.assertIn(("progress", 100, "Done"), events)++ def test_smooth_keeps_taubin_and_laplacian_parameter_semantics(self) -> None:+ for mode, expected_method, expected_arguments in (+ (+ "taubin",+ "apply_coord_taubin_smoothing",+ {"lambda_": 0.4, "mu": -0.41000000000000003, "stepsmoothnum": 7},+ ),+ (+ "laplacian",+ "apply_coord_laplacian_smoothing",+ {"stepsmoothnum": 7, "cotangentweight": False},+ ),+ ):+ with self.subTest(mode=mode), tempfile.TemporaryDirectory() as directory:+ mesh_set = _FakeMeshSet()+ geometry = _FakeGeometry()+ root = Path(directory)+ input_path = root / "input.glb"+ input_path.touch()+ context = MeshOpContext(+ workspace_dir=root,+ temp_dir=root,+ output_path=root / "output.glb",+ )++ with (+ patch.object(+ operations,+ "_mesh_libraries",+ return_value=(+ SimpleNamespace(MeshSet=lambda: mesh_set),+ SimpleNamespace(Scene=_FakeScene),+ ),+ ),+ patch.object(+ operations,+ "_load_single_mesh",+ return_value=geometry,+ ),+ patch.object(+ operations,+ "_raw_geometry",+ return_value=geometry,+ ),+ ):+ operations.smooth_mesh(+ input_path,+ {"iterations": 7, "lambda_": 0.4, "mode": mode},+ context,+ )++ smoothing_call = next(+ call for call in mesh_set.calls if call[0] == expected_method+ )+ self.assertEqual(smoothing_call[2], expected_arguments)++ def test_legacy_smooth_keeps_its_original_laplacian_arguments(self) -> None:+ mesh_set = _FakeMeshSet()+ geometry = _FakeGeometry()+ fake_trimesh = SimpleNamespace(+ Scene=_FakeScene,+ load=lambda path, **kwargs: geometry,+ )++ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ input_path = root / "input.glb"+ input_path.touch()+ context = MeshOpContext(+ workspace_dir=root,+ temp_dir=root,+ output_path=root / "output.glb",+ preserve_visuals=True,+ )+ with (+ patch.object(+ operations,+ "_mesh_libraries",+ return_value=(+ SimpleNamespace(MeshSet=lambda: mesh_set),+ fake_trimesh,+ ),+ ),+ patch.object(+ operations,+ "_load_single_mesh",+ return_value=geometry,+ ),+ patch.object(operations, "_has_texture", return_value=False),+ ):+ operations.smooth_mesh(+ input_path,+ {"iterations": 9, "lambda_": 0.5, "mode": "laplacian"},+ context,+ )++ smoothing_call = next(+ call+ for call in mesh_set.calls+ if call[0] == "apply_coord_laplacian_smoothing"+ )+ self.assertEqual(smoothing_call[2], {"stepsmoothnum": 9})++ def test_decimate_forwards_meshopt_progress_logs_and_result(self) -> None:+ messages = [+ {"type": "log", "message": "Current triangles: 12"},+ {"type": "progress", "percent": 55, "label": "Simplifying mesh…"},+ {+ "type": "done",+ "result": {"filePath": "/workspace/result.glb", "faceCount": 5},+ },+ ]+ fake_process = _FakeProcess(messages)+ events = []++ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ input_path = root / "input.glb"+ input_path.touch()+ context = MeshOpContext(+ workspace_dir=root,+ temp_dir=root,+ progress_cb=lambda percent, label: events.append(+ ("progress", percent, label)+ ),+ log_cb=lambda message: events.append(("log", message)),+ )+ with (+ patch.object(+ operations,+ "_node_executable",+ return_value=("node", False),+ ),+ patch.object(+ operations,+ "_meshopt_dependency_dir",+ return_value=root,+ ),+ patch.object(+ operations.subprocess,+ "Popen",+ return_value=fake_process,+ ) as popen,+ ):+ result = operations.decimate_mesh(+ input_path,+ {"target_faces": 5},+ context,+ )++ self.assertEqual(result.file_path, Path("/workspace/result.glb"))+ self.assertEqual(result.details, {"face_count": 5})+ self.assertIn(("log", "Current triangles: 12"), events)+ self.assertIn(("progress", 55, "Simplifying mesh…"), events)+ command = popen.call_args.args[0]+ self.assertEqual(command[0], "node")+ self.assertTrue(command[1].endswith("meshopt_runner.cjs"))+ payload = json.loads(fake_process.stdin.value)+ self.assertEqual(payload["inputPath"], str(input_path))+ self.assertEqual(payload["params"], {"target_faces": 5})+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_mesh_ops_processor.py b/apps/forge-desktop/api/tests/test_mesh_ops_processor.pynew file mode 100644index 000000000..2f8a6659a--- /dev/null+++ b/apps/forge-desktop/api/tests/test_mesh_ops_processor.py@@ -0,0 +1,76 @@+import io+import json+import tempfile+import unittest+from contextlib import redirect_stdout+from pathlib import Path+from unittest.mock import patch++from services.mesh_ops import MeshOpResult+from services.mesh_ops import processor+++class _FakeRegistry:+ def __init__(self, output_path: Path) -> None:+ self.output_path = output_path+ self.calls = []++ def run(self, operation_id, input_path, params, context):+ self.calls.append((operation_id, input_path, params, context))+ context.progress(35, "Working…")+ context.log("shared implementation")+ return MeshOpResult(self.output_path)+++class MeshOpProcessorTests(unittest.TestCase):+ def test_workflow_protocol_forwards_to_registry_and_preserves_events(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ input_path = root / "input.glb"+ output_path = root / "output.glb"+ input_path.touch()+ registry = _FakeRegistry(output_path)+ request = {+ "input": {"filePath": str(input_path)},+ "params": {"iterations": 7},+ "workspaceDir": str(root),+ "tempDir": str(root / "tmp"),+ }++ stdout = io.StringIO()+ with (+ patch.object(processor, "mesh_ops_registry", registry),+ patch.object(processor.sys, "stdin", io.StringIO(json.dumps(request))),+ redirect_stdout(stdout),+ ):+ processor.run_processor("smooth", "mesh-smoother")++ messages = [json.loads(line) for line in stdout.getvalue().splitlines()]+ self.assertEqual(+ [message["type"] for message in messages],+ ["progress", "log", "done"],+ )+ self.assertEqual(messages[-1]["result"]["filePath"], str(output_path))+ self.assertEqual(registry.calls[0][0:3], (+ "smooth",+ input_path,+ {"iterations": 7},+ ))+ self.assertEqual(registry.calls[0][3].workspace_dir, root)++ def test_missing_input_uses_existing_node_error_contract(self) -> None:+ stdout = io.StringIO()+ request = {"input": {}, "params": {}}+ with (+ patch.object(processor.sys, "stdin", io.StringIO(json.dumps(request))),+ redirect_stdout(stdout),+ ):+ processor.run_processor("repair", "mesh-repair")++ message = json.loads(stdout.getvalue())+ self.assertEqual(message["type"], "error")+ self.assertIn("mesh-repair: input file not found: None", message["message"])+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_mesh_ops_registry.py b/apps/forge-desktop/api/tests/test_mesh_ops_registry.pynew file mode 100644index 000000000..31a777a20--- /dev/null+++ b/apps/forge-desktop/api/tests/test_mesh_ops_registry.py@@ -0,0 +1,194 @@+import json+import tempfile+import unittest+from pathlib import Path++from services.mesh_ops import (+ MeshOp,+ MeshOpContext,+ MeshOpNotFoundError,+ MeshOpResult,+ MeshOpsRegistry,+ mesh_ops_registry,+)+++class MeshOpsRegistryTests(unittest.TestCase):+ def test_builtin_metadata_is_serializable_and_complete(self) -> None:+ descriptions = mesh_ops_registry.describe()++ self.assertEqual(+ [description["id"] for description in descriptions],+ ["repair", "decimate", "smooth"],+ )+ for description in descriptions:+ self.assertIn(description["category"], {"repair", "optimization"})+ self.assertFalse(description["destructive"])+ self.assertTrue(description["undoable"])+ self.assertIsInstance(description["params_schema"], list)+ json.dumps(descriptions)++ def test_run_applies_schema_defaults_without_mutating_metadata(self) -> None:+ calls = []++ def operation(input_path, params, context):+ calls.append((input_path, params, context))+ return MeshOpResult(input_path)++ registry = MeshOpsRegistry(+ [+ MeshOp(+ id="example",+ label="Example",+ params_schema=(+ {"id": "amount", "type": "int", "default": 3},+ ),+ fn=operation,+ category="test",+ )+ ]+ )++ with tempfile.TemporaryDirectory() as directory:+ input_path = Path(directory) / "mesh.glb"+ input_path.touch()+ context = MeshOpContext(Path(directory), Path(directory))+ registry.run("example", input_path, {"extra": True}, context)++ self.assertEqual(calls[0][1], {"amount": 3, "extra": True})+ calls[0][1]["amount"] = 99+ self.assertEqual(+ registry.describe()[0]["params_schema"][0]["default"],+ 3,+ )++ def test_run_clamps_supplied_values_to_schema_bounds(self) -> None:+ calls = []++ def operation(input_path, params, context):+ calls.append(params)+ return MeshOpResult(input_path)++ registry = MeshOpsRegistry(+ [+ MeshOp(+ id="bounded",+ label="Bounded",+ params_schema=(+ {+ "id": "count",+ "type": "int",+ "default": 3,+ "min": 1,+ "max": 5,+ },+ {+ "id": "strength",+ "type": "float",+ "default": 0.5,+ "min": 0.1,+ "max": 1.0,+ },+ ),+ fn=operation,+ category="test",+ )+ ]+ )++ with tempfile.TemporaryDirectory() as directory:+ input_path = Path(directory) / "mesh.glb"+ input_path.touch()+ context = MeshOpContext(Path(directory), Path(directory))+ registry.run(+ "bounded",+ input_path,+ {"count": 99, "strength": -2.0},+ context,+ )++ self.assertEqual(calls[0], {"count": 5, "strength": 0.1})++ def test_run_rejects_non_numeric_values_for_bounded_params(self) -> None:+ operation = MeshOp(+ id="bounded",+ label="Bounded",+ params_schema=(+ {"id": "amount", "type": "int", "min": 1, "max": 5},+ ),+ fn=lambda path, params, context: MeshOpResult(path),+ category="test",+ )+ registry = MeshOpsRegistry([operation])++ with tempfile.TemporaryDirectory() as directory:+ input_path = Path(directory) / "mesh.glb"+ input_path.touch()+ context = MeshOpContext(Path(directory), Path(directory))+ with self.assertRaisesRegex(TypeError, "'amount' must be numeric"):+ registry.run(+ "bounded",+ input_path,+ {"amount": "a lot"},+ context,+ )++ def test_invalid_duplicate_and_unknown_ids_are_rejected(self) -> None:+ operation = MeshOp(+ id="valid",+ label="Valid",+ params_schema=(),+ fn=lambda path, params, context: MeshOpResult(path),+ category="test",+ )+ registry = MeshOpsRegistry([operation])++ with self.assertRaisesRegex(ValueError, "Duplicate"):+ registry.register(operation)+ with self.assertRaisesRegex(ValueError, "Invalid"):+ registry.register(+ MeshOp(+ id="Not Valid",+ label="Invalid",+ params_schema=(),+ fn=operation.fn,+ category="test",+ )+ )+ with self.assertRaises(MeshOpNotFoundError):+ registry.get("missing")++ def test_workflow_manifests_share_registry_schemas_and_thin_adapters(self) -> None:+ repository_root = Path(__file__).resolve().parents[2]+ nodes_root = repository_root / "src" / "areas" / "workflows" / "nodes"+ cases = {+ "repair": ("mesh-repair", "repair"),+ "decimate": ("mesh-optimizer", "decimate"),+ "smooth": ("mesh-smoother", "smooth"),+ }++ descriptions = {+ description["id"]: description+ for description in mesh_ops_registry.describe()+ }+ for operation_id, (extension_id, wrapper_operation_id) in cases.items():+ extension_dir = nodes_root / extension_id+ manifest = json.loads(+ (extension_dir / "manifest.json").read_text(encoding="utf-8")+ )+ self.assertEqual(manifest["entry"], "processor.py")+ self.assertEqual(+ manifest["nodes"][0]["params_schema"],+ descriptions[operation_id]["params_schema"],+ )++ wrapper = (extension_dir / "processor.py").read_text(encoding="utf-8")+ self.assertIn(+ f'run_processor("{wrapper_operation_id}", "{extension_id}")',+ wrapper,+ )+ self.assertLess(len(wrapper.splitlines()), 30)+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_mesh_routers_workspace.py b/apps/forge-desktop/api/tests/test_mesh_routers_workspace.pynew file mode 100644index 000000000..f03e86dff--- /dev/null+++ b/apps/forge-desktop/api/tests/test_mesh_routers_workspace.py@@ -0,0 +1,144 @@+import tempfile+import unittest+from pathlib import Path+from unittest.mock import patch++import trimesh+from fastapi import HTTPException++import routers.export as export_router+import routers.optimize as optimize_router+import services.generator_registry as registry+from services.mesh_ops import MeshOpResult++IDENTITY = [+ [1.0, 0.0, 0.0, 0.0],+ [0.0, 1.0, 0.0, 0.0],+ [0.0, 0.0, 1.0, 0.0],+ [0.0, 0.0, 0.0, 1.0],+]+++class MeshRoutersAfterWorkspaceMoveTests(unittest.TestCase):+ """Export and mesh-edit endpoints must resolve paths against the workspace as+ it is *now*. POST /settings/paths rebinds registry.WORKSPACE_DIR when the user+ moves the workspace; a name captured at import keeps pointing at the old+ folder, so a model generated after the move can't be exported or edited."""++ def setUp(self) -> None:+ self._tmp = tempfile.TemporaryDirectory()+ self.root = Path(self._tmp.name)+ self._prev_ws = registry.WORKSPACE_DIR+ # The user moved the workspace: the registry global now points here.+ registry.WORKSPACE_DIR = self.root / "new_workspace"+ # Keep the test hermetic against import-time bindings: if a router still+ # holds its own WORKSPACE_DIR name, point it at an empty "old" folder in+ # the temp tree so the assertions -- not the real workspace -- catch it.+ (self.root / "old_workspace").mkdir()+ self._stale = []+ for module in (export_router, optimize_router):+ if hasattr(module, "WORKSPACE_DIR"):+ self._stale.append((module, module.WORKSPACE_DIR))+ module.WORKSPACE_DIR = self.root / "old_workspace"++ mesh_dir = registry.WORKSPACE_DIR / "MyColl"+ mesh_dir.mkdir(parents=True)+ trimesh.creation.box().export(mesh_dir / "mesh.glb")++ def tearDown(self) -> None:+ registry.WORKSPACE_DIR = self._prev_ws+ for module, value in self._stale:+ module.WORKSPACE_DIR = value+ self._tmp.cleanup()++ def test_export_router_converts_a_mesh_in_the_moved_workspace(self) -> None:+ response = export_router.export_mesh("stl", "MyColl/mesh.glb")+ self.assertEqual(response.status_code, 200)+ self.assertGreater(len(response.body), 0)++ def test_optimize_export_converts_a_mesh_in_the_moved_workspace(self) -> None:+ response = optimize_router.export_mesh(path="MyColl/mesh.glb", format="obj")+ self.assertEqual(response.status_code, 200)+ self.assertIn(b"v ", response.body)++ def test_transform_writes_its_result_into_the_moved_workspace(self) -> None:+ result = optimize_router.transform_mesh(+ optimize_router.TransformRequest(path="MyColl/mesh.glb", matrix=IDENTITY)+ )+ self.assertTrue(result["url"].startswith("/workspace/MyColl/mesh_xf_"))+ written = registry.WORKSPACE_DIR / result["url"].removeprefix("/workspace/")+ self.assertTrue(written.is_file())++ def test_decimate_and_smooth_read_their_input_from_the_moved_workspace(self) -> None:+ # /optimize/mesh and /optimize/smooth resolve their input through this helper.+ resolved = optimize_router._resolve_input_path("MyColl/mesh.glb")+ self.assertEqual(resolved, (registry.WORKSPACE_DIR / "MyColl" / "mesh.glb").resolve())++ def test_decimate_and_smooth_write_their_result_into_the_moved_workspace(self) -> None:+ # The backends (meshoptimizer, pymeshlab) aren't available here, so stand in+ # for the mesh-ops registry and check the router's own path handling: the+ # workspace it hands the operation, where the output goes, and the URL.+ class _RecordingRegistry:+ def __init__(self) -> None:+ self.contexts = []++ def run(self, operation_id, input_path, params, context):+ self.contexts.append(context)+ context.output_path.touch()+ return MeshOpResult(context.output_path, {"face_count": 12})++ ops = _RecordingRegistry()+ with patch.object(optimize_router, "mesh_ops_registry", ops):+ decimated = optimize_router.optimize_mesh(+ optimize_router.OptimizeRequest(path="MyColl/mesh.glb", target_faces=500)+ )+ smoothed = optimize_router.smooth_mesh(+ optimize_router.SmoothRequest(path="MyColl/mesh.glb", iterations=2)+ )++ self.assertEqual(decimated["url"], "/workspace/MyColl/mesh_opt500.glb")+ self.assertEqual(smoothed["url"], "/workspace/MyColl/mesh_smooth2.glb")+ for context in ops.contexts:+ self.assertEqual(context.workspace_dir, registry.WORKSPACE_DIR)+ self.assertEqual(context.output_path.parent, registry.WORKSPACE_DIR / "MyColl")++ def test_a_path_leaving_the_workspace_is_still_refused(self) -> None:+ # Reading the live workspace must not loosen the containment check.+ trimesh.creation.box().export(self.root / "outside.glb")+ calls = (+ lambda: export_router.export_mesh("stl", "../outside.glb"),+ lambda: optimize_router.export_mesh(path="../outside.glb", format="obj"),+ )+ for call in calls:+ with self.assertRaises(HTTPException) as raised:+ call()+ self.assertEqual(raised.exception.status_code, 400)++ def test_a_sibling_folder_sharing_the_workspace_prefix_is_refused(self) -> None:+ # "<workspace>-secret" starts with the workspace's path string, so a string+ # prefix check let it through; the containment check must compare ancestry.+ sibling = self.root / "new_workspace-secret"+ sibling.mkdir()+ trimesh.creation.box().export(sibling / "private.glb")+ escaping = "../new_workspace-secret/private.glb"+ calls = {+ "/export/{fmt}": lambda: export_router.export_mesh("stl", escaping),+ "/optimize/export": lambda: optimize_router.export_mesh(path=escaping, format="obj"),+ "/optimize/mesh, /smooth, /transform": lambda: optimize_router._resolve_input_path(escaping),+ "/optimize/ply-to-splat": lambda: optimize_router.ply_to_splat(escaping),+ }+ for route, call in calls.items():+ with self.subTest(route=route), self.assertRaises(HTTPException) as raised:+ call()+ self.assertEqual(raised.exception.status_code, 400)++ def test_is_within_workspace_compares_ancestry(self) -> None:+ workspace = registry.WORKSPACE_DIR.resolve()+ self.assertTrue(registry.is_within_workspace(workspace))+ self.assertTrue(registry.is_within_workspace(workspace / "MyColl" / "mesh.glb"))+ self.assertFalse(registry.is_within_workspace(workspace.parent / "new_workspace-secret" / "x.glb"))+ self.assertFalse(registry.is_within_workspace(workspace.parent))+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_model_router.py b/apps/forge-desktop/api/tests/test_model_router.pynew file mode 100644index 000000000..4090a0ea0--- /dev/null+++ b/apps/forge-desktop/api/tests/test_model_router.py@@ -0,0 +1,313 @@+import asyncio+import json+import sys+import tempfile+import threading+import types+import unittest+from pathlib import Path+from unittest.mock import patch++from starlette.requests import Request++import routers.model as model_router+++SOURCES = [+ {+ "id": "primary",+ "provider": "huggingface",+ "repo_id": "org/main",+ "destination": ".",+ "checks": ["main.bin"],+ },+ {+ "id": "encoder",+ "provider": "huggingface",+ "repo_id": "org/encoder",+ "destination": "auxiliary/encoder",+ "checks": ["encoder.bin"],+ },+]+++def request_for(sources: list[dict]) -> Request:+ body = json.dumps({"sources": sources}).encode()+ sent = False++ async def receive():+ nonlocal sent+ if sent:+ return {"type": "http.disconnect"}+ sent = True+ return {"type": "http.request", "body": body, "more_body": False}++ return Request({+ "type": "http",+ "method": "POST",+ "path": "/model/hf-download-sources",+ "headers": [(b"authorization", b"Bearer test-token")],+ "query_string": b"",+ "server": ("test", 80),+ "client": ("test", 1),+ "scheme": "http",+ }, receive)+++async def collect_events(response) -> list[dict]:+ payload = ""+ async for chunk in response.body_iterator:+ payload += chunk.decode() if isinstance(chunk, bytes) else chunk+ return [+ json.loads(block[6:])+ for block in payload.strip().split("\n\n")+ if block.startswith("data: ")+ ]+++class MultiSourceRouterTests(unittest.TestCase):+ def setUp(self) -> None:+ self.tempdir = tempfile.TemporaryDirectory(prefix="modly-model-router-")+ self.models_dir = Path(self.tempdir.name) / "models"+ self.models_dir.mkdir()+ self.old_models_dir = model_router.registry_module.MODELS_DIR+ model_router.registry_module.MODELS_DIR = self.models_dir+ self.old_hf_module = sys.modules.get("huggingface_hub")++ def tearDown(self) -> None:+ model_router.registry_module.MODELS_DIR = self.old_models_dir+ model_router._download_controls.clear()+ if self.old_hf_module is None:+ sys.modules.pop("huggingface_hub", None)+ else:+ sys.modules["huggingface_hub"] = self.old_hf_module+ self.tempdir.cleanup()++ def install_hf_stub(self, files: dict[str, list[str]], calls: list[str]) -> None:+ module = types.ModuleType("huggingface_hub")++ def list_repo_files(repo_id, revision=None, token=None):+ calls.append(f"list:{repo_id}:{revision}:{token}")+ return files[repo_id]++ def hf_hub_url(repo_id, filename, revision=None):+ return f"https://example.invalid/{repo_id}/{revision or 'main'}/{filename}"++ module.list_repo_files = list_repo_files+ module.hf_hub_url = hf_hub_url+ sys.modules["huggingface_hub"] = module++ def test_lists_every_source_before_sequential_download_with_monotonic_progress(self) -> None:+ calls: list[str] = []+ controls: list[int] = []+ self.install_hf_stub({"org/main": ["main.bin"], "org/encoder": ["encoder.bin"]}, calls)++ def fake_download(**kwargs):+ calls.append(f"download:{kwargs['dest_dir']}:{kwargs['filename']}")+ controls.append(id(kwargs["control"]))+ target = Path(kwargs["dest_dir"]) / kwargs["filename"]+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(b"data")+ kwargs["progress_cb"]({+ "percent": kwargs["base_percent"],+ "file": kwargs["filename"],+ "fileIndex": kwargs["file_index"],+ "totalFiles": kwargs["total_files"],+ "status": "Downloading...",+ "bytesDownloaded": 4,+ "stalledSeconds": 0,+ })+ return 4++ async def run():+ with patch.object(model_router, "_download_file_streamed", fake_download):+ response = await model_router.hf_download_sources(+ request_for(SOURCES), "pixal3d/generate"+ )+ return await collect_events(response)++ events = asyncio.run(run())+ first_download = next(index for index, value in enumerate(calls) if value.startswith("download:"))+ self.assertTrue(all(value.startswith("list:") for value in calls[:first_download]))+ self.assertEqual(len(set(controls)), 1)+ self.assertEqual([event["percent"] for event in events if "percent" in event], sorted(+ event["percent"] for event in events if "percent" in event+ ))+ self.assertEqual(events[-1], {"percent": 100, "status": "done"})+ self.assertTrue((self.models_dir / "pixal3d/generate/main.bin").is_file())+ self.assertTrue((self.models_dir / "pixal3d/generate/auxiliary/encoder/encoder.bin").is_file())++ def test_pause_cancel_and_resume_reuse_one_model_control(self) -> None:+ calls: list[str] = []+ self.install_hf_stub({"org/main": ["main.bin"]}, calls)+ source = [SOURCES[0]]+ mode = "pause"++ def controlled_download(**kwargs):+ target = Path(kwargs["dest_dir"]) / kwargs["filename"]+ target.parent.mkdir(parents=True, exist_ok=True)+ part = Path(f"{target}.part")+ part.write_bytes(b"partial")+ if mode == "pause":+ kwargs["control"]["pause"].set()+ model_router._check_download_control(kwargs["control"])+ if mode == "cancel":+ kwargs["control"]["cancel"].set()+ model_router._check_download_control(kwargs["control"])+ part.replace(target)+ return target.stat().st_size++ async def one_run():+ with patch.object(model_router, "_download_file_streamed", controlled_download):+ response = await model_router.hf_download_sources(+ request_for(source), "pixal3d/generate"+ )+ return await collect_events(response)++ paused = asyncio.run(one_run())+ self.assertTrue(paused[-1]["paused"])+ self.assertTrue((self.models_dir / "pixal3d/generate/main.bin.part").is_file())++ mode = "cancel"+ cancelled = asyncio.run(one_run())+ self.assertTrue(cancelled[-1]["cancelled"])+ self.assertFalse((self.models_dir / "pixal3d/generate/main.bin.part").exists())++ mode = "resume"+ resumed = asyncio.run(one_run())+ self.assertEqual(resumed[-1], {"percent": 100, "status": "done"})+ self.assertTrue((self.models_dir / "pixal3d/generate/main.bin").is_file())++ def test_shared_target_downloads_under_extension_reserved_root(self) -> None:+ calls: list[str] = []+ self.install_hf_stub({"org/main": ["main.bin"]}, calls)++ def fake_download(**kwargs):+ target = Path(kwargs["dest_dir"]) / kwargs["filename"]+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(b"shared")+ return target.stat().st_size++ async def run():+ with patch.object(model_router, "_download_file_streamed", fake_download):+ response = await model_router.hf_download_sources(+ request_for([SOURCES[0]]), "pixal3d/_shared/base"+ )+ return await collect_events(response)++ events = asyncio.run(run())+ self.assertEqual(events[-1], {"percent": 100, "status": "done"})+ self.assertTrue(+ (self.models_dir / "pixal3d/_shared/base/main.bin").is_file()+ )++ def test_rejects_a_check_filtered_out_of_the_source_plan(self) -> None:+ calls: list[str] = []+ self.install_hf_stub({"org/main": ["other.bin"]}, calls)++ async def run():+ response = await model_router.hf_download_sources(+ request_for([SOURCES[0]]), "pixal3d/generate"+ )+ return await collect_events(response)++ events = asyncio.run(run())+ self.assertIn("excluded from its download plan", events[-1]["error"])+ self.assertFalse((self.models_dir / "pixal3d/generate/other.bin").exists())++ def test_download_uses_live_storage_after_settings_update(self):+ calls = []+ self.install_hf_stub({"org/main": ["main.bin"]}, calls)+ relocated = self.models_dir.parent / "relocated"+ registry = model_router.registry_module.GeneratorRegistry()+ registry.update_paths(relocated, None)++ def fake_download(**kwargs):+ target = Path(kwargs["dest_dir"]) / kwargs["filename"]+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(b"complete")+ return target.stat().st_size++ async def run():+ with patch.object(model_router, "_download_file_streamed", fake_download):+ for target_id in ("pixal3d/generate", "pixal3d/_shared/base"):+ response = await model_router.hf_download_sources(request_for([SOURCES[0]]), target_id)+ await collect_events(response)+ self.assertTrue((relocated / target_id / "main.bin").is_file())+ self.assertFalse((self.models_dir / target_id).exists())+ asyncio.run(run())++ def test_removal_unload_requires_confirmed_process_stop(self):+ from unittest.mock import Mock+ from services.extension_process import ExtensionProcess+ gen = Mock(spec=ExtensionProcess)+ with patch.object(model_router.generator_registry, "get_generator", return_value=gen):+ self.assertEqual(asyncio.run(model_router.unload_model("demo/a")), {"unloaded": True})+ gen.stop.assert_called_once()+ gen.unload.assert_not_called()+ gen.stop.side_effect = RuntimeError("still running")+ with self.assertRaisesRegex(RuntimeError, "still running"):+ asyncio.run(model_router.unload_model("demo/a"))++ def test_removal_rejects_direct_generator_that_remains_loaded(self):+ from unittest.mock import Mock+ from fastapi import HTTPException+ gen = Mock()+ gen.is_loaded.return_value = True+ with patch.object(model_router.generator_registry, "get_generator", return_value=gen):+ with self.assertRaises(HTTPException) as error:+ asyncio.run(model_router.unload_model("demo/a"))+ self.assertEqual(error.exception.status_code, 409)++ def test_composite_model_unload_route_uses_path_converter(self) -> None:+ paths = {route.path for route in model_router.router.routes}+ self.assertIn("/unload/{model_id:path}", paths)+ self.assertEqual(model_router.Request.__module__, "urllib.request")+++class ModelLifecycleEndpointTests(unittest.TestCase):+ def test_status_and_switch_do_not_block_the_event_loop_while_lifecycle_is_contended(self) -> None:+ class ContendedRegistry:+ def __init__(self):+ self.lock = threading.Lock()+ def active_status(self):+ with self.lock:+ return {"id": "demo/a", "loaded": True}+ def switch_model(self, model_id):+ with self.lock:+ return None++ registry = ContendedRegistry()+ previous = model_router.generator_registry+ model_router.generator_registry = registry++ async def assert_responsive(call):+ registry.lock.acquire()+ release = threading.Timer(0.25, registry.lock.release)+ release.start()+ try:+ start = asyncio.get_running_loop().time()+ task = asyncio.create_task(call())+ await asyncio.sleep(0.02)+ elapsed = asyncio.get_running_loop().time() - start+ self.assertLess(elapsed, 0.15)+ return await task+ finally:+ release.join()++ async def run():+ status = await assert_responsive(model_router.model_status)+ switched = await assert_responsive(lambda: model_router.switch_model("demo/b"))+ return status, switched++ try:+ status, switched = asyncio.run(run())+ finally:+ model_router.generator_registry = previous++ self.assertEqual(status["id"], "demo/a")+ self.assertEqual(switched, {"active": "demo/b"})+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_model_sources.py b/apps/forge-desktop/api/tests/test_model_sources.pynew file mode 100644index 000000000..54ecbf06e--- /dev/null+++ b/apps/forge-desktop/api/tests/test_model_sources.py@@ -0,0 +1,249 @@+import os+import tempfile+import unittest+from pathlib import Path++from services.model_sources import (+ installed_weight_variants,+ missing_weight_variant,+ model_sources_are_downloaded,+ normalize_model_sources,+ normalize_weight_group_references,+ normalize_weight_groups,+ normalize_weight_variants,+ resolve_model_root,+ resolve_weight_group_root,+ resolve_weight_storage_root,+ validate_source_file_plan,+ validate_model_node_ids,+ weight_group_sources_are_downloaded,+)+++def valid_node() -> dict:+ return {+ "model_sources": [+ {+ "id": "primary",+ "provider": "huggingface",+ "repo_id": "org/main",+ "destination": ".",+ "checks": ["pipeline.json"],+ },+ {+ "id": "encoder",+ "provider": "huggingface",+ "repo_id": "org/encoder",+ "revision": "refs/pr/1",+ "destination": "auxiliary/encoder",+ "include_prefixes": ["config.json", "weights/"],+ "checks": ["config.json", "model.safetensors"],+ },+ ]+ }+++class ModelSourcesTests(unittest.TestCase):+ def test_managed_node_ids_reject_case_aliases(self):+ for ids in (("Fast", "fast"), ("fast", "fast")):+ with self.subTest(ids=ids), self.assertRaisesRegex(ValueError, "portable-unique"):+ validate_model_node_ids([{"id": node_id} for node_id in ids])++ def test_validates_new_sources_without_reinterpreting_legacy_fields(self) -> None:+ sources = normalize_model_sources(valid_node())+ self.assertEqual([source["id"] for source in sources or []], ["primary", "encoder"])+ self.assertIsNone(normalize_model_sources({+ "hf_repo": "legacy/repo",+ "download_check": "../generate/model.safetensors",+ "hf_skip_prefixes": ["weights/**"],+ }))++ def test_rejects_unsafe_and_non_portable_declarations(self) -> None:+ source = valid_node()["model_sources"][0]+ for destination in ("../outside", "aux/CON", "aux/name.", "C:/models"):+ with self.subTest(destination=destination), self.assertRaises(ValueError):+ normalize_model_sources({+ "model_sources": [{**source, "destination": destination}]+ })+ with self.assertRaisesRegex(ValueError, "provider"):+ normalize_model_sources({+ "model_sources": [{**source, "provider": "url"}]+ })+ with self.assertRaisesRegex(ValueError, "portable-unique"):+ normalize_model_sources({+ "model_sources": [source, {**source, "id": "PRIMARY"}]+ })+ with self.assertRaisesRegex(ValueError, "checks"):+ normalize_model_sources({+ "model_sources": [{**source, "checks": []}]+ })++ def test_rejects_portable_cross_source_file_collisions(self) -> None:+ sources = normalize_model_sources(valid_node()) or []+ with self.assertRaisesRegex(ValueError, "portable target collision"):+ validate_source_file_plan(sources, {+ "primary": ["pipeline.json", "Auxiliary/Encoder/model.safetensors"],+ "encoder": ["config.json", "model.safetensors"],+ })++ def test_rejects_checks_excluded_from_the_download_plan(self) -> None:+ sources = normalize_model_sources(valid_node()) or []+ with self.assertRaisesRegex(ValueError, "excluded from its download plan"):+ validate_source_file_plan(sources, {+ "primary": ["pipeline.json"],+ "encoder": ["config.json"],+ })++ def test_requires_all_checks_and_rejects_symlinked_extension_ancestry(self) -> None:+ sources = normalize_model_sources(valid_node()) or []+ with tempfile.TemporaryDirectory(prefix="modly-model-sources-") as tmp:+ models = Path(tmp) / "models"+ model_root = models / "pixal3d" / "generate"+ encoder = model_root / "auxiliary" / "encoder"+ encoder.mkdir(parents=True)+ (model_root / "pipeline.json").write_text("{}", encoding="utf-8")+ (encoder / "config.json").write_text("{}", encoding="utf-8")+ self.assertFalse(model_sources_are_downloaded(models, "pixal3d/generate", sources))+ (encoder / "model.safetensors").write_bytes(b"x")+ self.assertTrue(model_sources_are_downloaded(models, "pixal3d/generate", sources))++ (encoder / "model.safetensors").write_bytes(b"")+ self.assertFalse(model_sources_are_downloaded(models, "pixal3d/generate", sources))+ (encoder / "model.safetensors").unlink()+ (encoder / "model.safetensors").mkdir()+ self.assertFalse(model_sources_are_downloaded(models, "pixal3d/generate", sources))++ for child in sorted((models / "pixal3d").rglob("*"), reverse=True):+ child.unlink() if child.is_file() else child.rmdir()+ (models / "pixal3d").rmdir()+ outside = Path(tmp) / "outside"+ (outside / "generate").mkdir(parents=True)+ try:+ os.symlink(outside, models / "pixal3d", target_is_directory=True)+ except (NotImplementedError, OSError) as exc:+ self.skipTest(f"Symlinks unavailable: {exc}")+ with self.assertRaisesRegex(ValueError, "symlink"):+ resolve_model_root(models, "pixal3d/generate")+ self.assertFalse(model_sources_are_downloaded(models, "pixal3d/generate", sources))++ def test_validates_group_references_and_rejects_portable_aliases(self) -> None:+ groups = normalize_weight_groups({+ "weight_groups": [{+ "id": "Base-Weights",+ "model_sources": valid_node()["model_sources"],+ }]+ })+ self.assertEqual(+ normalize_weight_group_references(+ {"weight_groups": ["base-weights"]}, groups+ ),+ ["Base-Weights"],+ )+ with self.assertRaisesRegex(ValueError, "unknown weight group"):+ normalize_weight_group_references(+ {"weight_groups": ["missing"]}, groups+ )+ with self.assertRaisesRegex(ValueError, "portable-unique"):+ normalize_weight_groups({+ "weight_groups": [+ {"id": "base", "model_sources": valid_node()["model_sources"]},+ {"id": "BASE", "model_sources": valid_node()["model_sources"]},+ ]+ })++ def test_shared_group_uses_reserved_extension_storage_root(self) -> None:+ group = (normalize_weight_groups({+ "weight_groups": [{+ "id": "base",+ "model_sources": [{+ "id": "primary",+ "provider": "huggingface",+ "repo_id": "org/base",+ "destination": ".",+ "checks": ["model.bin"],+ }],+ }]+ }) or [])[0]+ with tempfile.TemporaryDirectory(prefix="modly-shared-sources-") as tmp:+ models = Path(tmp) / "models"+ group_root = models / "demo" / "_shared" / "base"+ self.assertEqual(resolve_weight_group_root(models, "demo", "base"), group_root)+ self.assertEqual(+ resolve_weight_storage_root(models, "demo/_shared/base"), group_root+ )+ with self.assertRaisesRegex(ValueError, "reserved"):+ resolve_model_root(models, "demo/_shared")+ self.assertFalse(weight_group_sources_are_downloaded(models, "demo", group))+ group_root.mkdir(parents=True)+ (group_root / "model.bin").write_bytes(b"weights")+ self.assertTrue(weight_group_sources_are_downloaded(models, "demo", group))++ def test_weight_variants_validate_and_report_the_missing_selection(self) -> None:+ def variant(quant: str) -> dict:+ return {+ "id": quant,+ "include_prefixes": [f"dit/model_{quant}.gguf"],+ "checks": [f"dit/model_{quant}.gguf"],+ }++ node = {+ "hf_repo": "org/model-gguf",+ "download_check": "pipeline.json",+ "params_schema": [+ {"id": "quant", "type": "select", "options": [{"value": "Q4"}, {"value": "Q5"}]}+ ],+ "weight_variants": {"param": "quant", "options": [variant("Q4"), variant("Q5")]},+ }+ variants = normalize_weight_variants(node) or {}+ self.assertEqual(variants["default"], "Q4")+ self.assertIsNone(normalize_weight_variants({"hf_repo": "org/model"}))++ def with_options(options: list, **extra) -> dict:+ return {**node, "weight_variants": {"param": "quant", "options": options, **extra}}++ overlapping = {**variant("Q5"), "include_prefixes": ["dit/"]}+ for broken, message in (+ ({**node, "hf_repo": ""}, "requires hf_repo"),+ ({**node, "model_sources": []}, "cannot be combined"),+ ({**node, "weight_groups": ["base"]}, "cannot be combined with weight_groups"),+ ({**node, "download_check": "dit/model_Q4.gguf"}, "download_check"),+ (with_options([variant("Q4"), overlapping]), "share files"),+ (with_options([variant("Q4")], default="Q8"), "default"),+ (with_options([{**variant("Q4"), "checks": ["x.gguf"]}]), "not covered"),+ (with_options([{**variant("Q4"), "size_gb": True}]), "size_gb"),+ (with_options([{**variant("Q4"), "vram_gb": 0}]), "vram_gb"),+ (with_options([{**variant("Q4"), "vram_gb": "6"}]), "vram_gb"),+ ({**node, "params_schema": []}, "must name a params_schema entry"),+ (+ {**node, "params_schema": [{"id": "quant", "options": [{"value": "Q5"}]}]},+ "must offer every weight variant id",+ ),+ ):+ with self.subTest(message=message), self.assertRaisesRegex(ValueError, message):+ normalize_weight_variants(broken)++ # A param that declares no options is left to the node to interpret.+ self.assertIsNotNone(+ normalize_weight_variants({**node, "params_schema": [{"id": "quant", "type": "string"}]})+ )+ self.assertNotIn("vram_gb", variants["options"][0])+ with_vram = normalize_weight_variants(with_options([{**variant("Q4"), "vram_gb": 6.5}])) or {}+ self.assertEqual(with_vram["options"][0]["vram_gb"], 6.5)++ with tempfile.TemporaryDirectory(prefix="modly-weight-variants-") as tmp:+ models = Path(tmp) / "models"+ dit = models / "trellis" / "generate" / "dit"+ dit.mkdir(parents=True)+ (dit / "model_Q5.gguf").write_bytes(b"q5")+ (dit / "model_Q4.gguf").write_bytes(b"")+ self.assertEqual(installed_weight_variants(models, "trellis/generate", variants), ["Q5"])+ missing = missing_weight_variant(models, "trellis/generate", variants, {})+ self.assertEqual((missing or {}).get("id"), "Q4")+ for params in ({"quant": "Q5"}, {"quant": "fp16"}):+ with self.subTest(params=params):+ self.assertIsNone(missing_weight_variant(models, "trellis/generate", variants, params))+ self.assertIsNone(missing_weight_variant(models, "trellis/generate", None, {"quant": "Q4"}))+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_optimize_mesh_ops.py b/apps/forge-desktop/api/tests/test_optimize_mesh_ops.pynew file mode 100644index 000000000..6c702ddb6--- /dev/null+++ b/apps/forge-desktop/api/tests/test_optimize_mesh_ops.py@@ -0,0 +1,207 @@+import tempfile+import unittest+from pathlib import Path+from unittest.mock import patch++from fastapi import HTTPException++from routers import optimize+from services.mesh_ops import (+ MeshOp,+ MeshOpExecutionError,+ MeshOpNotFoundError,+ MeshOpResult,+ MeshOpsRegistry,+)+++class _FakeRegistry:+ def __init__(self, output_path: Path) -> None:+ self.output_path = output_path+ self.calls = []++ def describe(self):+ return [{"id": "repair", "category": "repair", "params_schema": []}]++ def run(self, operation_id, input_path, params, context):+ self.calls.append((operation_id, input_path, params, context))+ output_path = context.output_path or self.output_path+ return MeshOpResult(output_path, {"face_count": 42})+++class OptimizeMeshOpsRouteTests(unittest.TestCase):+ def test_generic_list_and_run_routes_use_the_shared_registry(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ workspace = Path(directory)+ input_path = workspace / "input.glb"+ output_path = workspace / "Workflows" / "output.glb"+ input_path.touch()+ registry = _FakeRegistry(output_path)++ with (+ patch.object(optimize.registry, "WORKSPACE_DIR", workspace),+ patch.object(optimize, "mesh_ops_registry", registry),+ ):+ descriptions = optimize.list_mesh_operations()+ response = optimize.run_mesh_operation(+ "repair",+ optimize.MeshOpRequest(+ path="input.glb",+ params={"fill_holes": False},+ ),+ )++ self.assertEqual(descriptions[0]["id"], "repair")+ self.assertEqual(+ response,+ {+ "path": "Workflows/output.glb",+ "url": "/workspace/Workflows/output.glb",+ "face_count": 42,+ },+ )+ self.assertEqual(registry.calls[0][0:3], (+ "repair",+ input_path,+ {"fill_holes": False},+ ))++ def test_legacy_routes_delegate_with_their_existing_clamps_and_names(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ workspace = Path(directory)+ input_path = workspace / "model.glb"+ fallback_output = workspace / "Workflows" / "unused.glb"+ input_path.touch()+ registry = _FakeRegistry(fallback_output)++ with (+ patch.object(optimize.registry, "WORKSPACE_DIR", workspace),+ patch.object(optimize, "mesh_ops_registry", registry),+ ):+ optimize_response = optimize.optimize_mesh(+ optimize.OptimizeRequest(path="model.glb", target_faces=2)+ )+ smooth_response = optimize.smooth_mesh(+ optimize.SmoothRequest(path="model.glb", iterations=99)+ )++ optimize_call, smooth_call = registry.calls+ self.assertEqual(optimize_call[0], "decimate")+ self.assertEqual(optimize_call[2], {"target_faces": 100})+ self.assertEqual(+ optimize_call[3].output_path,+ workspace / "model_opt100.glb",+ )+ self.assertEqual(smooth_call[0], "smooth")+ self.assertEqual(+ smooth_call[2],+ {"iterations": 20, "lambda_": 0.5, "mode": "laplacian"},+ )+ self.assertEqual(+ smooth_call[3].output_path,+ workspace / "model_smooth20.glb",+ )+ self.assertTrue(smooth_call[3].preserve_visuals)+ self.assertEqual(optimize_response["face_count"], 42)+ self.assertEqual(smooth_response["url"], "/workspace/model_smooth20.glb")++ def test_unknown_generic_operation_is_a_404(self) -> None:+ class MissingRegistry:+ def run(self, operation_id, input_path, params, context):+ raise MeshOpNotFoundError(operation_id)++ with tempfile.TemporaryDirectory() as directory:+ workspace = Path(directory)+ input_path = workspace / "input.glb"+ input_path.touch()+ with (+ patch.object(optimize.registry, "WORKSPACE_DIR", workspace),+ patch.object(optimize, "mesh_ops_registry", MissingRegistry()),+ self.assertRaises(HTTPException) as raised,+ ):+ optimize.run_mesh_operation(+ "missing",+ optimize.MeshOpRequest(path="input.glb"),+ )++ self.assertEqual(raised.exception.status_code, 404)++ def test_generic_run_route_enforces_registry_bounds(self) -> None:+ calls = []++ def operation(input_path, params, context):+ calls.append(params)+ return MeshOpResult(input_path)++ registry = MeshOpsRegistry(+ [+ MeshOp(+ id="bounded",+ label="Bounded",+ params_schema=(+ {+ "id": "amount",+ "type": "int",+ "default": 3,+ "min": 1,+ "max": 5,+ },+ ),+ fn=operation,+ category="test",+ )+ ]+ )++ with tempfile.TemporaryDirectory() as directory:+ workspace = Path(directory)+ input_path = workspace / "input.glb"+ input_path.touch()+ with (+ patch.object(optimize.registry, "WORKSPACE_DIR", workspace),+ patch.object(optimize, "mesh_ops_registry", registry),+ ):+ optimize.run_mesh_operation(+ "bounded",+ optimize.MeshOpRequest(+ path="input.glb",+ params={"amount": 99},+ ),+ )++ self.assertEqual(calls, [{"amount": 5}])++ def test_missing_input_during_execution_is_a_404(self) -> None:+ class MissingInputRegistry:+ def run(self, operation_id, input_path, params, context):+ raise FileNotFoundError(f"Input mesh not found: {input_path}")++ self._assert_operation_error(MissingInputRegistry(), 404)++ def test_backend_execution_failure_is_a_503(self) -> None:+ class FailedBackendRegistry:+ def run(self, operation_id, input_path, params, context):+ raise MeshOpExecutionError("mesh-optimizer exited with code 1")++ self._assert_operation_error(FailedBackendRegistry(), 503)++ def _assert_operation_error(self, registry, expected_status: int) -> None:+ with tempfile.TemporaryDirectory() as directory:+ workspace = Path(directory)+ input_path = workspace / "input.glb"+ input_path.touch()+ with (+ patch.object(optimize.registry, "WORKSPACE_DIR", workspace),+ patch.object(optimize, "mesh_ops_registry", registry),+ self.assertRaises(HTTPException) as raised,+ ):+ optimize.run_mesh_operation(+ "decimate",+ optimize.MeshOpRequest(path="input.glb"),+ )++ self.assertEqual(raised.exception.status_code, expected_status)+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_runner.py b/apps/forge-desktop/api/tests/test_runner.pynew file mode 100644index 000000000..084e3e7b4--- /dev/null+++ b/apps/forge-desktop/api/tests/test_runner.py@@ -0,0 +1,415 @@+import unittest+import os+import io+import sys+import json+import tempfile+import importlib+from unittest.mock import patch+from contextlib import redirect_stdout+from pathlib import Path+++_tmp_ext_dir = tempfile.mkdtemp(prefix="modly-runner-test-")+Path(_tmp_ext_dir, "manifest.json").write_text("{}", encoding="utf-8")+os.environ.setdefault("EXTENSION_DIR", _tmp_ext_dir)++runner = importlib.import_module("runner")+_apply_manifest_metadata = runner._apply_manifest_metadata+_resolve_ready_schema = runner._resolve_ready_schema+_select_node = runner._select_node+++class RunnerTests(unittest.TestCase):+ def test_decode_typed_scene_revalidates_worker_workspace_and_keeps_legacy_image(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ workspace = Path(tmp) / "workspace"+ scene = workspace / "Workflows" / "room"+ scene.mkdir(parents=True)+ manifest = scene / "scene-manifest.json"+ manifest.write_text(json.dumps({+ "schema": "modly.scene-manifest.v1", "sceneRoot": ".", "assets": [],+ }))+ with patch.object(runner, "WORKSPACE_DIR", workspace):+ typed = runner.decode_model_input({"input": {"kind": "scene", "path": str(manifest)}})+ self.assertEqual(typed.kind, "scene")+ self.assertEqual(typed.path, manifest.resolve())+ self.assertEqual(runner.decode_model_input({"image_b64": "aW1hZ2U="}), b"image")+ with self.assertRaises(ValueError):+ runner.decode_model_input({"input": {"kind": "video", "path": str(manifest)}})++ def test_runner_model_envelope_rejects_cross_node_dispatch(self) -> None:+ manifest = {"id": "pixal3d"}+ node = {"id": "worldsculpt"}+ runner.validate_requested_model({"model_id": "pixal3d/worldsculpt"}, manifest, node)+ with self.assertRaisesRegex(ValueError, "does not match"):+ runner.validate_requested_model({"model_id": "pixal3d/generate"}, manifest, node)++ def test_select_node_uses_model_dir_override(self) -> None:+ manifest = {+ "nodes": [+ {"id": "fast", "params_schema": [{"id": "a"}]},+ {"id": "quality", "params_schema": [{"id": "b"}]},+ ]+ }++ node = _select_node(manifest, str(Path("/tmp/ext/quality")))++ self.assertEqual(node["id"], "quality")++ def test_select_node_prefers_explicit_node_id_over_storage_path(self) -> None:+ manifest = {"nodes": [{"id": "fast"}, {"id": "quality"}]}++ node = _select_node(+ manifest,+ str(Path("/tmp/ext/_shared/base")),+ "quality",+ )++ self.assertEqual(node["id"], "quality")++ def test_ready_schema_falls_back_to_selected_node_schema(self) -> None:+ class GenClass:+ @classmethod+ def params_schema(cls):+ raise RuntimeError("not available")++ manifest = {"params_schema": [{"id": "manifest"}]}+ node = {"params_schema": [{"id": "node"}]}++ schema = _resolve_ready_schema(GenClass, node, manifest)++ self.assertEqual(schema, [{"id": "node"}])++ def test_apply_manifest_metadata_prefers_node_specific_values(self) -> None:+ gen = type("Gen", (), {})()+ manifest = {+ "hf_repo": "top/repo",+ "hf_skip_prefixes": ["top/"],+ "download_check": "top/file",+ "params_schema": [{"id": "top"}],+ }+ node = {+ "hf_repo": "node/repo",+ "hf_skip_prefixes": ["node/"],+ "download_check": "node/file",+ "params_schema": [{"id": "node"}],+ }++ _apply_manifest_metadata(gen, manifest, node)++ self.assertEqual(gen.hf_repo, "node/repo")+ self.assertEqual(gen.hf_skip_prefixes, ["node/"])+ self.assertEqual(gen.download_check, "node/file")+ self.assertEqual(gen._params_schema, [{"id": "node"}])++ def test_apply_manifest_metadata_falls_back_to_manifest_when_node_empty(self) -> None:+ gen = type("Gen", (), {})()+ manifest = {+ "hf_repo": "top/repo",+ "hf_skip_prefixes": ["top/"],+ "download_check": "top/file",+ "params_schema": [{"id": "top"}],+ }++ _apply_manifest_metadata(gen, manifest, {})++ self.assertEqual(gen.hf_repo, "top/repo")+ self.assertEqual(gen.hf_skip_prefixes, ["top/"])+ self.assertEqual(gen.download_check, "top/file")+ self.assertEqual(gen._params_schema, [{"id": "top"}])+++class SelectNodeTests(unittest.TestCase):+ def test_returns_empty_dict_when_manifest_has_no_nodes(self) -> None:+ self.assertEqual(_select_node({}, ""), {})++ def test_falls_back_to_first_node_when_override_matches_nothing(self) -> None:+ manifest = {"nodes": [{"id": "a"}, {"id": "b"}]}+ self.assertEqual(_select_node(manifest, str(Path("/tmp/ext/zzz")))["id"], "a")++ def test_returns_first_node_when_no_override(self) -> None:+ manifest = {"nodes": [{"id": "a"}, {"id": "b"}]}+ self.assertEqual(_select_node(manifest, "")["id"], "a")+++class ResolveReadySchemaTests(unittest.TestCase):+ def test_uses_generator_classmethod_when_available(self) -> None:+ class GenClass:+ @classmethod+ def params_schema(cls):+ return [{"id": "from-class"}]++ schema = _resolve_ready_schema(GenClass, {"params_schema": [{"id": "node"}]}, {})+ self.assertEqual(schema, [{"id": "from-class"}])++ def test_falls_back_to_manifest_when_node_has_no_schema(self) -> None:+ class GenClass:+ @classmethod+ def params_schema(cls):+ raise RuntimeError("unavailable")++ schema = _resolve_ready_schema(GenClass, {}, {"params_schema": [{"id": "manifest"}]})+ self.assertEqual(schema, [{"id": "manifest"}])+++class ProtocolTests(unittest.TestCase):+ """recv()/send() implement the newline-delimited JSON wire protocol."""++ def setUp(self) -> None:+ self._stdin = sys.stdin++ def tearDown(self) -> None:+ sys.stdin = self._stdin++ def test_recv_parses_lines_and_skips_blank_lines(self) -> None:+ sys.stdin = io.StringIO('{"a": 1}\n\n \n{"b": 2}\n')+ self.assertEqual(list(runner.recv()), [{"a": 1}, {"b": 2}])++ def test_recv_skips_invalid_json_without_crashing_and_logs_error(self) -> None:+ sys.stdin = io.StringIO('not json\n{"ok": 1}\n')+ out = io.StringIO()+ with redirect_stdout(out):+ messages = list(runner.recv())++ self.assertEqual(messages, [{"ok": 1}])+ logged = [json.loads(line) for line in out.getvalue().splitlines() if line.strip()]+ self.assertTrue(any(+ entry.get("level") == "error" and "invalid JSON" in entry.get("message", "")+ for entry in logged+ ))++ def test_send_writes_single_json_line(self) -> None:+ out = io.StringIO()+ with redirect_stdout(out):+ runner.send({"type": "ready", "params_schema": []})++ written = out.getvalue()+ self.assertTrue(written.endswith("\n"))+ self.assertEqual(written.count("\n"), 1)+ self.assertEqual(json.loads(written), {"type": "ready", "params_schema": []})+++_FAKE_TEXGEN_GENERATOR = '''+from pathlib import Path++INSTANCES = []+++class FakeTexGen:+ """+ Mimics an extension whose texture pipeline is built lazily on first use and+ frees the shape pipeline first to make room for it.++ The first texture setup fails (missing `xatlas`), which is what issue #239+ reports; a later attempt succeeds once the dependency is available.+ """++ def __init__(self, model_dir, outputs_dir):+ self.model_dir = model_dir+ self.outputs_dir = outputs_dir+ self._model = None+ self.load_calls = 0+ self.texgen_attempts = 0+ INSTANCES.append(self)++ def is_loaded(self):+ return self._model is not None++ def load(self):+ self.load_calls += 1+ self._model = lambda image: "mesh"++ def unload(self):+ self._model = None++ def _setup_texgen(self):+ # Free the shape pipeline before building the texture pipeline.+ self._model = None+ self.texgen_attempts += 1+ if self.texgen_attempts == 1:+ raise RuntimeError("No module named 'xatlas'")+ # Texture setup succeeded: shape pipeline comes back.+ self.load()++ def generate(self, image_bytes, params, progress_cb=None, cancel_event=None):+ # Stands in for `self._model(image)` on a generator whose model is gone.+ if self._model is None:+ raise TypeError("'NoneType' object is not callable")+ self._model(image_bytes)+ if params.get("enable_texture"):+ self._setup_texgen()+ return Path("out.glb")+'''+++class _RunnerDriver:+ """Runs runner.main() against a throwaway extension dir."""++ def __init__(self, generator_src: str, generator_class: str) -> None:+ self.ext_dir = Path(tempfile.mkdtemp(prefix="modly-texgen-test-"))+ (self.ext_dir / "generator.py").write_text(generator_src, encoding="utf-8")+ (self.ext_dir / "manifest.json").write_text(+ json.dumps({"id": "demo-ext", "generator_class": generator_class}),+ encoding="utf-8",+ )++ def run(self, actions: list) -> list:+ """Feeds actions on stdin, returns the parsed messages runner emitted."""+ original_ext_dir = runner.EXT_DIR+ original_stdin = sys.stdin+ original_module = sys.modules.pop("generator", None)+ runner.EXT_DIR = self.ext_dir+ sys.stdin = io.StringIO("".join(json.dumps(a) + "\n" for a in actions))+ out = io.StringIO()+ try:+ with redirect_stdout(out):+ runner.main()+ self.generator_module = sys.modules["generator"]+ finally:+ runner.EXT_DIR = original_ext_dir+ sys.stdin = original_stdin+ sys.modules.pop("generator", None)+ if original_module is not None:+ sys.modules["generator"] = original_module+ return [json.loads(line) for line in out.getvalue().splitlines() if line.strip()]+++class RuntimeIdentityTests(unittest.TestCase):+ def test_runner_exposes_selected_identity_independently_of_storage(self):+ from unittest.mock import patch+ driver = _RunnerDriver(_FAKE_TEXGEN_GENERATOR, "FakeTexGen")+ manifest = {"id": "demo-ext", "generator_class": "FakeTexGen",+ "nodes": [{"id": "a"}, {"id": "b"}]}+ (driver.ext_dir / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")+ with patch.object(runner, "_MODEL_ID_OVERRIDE", "demo-ext/b"), \+ patch.object(runner, "_MODEL_NODE_ID_OVERRIDE", "b"), \+ patch.object(runner, "_MODEL_DIR_OVERRIDE", str(driver.ext_dir / "unrelated-storage")):+ driver.run([])+ gen = driver.generator_module.INSTANCES[0]+ self.assertEqual(gen.MODEL_ID, "demo-ext/b")+ self.assertEqual(gen.MODEL_NODE_ID, "b")+ self.assertEqual(gen.model_dir.name, "unrelated-storage")+++class GeneratorLoadedStateTests(unittest.TestCase):+ def test_reports_loaded_state(self) -> None:+ gen = type("Gen", (), {"is_loaded": lambda self: True})()+ self.assertTrue(runner._generator_is_loaded(gen))++ def test_treats_raising_is_loaded_as_not_loaded(self) -> None:+ class Gen:+ def is_loaded(self):+ raise RuntimeError("half-initialised")++ self.assertFalse(runner._generator_is_loaded(Gen()))++ def test_ensure_model_loaded_is_a_noop_when_already_loaded(self) -> None:+ class Gen:+ load_calls = 0++ def is_loaded(self):+ return True++ def load(self):+ self.load_calls += 1++ gen = Gen()+ self.assertFalse(runner._ensure_model_loaded(gen))+ self.assertEqual(gen.load_calls, 0)++ def test_ensure_model_loaded_reloads_when_model_is_gone(self) -> None:+ class Gen:+ def __init__(self):+ self._model = None+ self.load_calls = 0++ def is_loaded(self):+ return self._model is not None++ def load(self):+ self.load_calls += 1+ self._model = object()++ gen = Gen()+ self.assertTrue(runner._ensure_model_loaded(gen))+ self.assertEqual(gen.load_calls, 1)+ self.assertIsNotNone(gen._model)+++class TextureSetupRecoveryTests(unittest.TestCase):+ """+ Regression tests for issue #239: a failed lazy texture setup left the worker+ with _model = None and no recovery path, so every later generation raised+ "TypeError: 'NoneType' object is not callable" until the process was killed.+ """++ def setUp(self) -> None:+ self.driver = _RunnerDriver(_FAKE_TEXGEN_GENERATOR, "FakeTexGen")+ self.texture_run = {+ "action": "generate",+ "image_b64": "",+ "params": {"enable_texture": True},+ }++ def test_worker_recovers_after_failed_texture_setup(self) -> None:+ messages = self.driver.run([+ {"action": "load"},+ dict(self.texture_run, id="run-1"),+ dict(self.texture_run, id="run-2"),+ ])++ by_id = {m.get("id"): m for m in messages if m.get("type") in ("done", "error")}++ # First run fails during texture setup and surfaces the real cause.+ self.assertEqual(by_id["run-1"]["type"], "error")+ self.assertIn("xatlas", by_id["run-1"]["message"])++ # The retry must succeed instead of dying on a None model.+ self.assertEqual(+ by_id["run-2"]["type"], "done",+ msg=f"retry did not recover: {by_id['run-2']}",+ )+ self.assertNotIn("NoneType", json.dumps(by_id["run-2"]))++ # …and the worker's model is genuinely back.+ gen = self.driver.generator_module.INSTANCES[0]+ self.assertIsNotNone(gen._model)+ self.assertTrue(gen.is_loaded())++ def test_failed_run_reports_that_the_model_was_lost(self) -> None:+ messages = self.driver.run([+ {"action": "load"},+ dict(self.texture_run, id="run-1"),+ ])++ error = next(m for m in messages if m.get("type") == "error")+ self.assertIs(error["loaded"], False)++ def test_reload_before_generate_is_logged(self) -> None:+ messages = self.driver.run([+ {"action": "load"},+ dict(self.texture_run, id="run-1"),+ dict(self.texture_run, id="run-2"),+ ])++ logs = [m for m in messages if m.get("type") == "log"]+ self.assertTrue(+ any("reloaded before generating" in m.get("message", "") for m in logs),+ msg=f"expected a reload log, got {logs}",+ )++ def test_successful_run_does_not_reload_the_model(self) -> None:+ messages = self.driver.run([+ {"action": "load"},+ {"action": "generate", "id": "run-1", "image_b64": "", "params": {}},+ ])++ self.assertEqual(+ [m["type"] for m in messages if m.get("id") == "run-1"], ["done"]+ )+ self.assertEqual(self.driver.generator_module.INSTANCES[0].load_calls, 1)+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_scene_generation.py b/apps/forge-desktop/api/tests/test_scene_generation.pynew file mode 100644index 000000000..90333ca5b--- /dev/null+++ b/apps/forge-desktop/api/tests/test_scene_generation.py@@ -0,0 +1,339 @@+import asyncio+import json+import tempfile+import threading+import unittest+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+from unittest.mock import patch++from fastapi import BackgroundTasks, HTTPException+from pydantic import ValidationError++import routers.generation as generation+import services.generator_registry as registry+from schemas.generation import GenerateFromArtifactRequest+++class _Registry:+ def __init__(self):+ self.switched = False+ def get_generator(self, model_id): return object()+ def get_manifest(self, model_id): return {"input": "scene"}+ def switch_model(self, model_id): self.switched = True+ def assert_weight_variant_installed(self, params, model_id=None): pass+++class SceneGenerationTests(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.workspace = Path(self.tmp.name) / "workspace"+ self.scene = self.workspace / "Workflows" / "room"+ self.scene.mkdir(parents=True)+ self.manifest = self.scene / "scene-manifest.json"+ self.manifest.write_text(json.dumps({"schema": "modly.scene-manifest.v1", "sceneRoot": ".", "assets": []}))+ self.registry = _Registry()+ self.patches = [patch.object(generation, "generator_registry", self.registry), patch.object(registry, "WORKSPACE_DIR", self.workspace)]+ for item in self.patches: item.start()++ def tearDown(self):+ for item in reversed(self.patches): item.stop()+ generation._jobs.clear(); generation._cancel_events.clear(); generation._cancelled.clear(); generation._completed_at.clear(); generation._job_generators.clear()+ self.tmp.cleanup()++ def test_generic_route_queues_typed_scene_and_strips_reserved_params(self):+ tasks = BackgroundTasks()+ result = asyncio.run(generation.generate_from_artifact(GenerateFromArtifactRequest(+ input_kind="scene", input_path="Workflows/room", model_id="demo/scene",+ params={"artifact_path": "/etc/passwd", "input_kind": "image", "quality": "high"},+ ), tasks))+ queued = tasks.tasks[0]+ self.assertEqual(queued.args[1].kind, "scene")+ self.assertEqual(queued.args[1].path, self.manifest.resolve())+ self.assertEqual(queued.args[2]["scene_manifest_path"], str(self.manifest.resolve()))+ self.assertNotIn("artifact_path", queued.args[2])+ self.assertNotIn("input_kind", queued.args[2])+ self.assertEqual(queued.args[5], "demo/scene")+ self.assertEqual(result["job_id"], queued.args[0])+ self.assertFalse(self.registry.switched)++ def test_generic_route_rejects_unsupported_kind_and_model_mismatch(self):+ for kind in ("video", "capture", "image"):+ with self.subTest(kind=kind), self.assertRaises(ValidationError):+ GenerateFromArtifactRequest(+ input_kind=kind, input_path="Workflows/room", model_id="demo/scene")+ self.registry.get_manifest = lambda _model_id: {"input": "image"}+ with self.assertRaises(HTTPException) as caught:+ asyncio.run(generation.generate_from_artifact(GenerateFromArtifactRequest(+ input_kind="scene", input_path="Workflows/room", model_id="demo/image"), BackgroundTasks()))+ self.assertEqual(caught.exception.status_code, 400)++ def test_rejects_traversal_before_switch_or_queue(self):+ with self.assertRaises(HTTPException):+ asyncio.run(generation.generate_from_artifact(GenerateFromArtifactRequest(+ input_kind="scene", input_path="../outside", model_id="demo/scene"), BackgroundTasks()))+ self.assertFalse(self.registry.switched)++ def test_queued_scene_job_is_pinned_to_requested_model(self):+ calls = []++ class Generator:+ outputs_dir = None+ def is_loaded(self): return True+ def generate_artifact(self, kind, path, params, progress_cb, cancel_event=None):+ calls.append(("model-a", kind, path))+ output = Path(self.outputs_dir) / "result.glb"+ output.write_bytes(b"glb")+ return output++ generator = Generator()+ registry_stub = type("Registry", (), {+ "assert_weight_variant_installed": lambda self, params, model_id=None: None,+ "model_status": lambda self, model_id: {"name": model_id, "downloaded": True, "loaded": True},+ "get_generator": lambda self, model_id: generator if model_id == "demo/a" else (_ for _ in ()).throw(ValueError(f"Unknown model ID: {model_id}")),+ "activate_ready_generator": lambda self, model_id: generator if model_id == "demo/a" else (_ for _ in ()).throw(ValueError(f"Unknown model ID: {model_id}")),+ "get_active": lambda self: (_ for _ in ()).throw(AssertionError("mutable active model must not be used")),+ })()+ job_id = "pinned-scene"+ generation._jobs[job_id] = generation.JobStatus(job_id=job_id, status="pending", progress=0)+ generation._cancel_events[job_id] = __import__("threading").Event()+ with patch.object(generation, "generator_registry", registry_stub):+ asyncio.run(generation._run_generation(+ job_id, generation.TypedArtifactInput("scene", self.manifest.resolve()), {},+ "Workflows", "mesh", "demo/a",+ ))+ self.assertEqual(calls[0][0], "model-a")+ self.assertEqual(generation._jobs[job_id].status, "done")++ def test_missing_pinned_model_fails_actionably(self):+ registry_stub = type("Registry", (), {+ "assert_weight_variant_installed": lambda self, params, model_id=None: None,+ "model_status": lambda self, model_id: {"name": model_id, "downloaded": True, "loaded": False},+ "get_generator": lambda self, model_id: object(),+ "activate_ready_generator": lambda self, model_id: (_ for _ in ()).throw(ValueError(f"Unknown model ID: {model_id}")),+ "get_active": lambda self: (_ for _ in ()).throw(AssertionError("must not use active model")),+ })()+ job_id = "missing-scene"+ generation._jobs[job_id] = generation.JobStatus(job_id=job_id, status="pending", progress=0)+ generation._cancel_events[job_id] = __import__("threading").Event()+ with patch.object(generation, "generator_registry", registry_stub):+ asyncio.run(generation._run_generation(+ job_id, generation.TypedArtifactInput("scene", self.manifest.resolve()), {},+ "Workflows", "mesh", "demo/missing",+ ))+ self.assertEqual(generation._jobs[job_id].status, "error")+ self.assertIn("Unknown model ID: demo/missing", generation._jobs[job_id].error)++ def test_interleaved_pinned_jobs_serialize_model_lifecycle_and_cancel_exact_job(self):+ class Proc:+ def __init__(self, owner):+ self.owner = owner+ self.alive = True+ def poll(self):+ return None if self.alive else 0+ def kill(self):+ self.alive = False+ self.owner.killed = True++ class Generator:+ def __init__(self, model_id):+ self.model_id = model_id+ self.outputs_dir = None+ self.loaded = False+ self.started = threading.Event()+ self.killed = False+ self._loaded = True+ self._proc = Proc(self)+ def is_loaded(self): return self.loaded+ def is_downloaded(self): return True+ def load(self): self.loaded = True+ def unload(self): self.loaded = False+ def generate_artifact(self, kind, path, params, progress_cb, cancel_event=None):+ self.started.set()+ if self.model_id == "demo/a":+ if cancel_event is None or not cancel_event.wait(2):+ raise AssertionError("first job was not cancelled")+ raise generation.GenerationCancelled()+ output = Path(self.outputs_dir) / "result.glb"+ output.write_bytes(b"glb")+ return output++ class Registry:+ def __init__(self):+ self.generators = {model_id: Generator(model_id) for model_id in ("demo/a", "demo/b")}+ self.active_id = "demo/a"+ def assert_weight_variant_installed(self, params, model_id=None): pass+ def get_generator(self, model_id): return self.generators[model_id]+ def model_status(self, model_id):+ gen = self.generators[model_id]+ return {"name": model_id, "downloaded": True, "loaded": gen.loaded}+ def switch_model(self, model_id):+ if model_id != self.active_id:+ self.generators[self.active_id].unload()+ self.active_id = model_id+ def activate_ready_generator(self, model_id):+ self.switch_model(model_id)+ gen = self.generators[model_id]+ gen.load()+ if sum(candidate.loaded for candidate in self.generators.values()) != 1:+ raise AssertionError("more than one generator is resident")+ return gen+ def get_active(self): raise AssertionError("pinned jobs must not consult mutable active state")++ registry_stub = Registry()+ # Reproduce the request interleaving: A switches first, then B switches+ # before either background task has started.+ registry_stub.switch_model("demo/a")+ registry_stub.switch_model("demo/b")+ for job_id in ("job-a", "job-b"):+ generation._jobs[job_id] = generation.JobStatus(job_id=job_id, status="pending", progress=0)+ generation._cancel_events[job_id] = threading.Event()++ async def run_both():+ first = asyncio.create_task(generation._run_generation(+ "job-a", generation.TypedArtifactInput("scene", self.manifest.resolve()), {},+ "Workflows", "mesh", "demo/a",+ ))+ second = asyncio.create_task(generation._run_generation(+ "job-b", generation.TypedArtifactInput("scene", self.manifest.resolve()), {},+ "Workflows", "mesh", "demo/b",+ ))+ started = await asyncio.to_thread(registry_stub.generators["demo/a"].started.wait, 1)+ self.assertTrue(started)+ await asyncio.sleep(0.05)+ self.assertFalse(registry_stub.generators["demo/b"].started.is_set())+ await generation.cancel_job("job-a")+ await asyncio.gather(first, second)++ with patch.object(generation, "generator_registry", registry_stub):+ asyncio.run(run_both())++ self.assertTrue(registry_stub.generators["demo/a"].killed)+ self.assertFalse(registry_stub.generators["demo/b"].killed)+ self.assertEqual(generation._jobs["job-a"].status, "cancelled")+ self.assertEqual(generation._jobs["job-b"].status, "done")+ self.assertEqual(registry_stub.active_id, "demo/b")+ self.assertFalse(registry_stub.generators["demo/a"].loaded)+ self.assertTrue(registry_stub.generators["demo/b"].loaded)++ def test_cancelling_queued_generation_does_not_wedge_later_jobs(self):+ release_first = threading.Event()+ first_started = threading.Event()++ class Generator:+ outputs_dir = None++ def __init__(self):+ self.calls = 0++ def generate(self, image_bytes, params, progress_cb, cancel_event=None):+ self.calls += 1+ call_number = self.calls+ if call_number == 1:+ first_started.set()+ if not release_first.wait(2):+ raise AssertionError("first generation was not released")+ output = Path(self.outputs_dir) / f"result-{call_number}.glb"+ output.write_bytes(b"glb")+ return output++ generator = Generator()+ registry_stub = type("Registry", (), {+ "assert_weight_variant_installed": lambda self, params, model_id=None: None,+ "get_generator": lambda self, model_id: generator,+ "model_status": lambda self, model_id: {+ "name": model_id, "downloaded": True, "loaded": True,+ },+ "activate_ready_generator": lambda self, model_id: generator,+ "get_active": lambda self: (_ for _ in ()).throw(+ AssertionError("pinned jobs must not use mutable active state")+ ),+ })()+ for job_id in ("blocking", "cancelled-waiter", "after-cancel"):+ generation._jobs[job_id] = generation.JobStatus(+ job_id=job_id, status="pending", progress=0,+ )+ generation._cancel_events[job_id] = threading.Event()++ async def run_scenario():+ first = asyncio.create_task(generation._run_generation(+ "blocking", b"image", {}, "Workflows", "mesh", "demo/a",+ ))+ started = await asyncio.to_thread(first_started.wait, 1)+ self.assertTrue(started)++ queued = asyncio.create_task(generation._run_generation(+ "cancelled-waiter", b"image", {}, "Workflows", "mesh", "demo/b",+ ))+ await asyncio.sleep(0)+ queued.cancel()+ with self.assertRaises(asyncio.CancelledError):+ await queued++ release_first.set()+ await asyncio.wait_for(first, 1)+ await asyncio.wait_for(generation._run_generation(+ "after-cancel", b"image", {}, "Workflows", "mesh", "demo/c",+ ), 1)++ with patch.object(generation, "generator_registry", registry_stub):+ asyncio.run(run_scenario())++ self.assertEqual(generation._jobs["cancelled-waiter"].status, "cancelled")+ self.assertEqual(generation._jobs["after-cancel"].status, "done")+ self.assertEqual(generator.calls, 2)++ def test_pinned_jobs_do_not_starve_small_default_executor(self):+ class Generator:+ outputs_dir = None++ def __init__(self):+ self.calls = 0++ def generate(self, image_bytes, params, progress_cb, cancel_event=None):+ self.calls += 1+ output = Path(self.outputs_dir) / f"result-{self.calls}.glb"+ output.write_bytes(b"glb")+ return output++ generator = Generator()+ registry_stub = type("Registry", (), {+ "assert_weight_variant_installed": lambda self, params, model_id=None: None,+ "get_generator": lambda self, model_id: generator,+ "model_status": lambda self, model_id: {+ "name": model_id, "downloaded": True, "loaded": True,+ },+ "activate_ready_generator": lambda self, model_id: generator,+ "get_active": lambda self: (_ for _ in ()).throw(+ AssertionError("pinned jobs must not use mutable active state")+ ),+ })()+ job_ids = ("small-pool-a", "small-pool-b", "small-pool-c")+ for job_id in job_ids:+ generation._jobs[job_id] = generation.JobStatus(+ job_id=job_id, status="pending", progress=0,+ )+ generation._cancel_events[job_id] = threading.Event()++ default_executor = ThreadPoolExecutor(max_workers=2)++ async def run_scenario():+ asyncio.get_running_loop().set_default_executor(default_executor)+ await asyncio.wait_for(asyncio.gather(*(+ generation._run_generation(+ job_id, b"image", {}, "Workflows", "mesh", f"demo/{job_id}",+ )+ for job_id in job_ids+ )), 2)++ try:+ with patch.object(generation, "generator_registry", registry_stub):+ asyncio.run(run_scenario())+ finally:+ default_executor.shutdown(wait=True)++ self.assertEqual(generator.calls, 3)+ self.assertEqual(+ [generation._jobs[job_id].status for job_id in job_ids],+ ["done", "done", "done"],+ )diff --git a/apps/forge-desktop/api/tests/test_scene_input.py b/apps/forge-desktop/api/tests/test_scene_input.pynew file mode 100644index 000000000..aec4bc5ec--- /dev/null+++ b/apps/forge-desktop/api/tests/test_scene_input.py@@ -0,0 +1,93 @@+import json+import sys+import tempfile+import unittest+from pathlib import Path++from services.scene_input import validate_scene_input, revalidate_scene_manifest+++class SceneInputTests(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.workspace = Path(self.tmp.name) / "workspace"+ self.scene = self.workspace / "Workflows" / "room"+ self.scene.mkdir(parents=True)+ (self.scene / "model.glb").write_bytes(b"mesh")+ self.manifest = self.scene / "scene-manifest.json"+ self.manifest.write_text(json.dumps({+ "schema": "modly.scene-manifest.v1",+ "sceneRoot": ".",+ "assets": [{"path": "model.glb"}],+ }))++ def tearDown(self):+ self.tmp.cleanup()++ def test_directory_and_manifest_are_canonical_paths(self):+ expected = self.manifest.resolve()+ self.assertEqual(validate_scene_input(self.workspace, "Workflows/room"), expected)+ self.assertEqual(validate_scene_input(self.workspace, "Workflows/room/scene-manifest.json"), expected)+ self.assertEqual(revalidate_scene_manifest(self.workspace, expected), expected)++ def test_rejects_traversal_absolute_encoded_and_non_manifest_json(self):+ for path in ("../outside", "/etc/passwd", "C:/outside", "Workflows/room/../room", "Workflows/room/other.json", "Workflows/%2e%2e"):+ with self.subTest(path=path), self.assertRaises(ValueError):+ validate_scene_input(self.workspace, path)++ def test_rejects_symlink_escape_when_supported(self):+ outside = Path(self.tmp.name) / "outside"+ outside.mkdir()+ (outside / "scene-manifest.json").write_text(self.manifest.read_text())+ try:+ (self.workspace / "Workflows" / "link").symlink_to(outside, target_is_directory=True)+ except OSError as exc:+ self.skipTest(f"directory symlinks are unavailable on this host: {exc}")+ with self.assertRaises(ValueError):+ validate_scene_input(self.workspace, "Workflows/link")++ @unittest.skipUnless(sys.platform == "win32", "directory junctions are Windows-only")+ def test_rejects_junction_escape_on_windows(self):+ # Junctions need no privilege (unlike symlinks), so they are the+ # realistic escape on Windows and keep the reparse-point check covered.+ import _winapi++ outside = Path(self.tmp.name) / "outside"+ outside.mkdir()+ (outside / "scene-manifest.json").write_text(self.manifest.read_text())+ (outside / "model.glb").write_bytes(b"mesh")+ _winapi.CreateJunction(str(outside), str(self.workspace / "Workflows" / "link"))++ with self.assertRaises(ValueError):+ validate_scene_input(self.workspace, "Workflows/link")++ data = json.loads(self.manifest.read_text())+ data["assets"] = [{"workspacePath": "Workflows/link/model.glb"}]+ self.manifest.write_text(json.dumps(data))+ with self.assertRaises(ValueError):+ validate_scene_input(self.workspace, "Workflows/room")++ def test_rejects_missing_assets_and_oversized_manifest(self):+ data = json.loads(self.manifest.read_text())+ data["assets"] = [{"path": "missing.glb"}]+ self.manifest.write_text(json.dumps(data))+ with self.assertRaises(ValueError):+ validate_scene_input(self.workspace, "Workflows/room")++ self.manifest.write_text(" " * (1024 * 1024 + 1))+ with self.assertRaises(ValueError):+ validate_scene_input(self.workspace, "Workflows/room")++ def test_rejects_malformed_manifest_and_asset_paths(self):+ original = json.loads(self.manifest.read_text())+ for patch in (+ {"schema": "wrong"},+ {"assets": "bad"},+ {"assets": [{"path": "../escape.glb"}]},+ {"preview": {"image": None}},+ {"initialView": {"position": [0, 0, 0], "target": [0, 0, 0]}},+ ):+ with self.subTest(patch=patch):+ self.manifest.write_text(json.dumps({**original, **patch}))+ with self.assertRaises(ValueError):+ validate_scene_input(self.workspace, "Workflows/room")diff --git a/apps/forge-desktop/api/tests/test_stdio_utf8.py b/apps/forge-desktop/api/tests/test_stdio_utf8.pynew file mode 100644index 000000000..a18e8a9cd--- /dev/null+++ b/apps/forge-desktop/api/tests/test_stdio_utf8.py@@ -0,0 +1,58 @@+import io+import sys+import unittest+from unittest.mock import patch++from services.stdio_utf8 import ensure_utf8_stdio+++class _RecordingStream:+ def __init__(self) -> None:+ self.reconfigure_calls: list[dict] = []++ def reconfigure(self, **kwargs) -> None:+ self.reconfigure_calls.append(kwargs)+++class StdioUtf8Tests(unittest.TestCase):+ def test_reconfigures_all_streams_to_utf8(self) -> None:+ fake = _RecordingStream()+ with (+ patch.object(sys, "stdin", fake),+ patch.object(sys, "stdout", fake),+ patch.object(sys, "stderr", fake),+ ):+ ensure_utf8_stdio()++ self.assertEqual(+ fake.reconfigure_calls,+ [+ {"encoding": "utf-8", "errors": "replace"},+ {"encoding": "utf-8", "errors": "replace"},+ {"encoding": "utf-8", "errors": "replace"},+ ],+ )++ def test_skips_streams_without_reconfigure_without_raising(self) -> None:+ with (+ patch.object(sys, "stdin", io.StringIO()),+ patch.object(sys, "stdout", io.StringIO()),+ patch.object(sys, "stderr", io.StringIO()),+ ):+ ensure_utf8_stdio() # must not raise++ def test_ignores_reconfigure_errors(self) -> None:+ class _FailingStream:+ def reconfigure(self, **kwargs):+ raise ValueError("closed stream")++ with (+ patch.object(sys, "stdin", _FailingStream()),+ patch.object(sys, "stdout", _FailingStream()),+ patch.object(sys, "stderr", _FailingStream()),+ ):+ ensure_utf8_stdio() # must not raise+++if __name__ == "__main__":+ unittest.main()\ No newline at end of filediff --git a/apps/forge-desktop/api/tests/test_workflow_runs_lifecycle.py b/apps/forge-desktop/api/tests/test_workflow_runs_lifecycle.pynew file mode 100644index 000000000..474335739--- /dev/null+++ b/apps/forge-desktop/api/tests/test_workflow_runs_lifecycle.py@@ -0,0 +1,204 @@+import asyncio+import tempfile+import threading+import time+import unittest+from pathlib import Path++from fastapi import BackgroundTasks++import routers.generation as generation+import routers.workflow_runs as workflow_runs+import services.generator_registry as registry_module+from schemas.generation import JobStatus+++class _FakeUpload:+ """Minimal UploadFile stand-in: an image content-type and readable bytes."""++ def __init__(self, content_type: str = "image/png", data: bytes = b"\x89PNG\r\n") -> None:+ self.content_type = content_type+ self._data = data++ async def read(self) -> bytes:+ return self._data+++class _FakeRegistry:+ """Accepts any model id and exposes the attrs cancel_run pokes at."""++ _generators: dict = {}+ _active_id = None++ def get_generator(self, model_id: str) -> object:+ return object()++ def get_manifest(self, model_id: str) -> dict:+ return {"output": "mesh"}++ def switch_model(self, model_id: str) -> None:+ pass+++def _clear_job_stores() -> None:+ for store in (+ generation._jobs,+ generation._cancel_events,+ generation._cancelled,+ generation._completed_at,+ generation._job_generators,+ ):+ store.clear()+++class WorkflowRunJobLifecycleTests(unittest.TestCase):+ """The headless /workflow-runs surface shares the job dicts with /generate,+ so it must take part in the same TTL purge — otherwise long-running+ automation leaks a JobStatus + Event per run forever."""++ def setUp(self) -> None:+ self._prev = workflow_runs.generator_registry+ workflow_runs.generator_registry = _FakeRegistry()+ _clear_job_stores()++ def tearDown(self) -> None:+ workflow_runs.generator_registry = self._prev+ _clear_job_stores()++ def test_create_run_purges_terminal_jobs_past_ttl(self) -> None:+ stale = "stale-run"+ generation._jobs[stale] = JobStatus(job_id=stale, status="done", progress=100)+ generation._cancel_events[stale] = threading.Event()+ generation._completed_at[stale] = time.monotonic() - generation._JOB_TTL - 1++ background = BackgroundTasks()+ asyncio.run(+ workflow_runs.create_run_from_image(+ background,+ image=_FakeUpload(),+ model_id="sf3d",+ collection="Default",+ params="{}",+ )+ )++ # Before the fix create_run_from_image never purged, so the stale job lingered.+ self.assertNotIn(stale, generation._jobs)+ self.assertNotIn(stale, generation._completed_at)+ self.assertNotIn(stale, generation._cancel_events)++ def test_cancel_run_records_completion_so_it_can_be_purged(self) -> None:+ run_id = "run-1"+ generation._jobs[run_id] = JobStatus(job_id=run_id, status="running", progress=10)+ generation._cancel_events[run_id] = threading.Event()++ asyncio.run(workflow_runs.cancel_run(run_id))++ self.assertEqual(generation._jobs[run_id].status, "cancelled")+ # Without a _completed_at stamp the purge sweep can never evict a cancelled run.+ self.assertIn(run_id, generation._completed_at)++ def test_workflow_and_generate_routes_share_exact_model_queue_and_cancellation(self) -> None:+ class Proc:+ def __init__(self, owner):+ self.owner = owner+ self.alive = True+ def poll(self): return None if self.alive else 0+ def kill(self):+ self.alive = False+ self.owner.killed = True++ class Generator:+ def __init__(self, model_id):+ self.model_id = model_id+ self.outputs_dir = None+ self.loaded = False+ self.started = threading.Event()+ self.killed = False+ self._loaded = True+ self._proc = Proc(self)+ def is_loaded(self): return self.loaded+ def load(self): self.loaded = True+ def unload(self): self.loaded = False+ def generate(self, image_bytes, params, progress_cb, cancel_event=None):+ self.started.set()+ if self.model_id == "demo/workflow":+ if cancel_event is None or not cancel_event.wait(2):+ raise AssertionError("workflow job was not cancelled")+ raise generation.GenerationCancelled()+ output = Path(self.outputs_dir) / "result.glb"+ output.write_bytes(b"glb")+ return output++ class Registry:+ def __init__(self):+ ids = ("demo/workflow", "demo/generate")+ self.generators = {model_id: Generator(model_id) for model_id in ids}+ self.active_id = "demo/generate"+ def assert_weight_variant_installed(self, params, model_id=None): pass+ def get_generator(self, model_id): return self.generators[model_id]+ def get_manifest(self, model_id): return {"output": "mesh"}+ def model_status(self, model_id):+ gen = self.generators[model_id]+ return {"name": model_id, "downloaded": True, "loaded": gen.loaded}+ def activate_ready_generator(self, model_id):+ if model_id != self.active_id:+ self.generators[self.active_id].unload()+ self.active_id = model_id+ gen = self.generators[model_id]+ gen.load()+ if sum(candidate.loaded for candidate in self.generators.values()) != 1:+ raise AssertionError("more than one generator is resident")+ return gen+ def get_active(self): raise AssertionError("queued routes must use their pinned model id")++ fake_registry = Registry()+ previous_generation_registry = generation.generator_registry+ previous_workflow_registry = workflow_runs.generator_registry+ previous_workspace = registry_module.WORKSPACE_DIR+ with tempfile.TemporaryDirectory() as tmp:+ registry_module.WORKSPACE_DIR = Path(tmp)+ generation.generator_registry = fake_registry+ workflow_runs.generator_registry = fake_registry++ async def run_cross_route_jobs():+ workflow_background = BackgroundTasks()+ workflow_response = await workflow_runs.create_run_from_image(+ workflow_background, _FakeUpload(), "demo/workflow", "Workflows", "{}",+ )+ generate_background = BackgroundTasks()+ generate_response = await generation.generate_from_image(+ generate_background, _FakeUpload(), "demo/generate", "Workflows",+ "quad", False, 1024, "{}",+ )+ self.assertEqual(workflow_background.tasks[0].args[5], "demo/workflow")+ self.assertEqual(generate_background.tasks[0].args[5], "demo/generate")++ first = asyncio.create_task(workflow_background.tasks[0]())+ second = asyncio.create_task(generate_background.tasks[0]())+ started = await asyncio.to_thread(+ fake_registry.generators["demo/workflow"].started.wait, 1,+ )+ self.assertTrue(started)+ await asyncio.sleep(0.05)+ self.assertFalse(fake_registry.generators["demo/generate"].started.is_set())+ await workflow_runs.cancel_run(workflow_response["run_id"])+ await asyncio.gather(first, second)+ return workflow_response["run_id"], generate_response["job_id"]++ try:+ workflow_job_id, generate_job_id = asyncio.run(run_cross_route_jobs())+ finally:+ generation.generator_registry = previous_generation_registry+ workflow_runs.generator_registry = previous_workflow_registry+ registry_module.WORKSPACE_DIR = previous_workspace++ self.assertTrue(fake_registry.generators["demo/workflow"].killed)+ self.assertFalse(fake_registry.generators["demo/generate"].killed)+ self.assertEqual(generation._jobs[workflow_job_id].status, "cancelled")+ self.assertEqual(generation._jobs[generate_job_id].status, "done")+ self.assertEqual(fake_registry.active_id, "demo/generate")+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/tests/test_workflow_runs_router.py b/apps/forge-desktop/api/tests/test_workflow_runs_router.pynew file mode 100644index 000000000..7537a4844--- /dev/null+++ b/apps/forge-desktop/api/tests/test_workflow_runs_router.py@@ -0,0 +1,156 @@+import asyncio+import unittest++from fastapi import BackgroundTasks, HTTPException++import routers.workflow_runs as workflow_runs+from routers.generation import sanitize_collection+++class _FakeUpload:+ """Minimal stand-in for UploadFile: an image content-type and readable bytes."""++ def __init__(self, content_type: str = "image/png", data: bytes = b"\x89PNG\r\n") -> None:+ self.content_type = content_type+ self._data = data++ async def read(self) -> bytes:+ return self._data+++class _FakeRegistry:+ """Accepts any model id so the route reaches the point where it files the run."""++ def get_generator(self, model_id: str) -> object:+ return object()++ def get_manifest(self, model_id: str) -> dict:+ return {"output": "mesh"}++ def switch_model(self, model_id: str) -> None:+ pass+++class SanitizeCollectionTests(unittest.TestCase):+ def test_keeps_a_plain_name_trimmed(self) -> None:+ self.assertEqual(sanitize_collection(" Exports "), "Exports")++ def test_empty_or_blank_falls_back_to_default(self) -> None:+ self.assertEqual(sanitize_collection(""), "Default")+ self.assertEqual(sanitize_collection(" "), "Default")++ def test_path_and_wildcard_characters_fall_back_to_default(self) -> None:+ # Any of these would let the name escape the workspace root or fail to create on+ # Windows, so the whole name is refused rather than partly scrubbed.+ for name in ("../evil", "a/b", "a\\b", "a:b", "a*b", "a?b", 'a"b', "a<b", "a>b", "a|b"):+ self.assertEqual(sanitize_collection(name), "Default", name)++ def test_bare_dot_dot_falls_back_to_default(self) -> None:+ # ".." contains none of the blocked characters above, so a character blocklist alone+ # lets it through -- and WORKSPACE_DIR / ".." resolves to the workspace's *parent*,+ # writing the generated mesh outside the sandboxed root. Containment must be checked+ # against the resolved path, not just the spelling.+ self.assertEqual(sanitize_collection(".."), "Default")++ def test_trailing_dots_fall_back_to_default(self) -> None:+ # Windows silently drops trailing dots from the folder it actually creates, so+ # "Exports..." and "Exports" would otherwise land in the very same physical directory+ # -- two collections the caller thinks are distinct merging their output on disk.+ # (A trailing space is already normalized away by the .strip() above, consistently.)+ for name in ("Exports.", "Exports..", "..."):+ self.assertEqual(sanitize_collection(name), "Default", name)+++class CreateRunCollectionTests(unittest.TestCase):+ """The canonical /workflow-runs/from-image must file a run where the caller asked (#238)."""++ def setUp(self) -> None:+ self._previous = workflow_runs.generator_registry+ workflow_runs.generator_registry = _FakeRegistry()++ def tearDown(self) -> None:+ workflow_runs.generator_registry = self._previous++ def _collection_forwarded(self, collection: str) -> str:+ background = BackgroundTasks()+ asyncio.run(+ workflow_runs.create_run_from_image(+ background,+ image=_FakeUpload(),+ model_id="sf3d",+ collection=collection,+ params="{}",+ )+ )+ # add_task(_run_generation, ..., collection, output_kind, model_id)+ return background.tasks[0].args[3]++ def test_collection_is_forwarded_to_the_run(self) -> None:+ # The whole point of #238: a run driven over REST/MCP can land in a folder the Library+ # indexes, instead of always being filed under the hardcoded "Default".+ self.assertEqual(self._collection_forwarded("Exports"), "Exports")++ def test_a_blank_collection_becomes_default(self) -> None:+ self.assertEqual(self._collection_forwarded(" "), "Default")++ def test_a_traversing_collection_is_neutralized(self) -> None:+ # The name becomes a workspace subfolder, so a path-separator name must never survive.+ self.assertEqual(self._collection_forwarded("../../etc"), "Default")+++class _SwitchTrackingRegistry(_FakeRegistry):+ """Records whether switch_model ran, to prove a rejected request never reaches it."""++ def __init__(self) -> None:+ self.switched = False++ def switch_model(self, model_id: str) -> None:+ self.switched = True+++class CreateRunRemeshValidationTests(unittest.TestCase):+ """/generate/from-image rejects an invalid remesh with a 400; this endpoint must too."""++ def setUp(self) -> None:+ self._previous = workflow_runs.generator_registry+ workflow_runs.generator_registry = _FakeRegistry()++ def tearDown(self) -> None:+ workflow_runs.generator_registry = self._previous++ def test_invalid_remesh_is_rejected(self) -> None:+ background = BackgroundTasks()+ with self.assertRaises(HTTPException) as ctx:+ asyncio.run(+ workflow_runs.create_run_from_image(+ background,+ image=_FakeUpload(),+ model_id="sf3d",+ collection="Default",+ params='{"remesh": "garbage"}',+ )+ )+ self.assertEqual(ctx.exception.status_code, 400)++ def test_invalid_remesh_is_rejected_before_switching_the_active_model(self) -> None:+ # switch_model() unloads whatever generator is currently active (a blocking call for+ # subprocess-backed extensions), so a request doomed to a 400 anyway must not pay for+ # -- or force a reload after -- evicting it.+ registry = _SwitchTrackingRegistry()+ workflow_runs.generator_registry = registry+ background = BackgroundTasks()+ with self.assertRaises(HTTPException):+ asyncio.run(+ workflow_runs.create_run_from_image(+ background,+ image=_FakeUpload(),+ model_id="sf3d",+ collection="Default",+ params='{"remesh": "garbage"}',+ )+ )+ self.assertFalse(registry.switched)+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/api/texture_baker/README.md b/apps/forge-desktop/api/texture_baker/README.mdnew file mode 100644index 000000000..d7bde117f--- /dev/null+++ b/apps/forge-desktop/api/texture_baker/README.md@@ -0,0 +1,26 @@+# Texture baker++Small texture baker which rasterizes barycentric coordinates to a tensor.+It also implements an interpolation module which can be used to bake attributes to textures then.++## Usage++The baker can quickly bake vertex attributes to the a texture atlas based on the UV coordinates.+It supports baking on the CPU and GPU.++```python+from texture_baker import TextureBaker++mesh = ...+uv = mesh.uv # num_vertex, 2+triangle_idx = mesh.faces # num_faces, 3+vertices = mesh.vertices # num_vertex, 3++tb = TextureBaker()+# First get the barycentric coordinates+rast = tb.rasterize(+ uv=uv, face_indices=triangle_idx, bake_resolution=1024+)+# Then interpolate vertex attributes+position_bake = tb.interpolate(attr=vertices, rast=rast, face_indices=triangle_idx)+```diff --git a/apps/forge-desktop/api/texture_baker/requirements.txt b/apps/forge-desktop/api/texture_baker/requirements.txtnew file mode 100644index 000000000..af3149eb4--- /dev/null+++ b/apps/forge-desktop/api/texture_baker/requirements.txt@@ -0,0 +1,2 @@+torch+numpydiff --git a/apps/forge-desktop/api/texture_baker/setup.py b/apps/forge-desktop/api/texture_baker/setup.pynew file mode 100644index 000000000..e5158cb24--- /dev/null+++ b/apps/forge-desktop/api/texture_baker/setup.py@@ -0,0 +1,159 @@+import glob+import os+import platform++import torch+from setuptools import find_packages, setup+from torch.utils.cpp_extension import (+ CUDA_HOME,+ BuildExtension,+ CppExtension,+ CUDAExtension,+)++library_name = "texture_baker"++IS_WINDOWS = platform.system() == "Windows"+IS_MACOS = platform.system() == "Darwin"+++def get_extensions():+ debug_mode = os.getenv("DEBUG", "0") == "1"+ use_cuda = os.getenv("USE_CUDA", "1" if torch.cuda.is_available() else "0") == "1"+ use_metal = (+ os.getenv("USE_METAL", "1" if torch.backends.mps.is_available() else "0") == "1"+ )+ use_native_arch = os.getenv("USE_NATIVE_ARCH", "1") == "1"+ if debug_mode:+ print("Compiling in debug mode")++ use_cuda = use_cuda and CUDA_HOME is not None+ extension = CUDAExtension if use_cuda else CppExtension++ is_hip_extension = True if ((os.environ.get('ROCM_HOME') is not None) and (torch.version.hip is not None)) else False++ extra_link_args = []++ if IS_WINDOWS:+ # MSVC flags+ cxx_flags = ["/O2" if not debug_mode else "/Od", "/openmp"]+ if debug_mode:+ cxx_flags += ["/Z7"]+ extra_link_args += ["/DEBUG"]+ elif IS_MACOS:+ # Prefer a conservative Apple Silicon toolchain over OpenMP-specific flags.+ cxx_flags = [+ "-O3" if not debug_mode else "-O0",+ "-fdiagnostics-color=always",+ "-mmacosx-version-min=11.0",+ ]+ if use_native_arch:+ cxx_flags.append("-mcpu=apple-m1")+ if debug_mode:+ cxx_flags += ["-g", "-UNDEBUG"]+ extra_link_args += ["-O0", "-g"]+ else:+ # GCC/Clang flags+ cxx_flags = [+ "-O3" if not debug_mode else "-O0",+ "-fdiagnostics-color=always",+ "-fopenmp",+ ]+ if use_native_arch:+ cxx_flags.append("-march=native")+ if debug_mode:+ cxx_flags += ["-g", "-UNDEBUG"]+ extra_link_args += ["-O0", "-g"]++ extra_compile_args = {+ "cxx": cxx_flags,+ "nvcc": ["-O3" if not debug_mode else "-O0"],+ }+ if debug_mode and not IS_WINDOWS:+ extra_compile_args["nvcc"].append("-UNDEBUG")+ extra_compile_args["nvcc"].append("-g")++ define_macros = []+ extensions = []+ libraries = []++ this_dir = os.path.dirname(os.path.curdir)+ sources = glob.glob(+ os.path.join(this_dir, library_name, "csrc", "**", "*.cpp"), recursive=True+ )++ if len(sources) == 0:+ print("No source files found for extension, skipping extension compilation")+ return None++ if use_cuda:+ define_macros += [+ ("THRUST_IGNORE_CUB_VERSION_CHECK", None),+ ]+ sources += glob.glob(+ os.path.join(this_dir, library_name, "csrc", "**", "*.cu"), recursive=True+ )++ if not is_hip_extension:+ libraries += ["cudart", "c10_cuda"]++ if use_metal:+ define_macros += [+ ("WITH_MPS", None),+ ]+ sources += glob.glob(+ os.path.join(this_dir, library_name, "csrc", "**", "*.mm"), recursive=True+ )+ if IS_MACOS:+ if "-arch" not in extra_link_args:+ extra_link_args += [+ "-arch",+ "arm64",+ "-framework",+ "Metal",+ "-framework",+ "Foundation",+ ]+ cxx_flags.extend(["-arch", "arm64"])++ extensions.append(+ extension(+ name=f"{library_name}._C",+ sources=sources,+ define_macros=define_macros,+ extra_compile_args=extra_compile_args,+ extra_link_args=extra_link_args,+ libraries=libraries+ + [+ "c10",+ "torch",+ "torch_cpu",+ "torch_python",+ ],+ )+ )++ for ext in extensions:+ ext.libraries = ["cudart_static" if x == "cudart" else x for x in ext.libraries]++ print(extensions)++ return extensions+++setup(+ name=library_name,+ version="0.0.1",+ packages=find_packages(where="."),+ package_dir={"": "."},+ ext_modules=get_extensions(),+ install_requires=[],+ package_data={+ library_name: [os.path.join("csrc", "*.h"), os.path.join("csrc", "*.metal")],+ },+ description="Small texture baker which rasterizes barycentric coordinates to a tensor.",+ long_description=open("README.md").read(),+ long_description_content_type="text/markdown",+ url="https://github.com/Stability-AI/texture_baker",+ cmdclass={"build_ext": BuildExtension},+)diff --git a/apps/forge-desktop/api/texture_baker/texture_baker/__init__.py b/apps/forge-desktop/api/texture_baker/texture_baker/__init__.pynew file mode 100644index 000000000..b6173e690--- /dev/null+++ b/apps/forge-desktop/api/texture_baker/texture_baker/__init__.py@@ -0,0 +1,4 @@+import torch # noqa: F401++from . import _C # noqa: F401+from .baker import TextureBaker # noqa: F401diff --git a/apps/forge-desktop/api/texture_baker/texture_baker/baker.py b/apps/forge-desktop/api/texture_baker/texture_baker/baker.pynew file mode 100644index 000000000..923f110dc--- /dev/null+++ b/apps/forge-desktop/api/texture_baker/texture_baker/baker.py@@ -0,0 +1,90 @@+import torch+import torch.nn as nn+from torch import Tensor+++class TextureBaker(nn.Module):+ def __init__(self):+ super().__init__()++ def rasterize(+ self,+ uv: Tensor,+ face_indices: Tensor,+ bake_resolution: int,+ ) -> Tensor:+ """+ Rasterize the UV coordinates to a barycentric coordinates+ & Triangle idxs texture map++ Args:+ uv (Tensor, num_vertices 2, float): UV coordinates of the mesh+ face_indices (Tensor, num_faces 3, int): Face indices of the mesh+ bake_resolution (int): Resolution of the bake++ Returns:+ Tensor, bake_resolution bake_resolution 4, float: Rasterized map+ """+ device = uv.device+ result = torch.ops.texture_baker_cpp.rasterize(+ uv.cpu(), face_indices.to(torch.int32).cpu(), bake_resolution+ )+ return result.to(device)++ def get_mask(self, rast: Tensor) -> Tensor:+ """+ Get the occupancy mask from the rasterized map++ Args:+ rast (Tensor, bake_resolution bake_resolution 4, float): Rasterized map++ Returns:+ Tensor, bake_resolution bake_resolution, bool: Mask+ """+ return rast[..., -1] >= 0++ def interpolate(+ self,+ attr: Tensor,+ rast: Tensor,+ face_indices: Tensor,+ ) -> Tensor:+ """+ Interpolate the attributes using the rasterized map++ Args:+ attr (Tensor, num_vertices 3, float): Attributes of the mesh+ rast (Tensor, bake_resolution bake_resolution 4, float): Rasterized map+ face_indices (Tensor, num_faces 3, int): Face indices of the mesh+ uv (Tensor, num_vertices 2, float): UV coordinates of the mesh++ Returns:+ Tensor, bake_resolution bake_resolution 3, float: Interpolated attributes+ """+ device = attr.device+ result = torch.ops.texture_baker_cpp.interpolate(+ attr.cpu(), face_indices.to(torch.int32).cpu(), rast.cpu()+ )+ return result.to(device)++ def forward(+ self,+ attr: Tensor,+ uv: Tensor,+ face_indices: Tensor,+ bake_resolution: int,+ ) -> Tensor:+ """+ Bake the texture++ Args:+ attr (Tensor, num_vertices 3, float): Attributes of the mesh+ uv (Tensor, num_vertices 2, float): UV coordinates of the mesh+ face_indices (Tensor, num_faces 3, int): Face indices of the mesh+ bake_resolution (int): Resolution of the bake++ Returns:+ Tensor, bake_resolution bake_resolution 3, float: Baked texture+ """+ rast = self.rasterize(uv, face_indices, bake_resolution)+ return self.interpolate(attr, rast, face_indices, uv)diff --git a/apps/forge-desktop/api/texture_baker/texture_baker/csrc/baker.cpp b/apps/forge-desktop/api/texture_baker/texture_baker/csrc/baker.cppnew file mode 100644index 000000000..f92766489--- /dev/null+++ b/apps/forge-desktop/api/texture_baker/texture_baker/csrc/baker.cpp@@ -0,0 +1,548 @@+#include <ATen/ATen.h>+#include <ATen/Context.h>+#include <chrono>+#include <cmath>+#include <omp.h>+#include <torch/extension.h>+#ifndef __ARM_ARCH_ISA_A64+#include <immintrin.h>+#endif++#include "baker.h"++// #define TIMING+#define BINS 8++namespace texture_baker_cpp {+// Calculate the centroid of a triangle+tb_float2 triangle_centroid(const tb_float2 &v0, const tb_float2 &v1,+ const tb_float2 &v2) {+ return {(v0.x + v1.x + v2.x) * 0.3333f, (v0.y + v1.y + v2.y) * 0.3333f};+}++float BVH::find_best_split_plane(const BVHNode &node, int &best_axis,+ int &best_pos, AABB ¢roidBounds) {+ float best_cost = std::numeric_limits<float>::max();++ for (int axis = 0; axis < 2; ++axis) // We use 2 as we have only x and y+ {+ float boundsMin = centroidBounds.min[axis];+ float boundsMax = centroidBounds.max[axis];+ if (boundsMin == boundsMax) {+ continue;+ }++ // Populate the bins+ float scale = BINS / (boundsMax - boundsMin);+ float leftCountArea[BINS - 1], rightCountArea[BINS - 1];+ int leftSum = 0, rightSum = 0;++#ifndef __ARM_ARCH_ISA_A64+#ifndef _MSC_VER+ if (__builtin_cpu_supports("sse"))+#elif (defined(_M_AMD64) || defined(_M_X64))+ // SSE supported on Windows+ if constexpr (true)+#endif+ {+ __m128 min4[BINS], max4[BINS];+ unsigned int count[BINS];+ for (unsigned int i = 0; i < BINS; i++)+ min4[i] = _mm_set_ps1(1e30f), max4[i] = _mm_set_ps1(-1e30f),+ count[i] = 0;+ for (int i = node.start; i < node.end; i++) {+ int tri_idx = triangle_indices[i];+ const Triangle &triangle = triangles[tri_idx];++ int binIdx = std::min(+ BINS - 1, (int)((triangle.centroid[axis] - boundsMin) * scale));+ count[binIdx]++;+ __m128 v0 = _mm_set_ps(triangle.v0.x, triangle.v0.y, 0.0f, 0.0f);+ __m128 v1 = _mm_set_ps(triangle.v1.x, triangle.v1.y, 0.0f, 0.0f);+ __m128 v2 = _mm_set_ps(triangle.v2.x, triangle.v2.y, 0.0f, 0.0f);+ min4[binIdx] = _mm_min_ps(min4[binIdx], v0);+ max4[binIdx] = _mm_max_ps(max4[binIdx], v0);+ min4[binIdx] = _mm_min_ps(min4[binIdx], v1);+ max4[binIdx] = _mm_max_ps(max4[binIdx], v1);+ min4[binIdx] = _mm_min_ps(min4[binIdx], v2);+ max4[binIdx] = _mm_max_ps(max4[binIdx], v2);+ }+ // gather data for the 7 planes between the 8 bins+ __m128 leftMin4 = _mm_set_ps1(1e30f), rightMin4 = leftMin4;+ __m128 leftMax4 = _mm_set_ps1(-1e30f), rightMax4 = leftMax4;+ for (int i = 0; i < BINS - 1; i++) {+ leftSum += count[i];+ rightSum += count[BINS - 1 - i];+ leftMin4 = _mm_min_ps(leftMin4, min4[i]);+ rightMin4 = _mm_min_ps(rightMin4, min4[BINS - 2 - i]);+ leftMax4 = _mm_max_ps(leftMax4, max4[i]);+ rightMax4 = _mm_max_ps(rightMax4, max4[BINS - 2 - i]);+ float le[4], re[4];+ _mm_store_ps(le, _mm_sub_ps(leftMax4, leftMin4));+ _mm_store_ps(re, _mm_sub_ps(rightMax4, rightMin4));+ // SSE order goes from back to front+ leftCountArea[i] = leftSum * (le[2] * le[3]); // 2D area calculation+ rightCountArea[BINS - 2 - i] =+ rightSum * (re[2] * re[3]); // 2D area calculation+ }+ }+#else+ if constexpr (false) {+ }+#endif+ else {+ struct Bin {+ AABB bounds;+ int triCount = 0;+ } bins[BINS];++ for (int i = node.start; i < node.end; i++) {+ int tri_idx = triangle_indices[i];+ const Triangle &triangle = triangles[tri_idx];++ int binIdx = std::min(+ BINS - 1, (int)((triangle.centroid[axis] - boundsMin) * scale));+ bins[binIdx].triCount++;+ bins[binIdx].bounds.grow(triangle.v0);+ bins[binIdx].bounds.grow(triangle.v1);+ bins[binIdx].bounds.grow(triangle.v2);+ }++ // Gather data for the planes between the bins+ AABB leftBox, rightBox;++ for (int i = 0; i < BINS - 1; i++) {+ leftSum += bins[i].triCount;+ leftBox.grow(bins[i].bounds);+ leftCountArea[i] = leftSum * leftBox.area();++ rightSum += bins[BINS - 1 - i].triCount;+ rightBox.grow(bins[BINS - 1 - i].bounds);+ rightCountArea[BINS - 2 - i] = rightSum * rightBox.area();+ }+ }++ // Calculate SAH cost for the planes+ scale = (boundsMax - boundsMin) / BINS;+ for (int i = 0; i < BINS - 1; i++) {+ float planeCost = leftCountArea[i] + rightCountArea[i];+ if (planeCost < best_cost) {+ best_axis = axis;+ best_pos = i + 1;+ best_cost = planeCost;+ }+ }+ }++ return best_cost;+}++void BVH::update_node_bounds(BVHNode &node, AABB ¢roidBounds) {+#ifndef __ARM_ARCH_ISA_A64+#ifndef _MSC_VER+ if (__builtin_cpu_supports("sse"))+#elif (defined(_M_AMD64) || defined(_M_X64))+ // SSE supported on Windows+ if constexpr (true)+#endif+ {+ __m128 min4 = _mm_set_ps1(1e30f), max4 = _mm_set_ps1(-1e30f);+ __m128 cmin4 = _mm_set_ps1(1e30f), cmax4 = _mm_set_ps1(-1e30f);++ for (int i = node.start; i < node.end; i += 2) {+ int tri_idx1 = triangle_indices[i];+ const Triangle &leafTri1 = triangles[tri_idx1];+ // Check if the second actually exists in the node+ __m128 v0, v1, v2, centroid;+ if (i + 1 < node.end) {+ int tri_idx2 = triangle_indices[i + 1];+ const Triangle leafTri2 = triangles[tri_idx2];++ v0 = _mm_set_ps(leafTri1.v0.x, leafTri1.v0.y, leafTri2.v0.x,+ leafTri2.v0.y);+ v1 = _mm_set_ps(leafTri1.v1.x, leafTri1.v1.y, leafTri2.v1.x,+ leafTri2.v1.y);+ v2 = _mm_set_ps(leafTri1.v2.x, leafTri1.v2.y, leafTri2.v2.x,+ leafTri2.v2.y);+ centroid = _mm_set_ps(leafTri1.centroid.x, leafTri1.centroid.y,+ leafTri2.centroid.x, leafTri2.centroid.y);+ } else {+ // Otherwise do some duplicated work+ v0 = _mm_set_ps(leafTri1.v0.x, leafTri1.v0.y, leafTri1.v0.x,+ leafTri1.v0.y);+ v1 = _mm_set_ps(leafTri1.v1.x, leafTri1.v1.y, leafTri1.v1.x,+ leafTri1.v1.y);+ v2 = _mm_set_ps(leafTri1.v2.x, leafTri1.v2.y, leafTri1.v2.x,+ leafTri1.v2.y);+ centroid = _mm_set_ps(leafTri1.centroid.x, leafTri1.centroid.y,+ leafTri1.centroid.x, leafTri1.centroid.y);+ }++ min4 = _mm_min_ps(min4, v0);+ max4 = _mm_max_ps(max4, v0);+ min4 = _mm_min_ps(min4, v1);+ max4 = _mm_max_ps(max4, v1);+ min4 = _mm_min_ps(min4, v2);+ max4 = _mm_max_ps(max4, v2);+ cmin4 = _mm_min_ps(cmin4, centroid);+ cmax4 = _mm_max_ps(cmax4, centroid);+ }++ float min_values[4], max_values[4], cmin_values[4], cmax_values[4];+ _mm_store_ps(min_values, min4);+ _mm_store_ps(max_values, max4);+ _mm_store_ps(cmin_values, cmin4);+ _mm_store_ps(cmax_values, cmax4);++ node.bbox.min.x = std::min(min_values[3], min_values[1]);+ node.bbox.min.y = std::min(min_values[2], min_values[0]);+ node.bbox.max.x = std::max(max_values[3], max_values[1]);+ node.bbox.max.y = std::max(max_values[2], max_values[0]);++ centroidBounds.min.x = std::min(cmin_values[3], cmin_values[1]);+ centroidBounds.min.y = std::min(cmin_values[2], cmin_values[0]);+ centroidBounds.max.x = std::max(cmax_values[3], cmax_values[1]);+ centroidBounds.max.y = std::max(cmax_values[2], cmax_values[0]);+ }+#else+ if constexpr (false) {+ }+#endif+ {+ node.bbox.invalidate();+ centroidBounds.invalidate();++ // Calculate the bounding box for the node+ for (int i = node.start; i < node.end; ++i) {+ int tri_idx = triangle_indices[i];+ const Triangle &tri = triangles[tri_idx];+ node.bbox.grow(tri.v0);+ node.bbox.grow(tri.v1);+ node.bbox.grow(tri.v2);+ centroidBounds.grow(tri.centroid);+ }+ }+}++void BVH::build(const tb_float2 *vertices, const tb_int3 *indices,+ const int64_t &num_indices) {+#ifdef TIMING+ auto start = std::chrono::high_resolution_clock::now();+#endif+ // Create triangles+ for (size_t i = 0; i < num_indices; ++i) {+ tb_int3 idx = indices[i];+ triangles.push_back(+ {vertices[idx.x], vertices[idx.y], vertices[idx.z], static_cast<int>(i),+ triangle_centroid(vertices[idx.x], vertices[idx.y], vertices[idx.z])});+ }++ // Initialize triangle_indices+ triangle_indices.resize(triangles.size());+ std::iota(triangle_indices.begin(), triangle_indices.end(), 0);++ // Build BVH nodes+ // Reserve extra capacity to fix windows specific crashes+ nodes.reserve(triangles.size() * 2 + 1);+ nodes.push_back({}); // Create the root node+ root = 0;++ // Define a struct for queue entries+ struct QueueEntry {+ int node_idx;+ int start;+ int end;+ };++ // Queue for breadth-first traversal+ std::queue<QueueEntry> node_queue;+ node_queue.push({root, 0, (int)triangles.size()});++ // Process each node in the queue+ while (!node_queue.empty()) {+ QueueEntry current = node_queue.front();+ node_queue.pop();++ int node_idx = current.node_idx;+ int start = current.start;+ int end = current.end;++ BVHNode &node = nodes[node_idx];+ node.start = start;+ node.end = end;++ // Calculate the bounding box for the node+ AABB centroidBounds;+ update_node_bounds(node, centroidBounds);++ // Determine the best split using SAH+ int best_axis, best_pos;++ float splitCost =+ find_best_split_plane(node, best_axis, best_pos, centroidBounds);+ float nosplitCost = node.calculate_node_cost();++ // Stop condition: if the best cost is greater than or equal to the parent's+ // cost+ if (splitCost >= nosplitCost) {+ // Leaf node+ node.left = node.right = -1;+ continue;+ }++ float scale =+ BINS / (centroidBounds.max[best_axis] - centroidBounds.min[best_axis]);+ int i = node.start;+ int j = node.end - 1;++ // Sort the triangle_indices in the range [start, end) based on the best+ // axis+ while (i <= j) {+ // use the exact calculation we used for binning to prevent rare+ // inaccuracies+ int tri_idx = triangle_indices[i];+ tb_float2 tcentr = triangles[tri_idx].centroid;+ int binIdx = std::min(+ BINS - 1,+ (int)((tcentr[best_axis] - centroidBounds.min[best_axis]) * scale));+ if (binIdx < best_pos)+ i++;+ else+ std::swap(triangle_indices[i], triangle_indices[j--]);+ }+ int leftCount = i - node.start;+ if (leftCount == 0 || leftCount == node.num_triangles()) {+ // Leaf node+ node.left = node.right = -1;+ continue;+ }++ int mid = i;++ // Create and set left child+ node.left = nodes.size();+ nodes.push_back({});+ node_queue.push({node.left, start, mid});++ // Create and set right child+ node = nodes[node_idx]; // Update the node - Potentially stale reference+ node.right = nodes.size();+ nodes.push_back({});+ node_queue.push({node.right, mid, end});+ }+#ifdef TIMING+ auto end = std::chrono::high_resolution_clock::now();+ std::chrono::duration<double> elapsed = end - start;+ std::cout << "BVH build time: " << elapsed.count() << "s" << std::endl;+#endif+}++// Utility function to clamp a value between a minimum and a maximum+float clamp(float val, float minVal, float maxVal) {+ return std::min(std::max(val, minVal), maxVal);+}++// Function to check if a point (xy) is inside a triangle defined by vertices+// v1, v2, v3+bool barycentric_coordinates(tb_float2 xy, tb_float2 v1, tb_float2 v2,+ tb_float2 v3, float &u, float &v, float &w) {+ // Vectors from v1 to v2, v3 and xy+ tb_float2 v1v2 = {v2.x - v1.x, v2.y - v1.y};+ tb_float2 v1v3 = {v3.x - v1.x, v3.y - v1.y};+ tb_float2 xyv1 = {xy.x - v1.x, xy.y - v1.y};++ // Dot products of the vectors+ float d00 = v1v2.x * v1v2.x + v1v2.y * v1v2.y;+ float d01 = v1v2.x * v1v3.x + v1v2.y * v1v3.y;+ float d11 = v1v3.x * v1v3.x + v1v3.y * v1v3.y;+ float d20 = xyv1.x * v1v2.x + xyv1.y * v1v2.y;+ float d21 = xyv1.x * v1v3.x + xyv1.y * v1v3.y;++ // Calculate the barycentric coordinates+ float denom = d00 * d11 - d01 * d01;+ v = (d11 * d20 - d01 * d21) / denom;+ w = (d00 * d21 - d01 * d20) / denom;+ u = 1.0f - v - w;++ // Check if the point is inside the triangle+ return (v >= 0.0f) && (w >= 0.0f) && (v + w <= 1.0f);+}++bool BVH::intersect(const tb_float2 &point, float &u, float &v, float &w,+ int &index) const {+ const int max_stack_size = 64;+ int node_stack[max_stack_size];+ int stack_size = 0;++ node_stack[stack_size++] = root;++ while (stack_size > 0) {+ int node_idx = node_stack[--stack_size];+ const BVHNode &node = nodes[node_idx];++ if (node.is_leaf()) {+ for (int i = node.start; i < node.end; ++i) {+ const Triangle &tri = triangles[triangle_indices[i]];+ if (barycentric_coordinates(point, tri.v0, tri.v1, tri.v2, u, v, w)) {+ index = tri.index;+ return true;+ }+ }+ } else {+ if (nodes[node.right].bbox.overlaps(point)) {+ if (stack_size < max_stack_size) {+ node_stack[stack_size++] = node.right;+ } else {+ // Handle stack overflow+ throw std::runtime_error("Node stack overflow");+ }+ }+ if (nodes[node.left].bbox.overlaps(point)) {+ if (stack_size < max_stack_size) {+ node_stack[stack_size++] = node.left;+ } else {+ // Handle stack overflow+ throw std::runtime_error("Node stack overflow");+ }+ }+ }+ }++ return false;+}++torch::Tensor rasterize_cpu(torch::Tensor uv, torch::Tensor indices,+ int64_t bake_resolution) {+ int width = bake_resolution;+ int height = bake_resolution;+ int num_pixels = width * height;+ torch::Tensor rast_result = torch::empty(+ {bake_resolution, bake_resolution, 4},+ torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCPU));++ float *rast_result_ptr = rast_result.contiguous().data_ptr<float>();+ const tb_float2 *vertices = (tb_float2 *)uv.data_ptr<float>();+ const tb_int3 *tris = (tb_int3 *)indices.data_ptr<int>();++ BVH bvh;+ bvh.build(vertices, tris, indices.size(0));++#ifdef TIMING+ auto start = std::chrono::high_resolution_clock::now();+#endif++#pragma omp parallel for+ for (int idx = 0; idx < num_pixels; ++idx) {+ int x = idx / height;+ int y = idx % height;+ int idx_ = idx * 4; // Note: *4 because we're storing float4 per pixel++ tb_float2 pixel_coord = {float(y) / height, float(x) / width};+ pixel_coord.x = clamp(pixel_coord.x, 0.0f, 1.0f);+ pixel_coord.y = 1.0f - clamp(pixel_coord.y, 0.0f, 1.0f);++ float u, v, w;+ int triangle_idx;+ if (bvh.intersect(pixel_coord, u, v, w, triangle_idx)) {+ rast_result_ptr[idx_ + 0] = u;+ rast_result_ptr[idx_ + 1] = v;+ rast_result_ptr[idx_ + 2] = w;+ rast_result_ptr[idx_ + 3] = static_cast<float>(triangle_idx);+ } else {+ rast_result_ptr[idx_ + 0] = 0.0f;+ rast_result_ptr[idx_ + 1] = 0.0f;+ rast_result_ptr[idx_ + 2] = 0.0f;+ rast_result_ptr[idx_ + 3] = -1.0f;+ }+ }++#ifdef TIMING+ auto end = std::chrono::high_resolution_clock::now();+ std::chrono::duration<double> elapsed = end - start;+ std::cout << "Rasterization time: " << elapsed.count() << "s" << std::endl;+#endif+ return rast_result;+}++torch::Tensor interpolate_cpu(torch::Tensor attr, torch::Tensor indices,+ torch::Tensor rast) {+#ifdef TIMING+ auto start = std::chrono::high_resolution_clock::now();+#endif+ int height = rast.size(0);+ int width = rast.size(1);+ torch::Tensor pos_bake = torch::empty(+ {height, width, 3},+ torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCPU));++ const float *attr_ptr = attr.contiguous().data_ptr<float>();+ const int *indices_ptr = indices.contiguous().data_ptr<int>();+ const float *rast_ptr = rast.contiguous().data_ptr<float>();+ float *output_ptr = pos_bake.contiguous().data_ptr<float>();++ int num_pixels = width * height;++#pragma omp parallel for+ for (int idx = 0; idx < num_pixels; ++idx) {+ int idx_ = idx * 4; // Index into the float4 array (4 floats per pixel)+ tb_float3 barycentric = {+ rast_ptr[idx_ + 0],+ rast_ptr[idx_ + 1],+ rast_ptr[idx_ + 2],+ };+ int triangle_idx = static_cast<int>(rast_ptr[idx_ + 3]);++ if (triangle_idx < 0) {+ output_ptr[idx * 3 + 0] = 0.0f;+ output_ptr[idx * 3 + 1] = 0.0f;+ output_ptr[idx * 3 + 2] = 0.0f;+ continue;+ }++ tb_int3 triangle = {indices_ptr[3 * triangle_idx + 0],+ indices_ptr[3 * triangle_idx + 1],+ indices_ptr[3 * triangle_idx + 2]};+ tb_float3 v1 = {attr_ptr[3 * triangle.x + 0], attr_ptr[3 * triangle.x + 1],+ attr_ptr[3 * triangle.x + 2]};+ tb_float3 v2 = {attr_ptr[3 * triangle.y + 0], attr_ptr[3 * triangle.y + 1],+ attr_ptr[3 * triangle.y + 2]};+ tb_float3 v3 = {attr_ptr[3 * triangle.z + 0], attr_ptr[3 * triangle.z + 1],+ attr_ptr[3 * triangle.z + 2]};++ tb_float3 interpolated;+ interpolated.x =+ v1.x * barycentric.x + v2.x * barycentric.y + v3.x * barycentric.z;+ interpolated.y =+ v1.y * barycentric.x + v2.y * barycentric.y + v3.y * barycentric.z;+ interpolated.z =+ v1.z * barycentric.x + v2.z * barycentric.y + v3.z * barycentric.z;++ output_ptr[idx * 3 + 0] = interpolated.x;+ output_ptr[idx * 3 + 1] = interpolated.y;+ output_ptr[idx * 3 + 2] = interpolated.z;+ }++#ifdef TIMING+ auto end = std::chrono::high_resolution_clock::now();+ std::chrono::duration<double> elapsed = end - start;+ std::cout << "Interpolation time: " << elapsed.count() << "s" << std::endl;+#endif+ return pos_bake;+}++// Registers _C as a Python extension module.+PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {}++// Defines the operators+TORCH_LIBRARY(texture_baker_cpp, m) {+ m.def("rasterize(Tensor uv, Tensor indices, int bake_resolution) -> Tensor");+ m.def("interpolate(Tensor attr, Tensor indices, Tensor rast) -> Tensor");+}++// Registers CPP implementations+TORCH_LIBRARY_IMPL(texture_baker_cpp, CPU, m) {+ m.impl("rasterize", &rasterize_cpu);+ m.impl("interpolate", &interpolate_cpu);+}++} // namespace texture_baker_cppdiff --git a/apps/forge-desktop/api/texture_baker/texture_baker/csrc/baker.h b/apps/forge-desktop/api/texture_baker/texture_baker/csrc/baker.hnew file mode 100644index 000000000..ecb9b0d2a--- /dev/null+++ b/apps/forge-desktop/api/texture_baker/texture_baker/csrc/baker.h@@ -0,0 +1,203 @@+#pragma once++#if defined(__NVCC__) || defined(__HIPCC__) || defined(__METAL__)+#define CUDA_ENABLED+#ifndef __METAL__+#define CUDA_HOST_DEVICE __host__ __device__+#define CUDA_DEVICE __device__+#define METAL_CONSTANT_MEM+#define METAL_THREAD_MEM+#else+#define tb_float2 float2+#define CUDA_HOST_DEVICE+#define CUDA_DEVICE+#define METAL_CONSTANT_MEM constant+#define METAL_THREAD_MEM thread+#endif+#else+#define CUDA_HOST_DEVICE+#define CUDA_DEVICE+#define METAL_CONSTANT_MEM+#define METAL_THREAD_MEM+#include <cfloat>+#include <limits>+#include <vector>+#endif++namespace texture_baker_cpp {+// Structure to represent a 2D point or vector+#ifndef __METAL__+union alignas(8) tb_float2 {+ struct {+ float x, y;+ };++ float data[2];++ float &operator[](size_t idx) {+ if (idx > 1)+ throw std::runtime_error("bad index");+ return data[idx];+ }++ const float &operator[](size_t idx) const {+ if (idx > 1)+ throw std::runtime_error("bad index");+ return data[idx];+ }++ bool operator==(const tb_float2 &rhs) const {+ return x == rhs.x && y == rhs.y;+ }+};++union alignas(4) tb_float3 {+ struct {+ float x, y, z;+ };++ float data[3];++ float &operator[](size_t idx) {+ if (idx > 2)+ throw std::runtime_error("bad index");+ return data[idx];+ }++ const float &operator[](size_t idx) const {+ if (idx > 2)+ throw std::runtime_error("bad index");+ return data[idx];+ }+};++union alignas(16) tb_float4 {+ struct {+ float x, y, z, w;+ };++ float data[4];++ float &operator[](size_t idx) {+ if (idx > 3)+ throw std::runtime_error("bad index");+ return data[idx];+ }++ const float &operator[](size_t idx) const {+ if (idx > 3)+ throw std::runtime_error("bad index");+ return data[idx];+ }+};+#endif++union alignas(4) tb_int3 {+ struct {+ int x, y, z;+ };++ int data[3];+#ifndef __METAL__+ int &operator[](size_t idx) {+ if (idx > 2)+ throw std::runtime_error("bad index");+ return data[idx];+ }+#endif+};++// BVH structure to accelerate point-triangle intersection+struct alignas(16) AABB {+ // Init bounding boxes with max/min+ tb_float2 min = {FLT_MAX, FLT_MAX};+ tb_float2 max = {FLT_MIN, FLT_MIN};++#ifndef CUDA_ENABLED+ // grow the AABB to include a point+ void grow(const tb_float2 &p) {+ min.x = std::min(min.x, p.x);+ min.y = std::min(min.y, p.y);+ max.x = std::max(max.x, p.x);+ max.y = std::max(max.y, p.y);+ }++ void grow(const AABB &b) {+ if (b.min.x != FLT_MAX) {+ grow(b.min);+ grow(b.max);+ }+ }+#endif++ // Check if two AABBs overlap+ bool overlaps(const METAL_THREAD_MEM AABB &other) const {+ return min.x <= other.max.x && max.x >= other.min.x &&+ min.y <= other.max.y && max.y >= other.min.y;+ }++ bool overlaps(const METAL_THREAD_MEM tb_float2 &point) const {+ return point.x >= min.x && point.x <= max.x && point.y >= min.y &&+ point.y <= max.y;+ }++#if defined(__NVCC__) || defined(__HIPCC__)+ CUDA_DEVICE bool overlaps(const float2 &point) const {+ return point.x >= min.x && point.x <= max.x && point.y >= min.y &&+ point.y <= max.y;+ }+#endif++ // Initialize AABB to an invalid state+ void invalidate() {+ min = {FLT_MAX, FLT_MAX};+ max = {FLT_MIN, FLT_MIN};+ }++ // Calculate the area of the AABB+ float area() const {+ tb_float2 extent = {max.x - min.x, max.y - min.y};+ return extent.x * extent.y;+ }+};++struct BVHNode {+ AABB bbox;+ int start, end;+ int left, right;++ int num_triangles() const { return end - start; }++ CUDA_HOST_DEVICE bool is_leaf() const { return left == -1 && right == -1; }++ float calculate_node_cost() {+ float area = bbox.area();+ return num_triangles() * area;+ }+};++struct Triangle {+ tb_float2 v0, v1, v2;+ int index;+ tb_float2 centroid;+};++#ifndef __METAL__+struct BVH {+ std::vector<BVHNode> nodes;+ std::vector<Triangle> triangles;+ std::vector<int> triangle_indices;+ int root;++ void build(const tb_float2 *vertices, const tb_int3 *indices,+ const int64_t &num_indices);+ bool intersect(const tb_float2 &point, float &u, float &v, float &w,+ int &index) const;++ void update_node_bounds(BVHNode &node, AABB ¢roidBounds);+ float find_best_split_plane(const BVHNode &node, int &best_axis,+ int &best_pos, AABB ¢roidBounds);+};+#endif++} // namespace texture_baker_cppdiff --git a/apps/forge-desktop/api/texture_baker/texture_baker/csrc/baker_kernel.cu b/apps/forge-desktop/api/texture_baker/texture_baker/csrc/baker_kernel.cunew file mode 100644index 000000000..e9872c9cc--- /dev/null+++ b/apps/forge-desktop/api/texture_baker/texture_baker/csrc/baker_kernel.cu@@ -0,0 +1,306 @@+#include <ATen/ATen.h>+#include <ATen/Context.h>+#include <ATen/cuda/CUDAContext.h>+#include <torch/extension.h>++#include "baker.h"++// #define TIMING++#define STRINGIFY(x) #x+#define STR(x) STRINGIFY(x)+#define FILE_LINE __FILE__ ":" STR(__LINE__)+#define CUDA_CHECK_THROW(x) \+ do { \+ cudaError_t _result = x; \+ if (_result != cudaSuccess) \+ throw std::runtime_error(std::string(FILE_LINE " check failed " #x " failed: ") + cudaGetErrorString(_result)); \+ } while(0)++#if defined(__HIPCC__)+#define cudaMallocAsync hipMallocAsync+#define cudaFreeAsync hipFreeAsync+#endif++namespace texture_baker_cpp+{++ __device__ float3 operator+(const float3 &a, const float3 &b)+ {+ return make_float3(a.x + b.x, a.y + b.y, a.z + b.z);+ }++ // xy: 2D test position+ // v1: vertex position 1+ // v2: vertex position 2+ // v3: vertex position 3+ //+ __forceinline__ __device__ bool barycentric_coordinates(const float2 &xy, const tb_float2 &v1, const tb_float2 &v2, const tb_float2 &v3, float &u, float &v, float &w)+ {+ // Return true if the point (xy) is inside the triangle defined by the vertices v1, v2, v3.+ // If the point is inside the triangle, the barycentric coordinates are stored in u, v, and w.+ float2 v1v2 = make_float2(v2.x - v1.x, v2.y - v1.y);+ float2 v1v3 = make_float2(v3.x - v1.x, v3.y - v1.y);+ float2 xyv1 = make_float2(xy.x - v1.x, xy.y - v1.y);++ float d00 = v1v2.x * v1v2.x + v1v2.y * v1v2.y;+ float d01 = v1v2.x * v1v3.x + v1v2.y * v1v3.y;+ float d11 = v1v3.x * v1v3.x + v1v3.y * v1v3.y;+ float d20 = xyv1.x * v1v2.x + xyv1.y * v1v2.y;+ float d21 = xyv1.x * v1v3.x + xyv1.y * v1v3.y;++ float denom = d00 * d11 - d01 * d01;+ v = (d11 * d20 - d01 * d21) / denom;+ w = (d00 * d21 - d01 * d20) / denom;+ u = 1.0f - v - w;++ return (v >= 0.0f) && (w >= 0.0f) && (v + w <= 1.0f);+ }++ __global__ void kernel_interpolate(const float3* __restrict__ attr, const int3* __restrict__ indices, const float4* __restrict__ rast, float3* __restrict__ output, int width, int height)+ {+ // Interpolate the attr into output based on the rast result (barycentric coordinates, + triangle idx)+ //int idx = x * width + y;+ int idx = blockIdx.x * blockDim.x + threadIdx.x;+ int x = idx / width;+ int y = idx % width;++ if (x >= width || y >= height)+ return;++ float4 barycentric = rast[idx];+ int triangle_idx = int(barycentric.w);++ if (triangle_idx < 0)+ {+ output[idx] = make_float3(0.0f, 0.0f, 0.0f);+ return;+ }++ float3 v1 = attr[indices[triangle_idx].x];+ float3 v2 = attr[indices[triangle_idx].y];+ float3 v3 = attr[indices[triangle_idx].z];++ output[idx] = make_float3(v1.x * barycentric.x, v1.y * barycentric.x, v1.z * barycentric.x)+ + make_float3(v2.x * barycentric.y, v2.y * barycentric.y, v2.z * barycentric.y)+ + make_float3(v3.x * barycentric.z, v3.y * barycentric.z, v3.z * barycentric.z);+ }++ __device__ bool bvh_intersect(+ const BVHNode* __restrict__ nodes,+ const Triangle* __restrict__ triangles,+ const int* __restrict__ triangle_indices,+ const int root,+ const float2 &point,+ float &u, float &v, float &w,+ int &index)+ {+ constexpr int max_stack_size = 64;+ int node_stack[max_stack_size];+ int stack_size = 0;++ node_stack[stack_size++] = root;++ while (stack_size > 0)+ {+ int node_idx = node_stack[--stack_size];+ const BVHNode &node = nodes[node_idx];++ if (node.is_leaf())+ {+ for (int i = node.start; i < node.end; ++i)+ {+ const Triangle &tri = triangles[triangle_indices[i]];+ if (barycentric_coordinates(point, tri.v0, tri.v1, tri.v2, u, v, w))+ {+ index = tri.index;+ return true;+ }+ }+ }+ else+ {+ if (nodes[node.right].bbox.overlaps(point))+ {+ if (stack_size < max_stack_size)+ {+ node_stack[stack_size++] = node.right;+ }+ else+ {+ // Handle stack overflow+ // Make sure NDEBUG is not defined (see setup.py)+ assert(0 && "Node stack overflow");+ }+ }+ if (nodes[node.left].bbox.overlaps(point))+ {+ if (stack_size < max_stack_size)+ {+ node_stack[stack_size++] = node.left;+ }+ else+ {+ // Handle stack overflow+ // Make sure NDEBUG is not defined (see setup.py)+ assert(0 && "Node stack overflow");+ }+ }+ }+ }++ return false;+ }++ __global__ void kernel_bake_uv(+ float2* __restrict__ uv,+ int3* __restrict__ indices,+ float4* __restrict__ output,+ const BVHNode* __restrict__ nodes,+ const Triangle* __restrict__ triangles,+ const int* __restrict__ triangle_indices,+ const int root,+ const int width,+ const int height,+ const int num_indices)+ {+ //int idx = x * width + y;+ int idx = blockIdx.x * blockDim.x + threadIdx.x;+ int x = idx / width;+ int y = idx % width;++ if (y >= width || x >= height)+ return;++ // We index x,y but the original coords are HW. So swap them+ float2 pixel_coord = make_float2(float(y) / height, float(x) / width);+ pixel_coord.x = fminf(fmaxf(pixel_coord.x, 0.0f), 1.0f);+ pixel_coord.y = 1.0f - fminf(fmaxf(pixel_coord.y, 0.0f), 1.0f);++ float u, v, w;+ int triangle_idx;+ bool hit = bvh_intersect(nodes, triangles, triangle_indices, root, pixel_coord, u, v, w, triangle_idx);++ if (hit)+ {+ output[idx] = make_float4(u, v, w, float(triangle_idx));+ return;+ }++ output[idx] = make_float4(0.0f, 0.0f, 0.0f, -1.0f);+ }++ torch::Tensor rasterize_gpu(+ torch::Tensor uv,+ torch::Tensor indices,+ int64_t bake_resolution)+ {+#ifdef TIMING+ auto start = std::chrono::high_resolution_clock::now();+#endif+ constexpr int block_size = 16 * 16;+ int grid_size = bake_resolution * bake_resolution / block_size;+ dim3 block_dims(block_size, 1, 1);+ dim3 grid_dims(grid_size, 1, 1);++ int num_indices = indices.size(0);++ int width = bake_resolution;+ int height = bake_resolution;++ // Step 1: create an empty tensor to store the output.+ torch::Tensor rast_result = torch::empty({bake_resolution, bake_resolution, 4}, torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCUDA));++ auto vertices_cpu = uv.contiguous().cpu();+ auto indices_cpu = indices.contiguous().cpu();++ const tb_float2 *vertices_cpu_ptr = (tb_float2*)vertices_cpu.contiguous().data_ptr<float>();+ const tb_int3 *tris_cpu_ptr = (tb_int3*)indices_cpu.contiguous().data_ptr<int>();++ BVH bvh;+ bvh.build(vertices_cpu_ptr, tris_cpu_ptr, indices.size(0));++ BVHNode *nodes_gpu = nullptr;+ Triangle *triangles_gpu = nullptr;+ int *triangle_indices_gpu = nullptr;+ const int bvh_root = bvh.root;+ cudaStream_t cuda_stream = at::cuda::getCurrentCUDAStream();++ CUDA_CHECK_THROW(cudaMallocAsync(&nodes_gpu, sizeof(BVHNode) * bvh.nodes.size(), cuda_stream));+ CUDA_CHECK_THROW(cudaMallocAsync(&triangles_gpu, sizeof(Triangle) * bvh.triangles.size(), cuda_stream));+ CUDA_CHECK_THROW(cudaMallocAsync(&triangle_indices_gpu, sizeof(int) * bvh.triangle_indices.size(), cuda_stream));++ CUDA_CHECK_THROW(cudaMemcpyAsync(nodes_gpu, bvh.nodes.data(), sizeof(BVHNode) * bvh.nodes.size(), cudaMemcpyHostToDevice, cuda_stream));+ CUDA_CHECK_THROW(cudaMemcpyAsync(triangles_gpu, bvh.triangles.data(), sizeof(Triangle) * bvh.triangles.size(), cudaMemcpyHostToDevice, cuda_stream));+ CUDA_CHECK_THROW(cudaMemcpyAsync(triangle_indices_gpu, bvh.triangle_indices.data(), sizeof(int) * bvh.triangle_indices.size(), cudaMemcpyHostToDevice, cuda_stream));++ kernel_bake_uv<<<grid_dims, block_dims, 0, cuda_stream>>>(+ (float2 *)uv.contiguous().data_ptr<float>(),+ (int3 *)indices.contiguous().data_ptr<int>(),+ (float4 *)rast_result.contiguous().data_ptr<float>(),+ nodes_gpu,+ triangles_gpu,+ triangle_indices_gpu,+ bvh_root,+ width,+ height,+ num_indices);++ CUDA_CHECK_THROW(cudaFreeAsync(nodes_gpu, cuda_stream));+ CUDA_CHECK_THROW(cudaFreeAsync(triangles_gpu, cuda_stream));+ CUDA_CHECK_THROW(cudaFreeAsync(triangle_indices_gpu, cuda_stream));++#ifdef TIMING+ CUDA_CHECK_THROW(cudaStreamSynchronize(cuda_stream));+ auto end = std::chrono::high_resolution_clock::now();+ std::chrono::duration<double> elapsed = end - start;+ std::cout << "Rasterization time (CUDA): " << elapsed.count() << "s" << std::endl;+#endif+ return rast_result;+ }++ torch::Tensor interpolate_gpu(+ torch::Tensor attr,+ torch::Tensor indices,+ torch::Tensor rast)+ {+#ifdef TIMING+ auto start = std::chrono::high_resolution_clock::now();+#endif+ constexpr int block_size = 16 * 16;+ int grid_size = rast.size(0) * rast.size(0) / block_size;+ dim3 block_dims(block_size, 1, 1);+ dim3 grid_dims(grid_size, 1, 1);++ // Step 1: create an empty tensor to store the output.+ torch::Tensor pos_bake = torch::empty({rast.size(0), rast.size(1), 3}, torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCUDA));++ int width = rast.size(0);+ int height = rast.size(1);++ cudaStream_t cuda_stream = at::cuda::getCurrentCUDAStream();++ kernel_interpolate<<<grid_dims, block_dims, 0, cuda_stream>>>(+ (float3 *)attr.contiguous().data_ptr<float>(),+ (int3 *)indices.contiguous().data_ptr<int>(),+ (float4 *)rast.contiguous().data_ptr<float>(),+ (float3 *)pos_bake.contiguous().data_ptr<float>(),+ width,+ height);+#ifdef TIMING+ CUDA_CHECK_THROW(cudaStreamSynchronize(cuda_stream));+ auto end = std::chrono::high_resolution_clock::now();+ std::chrono::duration<double> elapsed = end - start;+ std::cout << "Interpolation time (CUDA): " << elapsed.count() << "s" << std::endl;+#endif+ return pos_bake;+ }++ // Registers CUDA implementations+ TORCH_LIBRARY_IMPL(texture_baker_cpp, CUDA, m)+ {+ m.impl("rasterize", &rasterize_gpu);+ m.impl("interpolate", &interpolate_gpu);+ }++}diff --git a/apps/forge-desktop/api/texture_baker/texture_baker/csrc/baker_kernel.metal b/apps/forge-desktop/api/texture_baker/texture_baker/csrc/baker_kernel.metalnew file mode 100644index 000000000..dff0a9413--- /dev/null+++ b/apps/forge-desktop/api/texture_baker/texture_baker/csrc/baker_kernel.metal@@ -0,0 +1,170 @@+#include <metal_stdlib>+using namespace metal;++// This header is inlined manually+//#include "baker.h"++// Use the texture_baker_cpp so it can use the classes from baker.h+using namespace texture_baker_cpp;++// Utility function to compute barycentric coordinates+bool barycentric_coordinates(float2 xy, float2 v1, float2 v2, float2 v3, thread float &u, thread float &v, thread float &w) {+ float2 v1v2 = v2 - v1;+ float2 v1v3 = v3 - v1;+ float2 xyv1 = xy - v1;++ float d00 = dot(v1v2, v1v2);+ float d01 = dot(v1v2, v1v3);+ float d11 = dot(v1v3, v1v3);+ float d20 = dot(xyv1, v1v2);+ float d21 = dot(xyv1, v1v3);++ float denom = d00 * d11 - d01 * d01;+ v = (d11 * d20 - d01 * d21) / denom;+ w = (d00 * d21 - d01 * d20) / denom;+ u = 1.0f - v - w;++ return (v >= 0.0f) && (w >= 0.0f) && (v + w <= 1.0f);+}++// Kernel function for interpolation+kernel void kernel_interpolate(constant packed_float3 *attr [[buffer(0)]],+ constant packed_int3 *indices [[buffer(1)]],+ constant packed_float4 *rast [[buffer(2)]],+ device packed_float3 *output [[buffer(3)]],+ constant int &width [[buffer(4)]],+ constant int &height [[buffer(5)]],+ uint3 blockIdx [[threadgroup_position_in_grid]],+ uint3 threadIdx [[thread_position_in_threadgroup]],+ uint3 blockDim [[threads_per_threadgroup]])+{+ // Calculate global position using threadgroup and thread positions+ int x = blockIdx.x * blockDim.x + threadIdx.x;+ int y = blockIdx.y * blockDim.y + threadIdx.y;++ if (x >= width || y >= height) return;++ int idx = y * width + x;+ float4 barycentric = rast[idx];+ int triangle_idx = int(barycentric.w);++ if (triangle_idx < 0) {+ output[idx] = float3(0.0f, 0.0f, 0.0f);+ return;+ }++ float3 v1 = attr[indices[triangle_idx].x];+ float3 v2 = attr[indices[triangle_idx].y];+ float3 v3 = attr[indices[triangle_idx].z];++ output[idx] = v1 * barycentric.x + v2 * barycentric.y + v3 * barycentric.z;+}++bool bvh_intersect(+ constant BVHNode* nodes,+ constant Triangle* triangles,+ constant int* triangle_indices,+ const thread int root,+ const thread float2 &point,+ thread float &u, thread float &v, thread float &w,+ thread int &index)+{+ const int max_stack_size = 64;+ thread int node_stack[max_stack_size];+ int stack_size = 0;++ node_stack[stack_size++] = root;++ while (stack_size > 0)+ {+ int node_idx = node_stack[--stack_size];+ BVHNode node = nodes[node_idx];++ if (node.is_leaf())+ {+ for (int i = node.start; i < node.end; ++i)+ {+ constant Triangle &tri = triangles[triangle_indices[i]];+ if (barycentric_coordinates(point, tri.v0, tri.v1, tri.v2, u, v, w))+ {+ index = tri.index;+ return true;+ }+ }+ }+ else+ {+ BVHNode test_node = nodes[node.right];+ if (test_node.bbox.overlaps(point))+ {+ if (stack_size < max_stack_size)+ {+ node_stack[stack_size++] = node.right;+ }+ else+ {+ // Handle stack overflow+ // Sadly, metal doesn't support asserts (but you could try enabling metal validation layers)+ return false;+ }+ }+ test_node = nodes[node.left];+ if (test_node.bbox.overlaps(point))+ {+ if (stack_size < max_stack_size)+ {+ node_stack[stack_size++] = node.left;+ }+ else+ {+ // Handle stack overflow+ return false;+ }+ }+ }+ }++ return false;+}+++// Kernel function for baking UV+kernel void kernel_bake_uv(constant packed_float2 *uv [[buffer(0)]],+ constant packed_int3 *indices [[buffer(1)]],+ device packed_float4 *output [[buffer(2)]],+ constant BVHNode *nodes [[buffer(3)]],+ constant Triangle *triangles [[buffer(4)]],+ constant int *triangle_indices [[buffer(5)]],+ constant int &root [[buffer(6)]],+ constant int &width [[buffer(7)]],+ constant int &height [[buffer(8)]],+ constant int &num_indices [[buffer(9)]],+ uint3 blockIdx [[threadgroup_position_in_grid]],+ uint3 threadIdx [[thread_position_in_threadgroup]],+ uint3 blockDim [[threads_per_threadgroup]])+{+ // Calculate global position using threadgroup and thread positions+ int x = blockIdx.x * blockDim.x + threadIdx.x;+ int y = blockIdx.y * blockDim.y + threadIdx.y;+++ if (x >= width || y >= height) return;++ int idx = x * width + y;++ // Swap original coordinates+ float2 pixel_coord = float2(float(y) / float(height), float(x) / float(width));+ pixel_coord = clamp(pixel_coord, 0.0f, 1.0f);+ pixel_coord.y = 1.0f - pixel_coord.y;++ float u, v, w;+ int triangle_idx;+ bool hit = bvh_intersect(nodes, triangles, triangle_indices, root, pixel_coord, u, v, w, triangle_idx);++ if (hit) {+ output[idx] = float4(u, v, w, float(triangle_idx));+ return;+ }++ output[idx] = float4(0.0f, 0.0f, 0.0f, -1.0f);+}diff --git a/apps/forge-desktop/api/texture_baker/texture_baker/csrc/baker_kernel.mm b/apps/forge-desktop/api/texture_baker/texture_baker/csrc/baker_kernel.mmnew file mode 100644index 000000000..ee406a215--- /dev/null+++ b/apps/forge-desktop/api/texture_baker/texture_baker/csrc/baker_kernel.mm@@ -0,0 +1,260 @@+#include <torch/extension.h>+#include <ATen/ATen.h>+#include <ATen/Context.h>+#include "baker.h"++#import <Foundation/Foundation.h>+#import <Metal/Metal.h>+#include <filesystem>++// Helper function to retrieve the `MTLBuffer` from a `torch::Tensor`.+static inline id<MTLBuffer> getMTLBufferStorage(const torch::Tensor& tensor) {+ return __builtin_bit_cast(id<MTLBuffer>, tensor.storage().data());+}++// Helper function to create a compute pipeline state object (PSO).+static inline id<MTLComputePipelineState> createComputePipelineState(id<MTLDevice> device, NSString* fullSource, std::string kernel_name) {+ NSError *error = nil;++ // Load the custom kernel shader.+ MTLCompileOptions *options = [[MTLCompileOptions alloc] init];+ // Add the preprocessor macro "__METAL__"+ options.preprocessorMacros = @{@"__METAL__": @""};+ id<MTLLibrary> customKernelLibrary = [device newLibraryWithSource: fullSource options:options error:&error];+ TORCH_CHECK(customKernelLibrary, "Failed to create custom kernel library, error: ", error.localizedDescription.UTF8String);++ id<MTLFunction> customKernelFunction = [customKernelLibrary newFunctionWithName:[NSString stringWithUTF8String:kernel_name.c_str()]];+ TORCH_CHECK(customKernelFunction, "Failed to create function state object for ", kernel_name.c_str());++ id<MTLComputePipelineState> pso = [device newComputePipelineStateWithFunction:customKernelFunction error:&error];+ TORCH_CHECK(pso, error.localizedDescription.UTF8String);++ return pso;+}++std::filesystem::path get_extension_path() {+ // Ensure the GIL is held before calling any Python C API function+ PyGILState_STATE gstate = PyGILState_Ensure();++ const char* module_name = "texture_baker";++ // Import the module by name+ PyObject* module = PyImport_ImportModule(module_name);+ if (!module) {+ PyGILState_Release(gstate);+ throw std::runtime_error("Could not import the module: " + std::string(module_name));+ }++ // Get the filename of the module+ PyObject* filename_obj = PyModule_GetFilenameObject(module);+ if (filename_obj) {+ std::string path = PyUnicode_AsUTF8(filename_obj);+ Py_DECREF(filename_obj);+ PyGILState_Release(gstate);++ // Get the directory part of the path (removing the __init__.py)+ std::filesystem::path module_path = std::filesystem::path(path).parent_path();++ // Append the 'csrc' directory to the path+ module_path /= "csrc";++ return module_path;+ } else {+ PyGILState_Release(gstate);+ throw std::runtime_error("Could not retrieve the module filename.");+ }+}++NSString *get_shader_sources_as_string()+{+ const std::filesystem::path csrc_path = get_extension_path();+ const std::string shader_path = (csrc_path / "baker_kernel.metal").string();+ const std::string shader_header_path = (csrc_path / "baker.h").string();+ // Load the Metal shader from the specified path+ NSError *error = nil;++ NSString* shaderHeaderSource = [+ NSString stringWithContentsOfFile:[NSString stringWithUTF8String:shader_header_path.c_str()]+ encoding:NSUTF8StringEncoding+ error:&error];+ if (error) {+ throw std::runtime_error("Failed to load baker.h: " + std::string(error.localizedDescription.UTF8String));+ }++ NSString* shaderSource = [+ NSString stringWithContentsOfFile:[NSString stringWithUTF8String:shader_path.c_str()]+ encoding:NSUTF8StringEncoding+ error:&error];+ if (error) {+ throw std::runtime_error("Failed to load Metal shader: " + std::string(error.localizedDescription.UTF8String));+ }++ NSString *fullSource = [shaderHeaderSource stringByAppendingString:shaderSource];++ return fullSource;+}++namespace texture_baker_cpp+{+ torch::Tensor rasterize_gpu(+ torch::Tensor uv,+ torch::Tensor indices,+ int64_t bake_resolution)+ {+ TORCH_CHECK(uv.device().is_mps(), "uv must be a MPS tensor");+ TORCH_CHECK(uv.is_contiguous(), "uv must be contiguous");+ TORCH_CHECK(indices.is_contiguous(), "indices must be contiguous");++ TORCH_CHECK(uv.scalar_type() == torch::kFloat32, "Unsupported data type: ", indices.scalar_type());+ TORCH_CHECK(indices.scalar_type() == torch::kInt32, "Unsupported data type: ", indices.scalar_type());++ torch::Tensor rast_result = torch::empty({bake_resolution, bake_resolution, 4}, torch::TensorOptions().dtype(torch::kFloat32).device(torch::kMPS)).contiguous();++ @autoreleasepool {+ auto vertices_cpu = uv.contiguous().cpu();+ auto indices_cpu = indices.contiguous().cpu();++ const tb_float2 *vertices_cpu_ptr = (tb_float2*)vertices_cpu.contiguous().data_ptr<float>();+ const tb_int3 *tris_cpu_ptr = (tb_int3*)indices_cpu.contiguous().data_ptr<int>();++ BVH bvh;+ bvh.build(vertices_cpu_ptr, tris_cpu_ptr, indices.size(0));++ id<MTLDevice> device = MTLCreateSystemDefaultDevice();++ NSString *fullSource = get_shader_sources_as_string();++ // Create a compute pipeline state object using the helper function+ id<MTLComputePipelineState> bake_uv_PSO = createComputePipelineState(device, fullSource, "kernel_bake_uv");++ // Get a reference to the command buffer for the MPS stream.+ id<MTLCommandBuffer> commandBuffer = torch::mps::get_command_buffer();+ TORCH_CHECK(commandBuffer, "Failed to retrieve command buffer reference");++ // Get a reference to the dispatch queue for the MPS stream, which encodes the synchronization with the CPU.+ dispatch_queue_t serialQueue = torch::mps::get_dispatch_queue();++ dispatch_sync(serialQueue, ^(){+ // Start a compute pass.+ id<MTLComputeCommandEncoder> computeEncoder = [commandBuffer computeCommandEncoder];+ TORCH_CHECK(computeEncoder, "Failed to create compute command encoder");++ // Get Metal buffers directly from PyTorch tensors+ auto uv_buf = getMTLBufferStorage(uv.contiguous());+ auto indices_buf = getMTLBufferStorage(indices.contiguous());+ auto rast_result_buf = getMTLBufferStorage(rast_result);++ const int width = bake_resolution;+ const int height = bake_resolution;+ const int num_indices = indices.size(0);+ const int bvh_root = bvh.root;++ // Wrap the existing CPU memory in Metal buffers with shared memory+ id<MTLBuffer> nodesBuffer = [device newBufferWithBytesNoCopy:(void*)bvh.nodes.data() length:sizeof(BVHNode) * bvh.nodes.size() options:MTLResourceStorageModeShared deallocator:nil];+ id<MTLBuffer> trianglesBuffer = [device newBufferWithBytesNoCopy:(void*)bvh.triangles.data() length:sizeof(Triangle) * bvh.triangles.size() options:MTLResourceStorageModeShared deallocator:nil];+ id<MTLBuffer> triangleIndicesBuffer = [device newBufferWithBytesNoCopy:(void*)bvh.triangle_indices.data() length:sizeof(int) * bvh.triangle_indices.size() options:MTLResourceStorageModeShared deallocator:nil];++ [computeEncoder setComputePipelineState:bake_uv_PSO];+ [computeEncoder setBuffer:uv_buf offset:uv.storage_offset() * uv.element_size() atIndex:0];+ [computeEncoder setBuffer:indices_buf offset:indices.storage_offset() * indices.element_size() atIndex:1];+ [computeEncoder setBuffer:rast_result_buf offset:rast_result.storage_offset() * rast_result.element_size() atIndex:2];+ [computeEncoder setBuffer:nodesBuffer offset:0 atIndex:3];+ [computeEncoder setBuffer:trianglesBuffer offset:0 atIndex:4];+ [computeEncoder setBuffer:triangleIndicesBuffer offset:0 atIndex:5];+ [computeEncoder setBytes:&bvh_root length:sizeof(int) atIndex:6];+ [computeEncoder setBytes:&width length:sizeof(int) atIndex:7];+ [computeEncoder setBytes:&height length:sizeof(int) atIndex:8];+ [computeEncoder setBytes:&num_indices length:sizeof(int) atIndex:9];++ // Calculate a thread group size.+ int block_size = 16;+ MTLSize threadgroupSize = MTLSizeMake(block_size, block_size, 1); // Fixed threadgroup size+ MTLSize numThreadgroups = MTLSizeMake(bake_resolution / block_size, bake_resolution / block_size, 1);++ // Encode the compute command.+ [computeEncoder dispatchThreadgroups:numThreadgroups threadsPerThreadgroup:threadgroupSize];+ [computeEncoder endEncoding];++ // Commit the work.+ torch::mps::commit();+ });+ }++ return rast_result;+ }++ torch::Tensor interpolate_gpu(+ torch::Tensor attr,+ torch::Tensor indices,+ torch::Tensor rast)+ {+ TORCH_CHECK(attr.is_contiguous(), "attr must be contiguous");+ TORCH_CHECK(indices.is_contiguous(), "indices must be contiguous");+ TORCH_CHECK(rast.is_contiguous(), "rast must be contiguous");++ torch::Tensor pos_bake = torch::empty({rast.size(0), rast.size(1), 3}, torch::TensorOptions().dtype(torch::kFloat32).device(torch::kMPS)).contiguous();+ std::filesystem::path csrc_path = get_extension_path();++ @autoreleasepool {+ id<MTLDevice> device = MTLCreateSystemDefaultDevice();++ NSString *fullSource = get_shader_sources_as_string();+ // Create a compute pipeline state object using the helper function+ id<MTLComputePipelineState> interpolate_PSO = createComputePipelineState(device, fullSource, "kernel_interpolate");++ // Get a reference to the command buffer for the MPS stream.+ id<MTLCommandBuffer> commandBuffer = torch::mps::get_command_buffer();+ TORCH_CHECK(commandBuffer, "Failed to retrieve command buffer reference");++ // Get a reference to the dispatch queue for the MPS stream, which encodes the synchronization with the CPU.+ dispatch_queue_t serialQueue = torch::mps::get_dispatch_queue();++ dispatch_sync(serialQueue, ^(){+ // Start a compute pass.+ id<MTLComputeCommandEncoder> computeEncoder = [commandBuffer computeCommandEncoder];+ TORCH_CHECK(computeEncoder, "Failed to create compute command encoder");++ // Get Metal buffers directly from PyTorch tensors+ auto attr_buf = getMTLBufferStorage(attr.contiguous());+ auto indices_buf = getMTLBufferStorage(indices.contiguous());+ auto rast_buf = getMTLBufferStorage(rast.contiguous());+ auto pos_bake_buf = getMTLBufferStorage(pos_bake);++ int width = rast.size(0);+ int height = rast.size(1);++ [computeEncoder setComputePipelineState:interpolate_PSO];+ [computeEncoder setBuffer:attr_buf offset:attr.storage_offset() * attr.element_size() atIndex:0];+ [computeEncoder setBuffer:indices_buf offset:indices.storage_offset() * indices.element_size() atIndex:1];+ [computeEncoder setBuffer:rast_buf offset:rast.storage_offset() * rast.element_size() atIndex:2];+ [computeEncoder setBuffer:pos_bake_buf offset:pos_bake.storage_offset() * pos_bake.element_size() atIndex:3];+ [computeEncoder setBytes:&width length:sizeof(int) atIndex:4];+ [computeEncoder setBytes:&height length:sizeof(int) atIndex:5];++ // Calculate a thread group size.++ int block_size = 16;+ MTLSize threadgroupSize = MTLSizeMake(block_size, block_size, 1); // Fixed threadgroup size+ MTLSize numThreadgroups = MTLSizeMake(rast.size(0) / block_size, rast.size(0) / block_size, 1);++ // Encode the compute command.+ [computeEncoder dispatchThreadgroups:numThreadgroups threadsPerThreadgroup:threadgroupSize];++ [computeEncoder endEncoding];++ // Commit the work.+ torch::mps::commit();+ });+ }++ return pos_bake;+ }++ // Registers MPS implementations+ TORCH_LIBRARY_IMPL(texture_baker_cpp, MPS, m)+ {+ m.impl("rasterize", &rasterize_gpu);+ m.impl("interpolate", &interpolate_gpu);+ }++}diff --git a/apps/forge-desktop/api/uv_unwrapper/README.md b/apps/forge-desktop/api/uv_unwrapper/README.mdnew file mode 100644index 000000000..e69de29bbdiff --git a/apps/forge-desktop/api/uv_unwrapper/requirements.txt b/apps/forge-desktop/api/uv_unwrapper/requirements.txtnew file mode 100644index 000000000..af3149eb4--- /dev/null+++ b/apps/forge-desktop/api/uv_unwrapper/requirements.txt@@ -0,0 +1,2 @@+torch+numpydiff --git a/apps/forge-desktop/api/uv_unwrapper/setup.py b/apps/forge-desktop/api/uv_unwrapper/setup.pynew file mode 100644index 000000000..8284ed93b--- /dev/null+++ b/apps/forge-desktop/api/uv_unwrapper/setup.py@@ -0,0 +1,97 @@+import glob+import os+import platform++import torch+from setuptools import find_packages, setup+from torch.utils.cpp_extension import (+ BuildExtension,+ CppExtension,+)++library_name = "uv_unwrapper"++IS_WINDOWS = platform.system() == "Windows"+IS_MACOS = platform.system() == "Darwin"+++def get_extensions():+ debug_mode = os.getenv("DEBUG", "0") == "1"+ if debug_mode:+ print("Compiling in debug mode")++ use_native_arch = not IS_MACOS and not IS_WINDOWS and os.getenv("USE_NATIVE_ARCH", "1") == "1"+ extension = CppExtension++ extra_link_args = []++ if IS_WINDOWS:+ # MSVC flags+ cxx_flags = ["/O2" if not debug_mode else "/Od", "/openmp"]+ if debug_mode:+ cxx_flags += ["/Z7", "/UNDEBUG"]+ extra_link_args += ["-O0"]+ elif IS_MACOS:+ cxx_flags = [+ "-O3" if not debug_mode else "-O0",+ "-fdiagnostics-color=always",+ "-mmacosx-version-min=11.0",+ "-arch",+ "arm64",+ ]+ if debug_mode:+ cxx_flags += ["-g", "-UNDEBUG"]+ extra_link_args += ["-O0", "-g"]+ else:+ cxx_flags = [+ "-O3" if not debug_mode else "-O0",+ "-fdiagnostics-color=always",+ "-fopenmp",+ ]+ if use_native_arch:+ cxx_flags.append("-march=native")+ if debug_mode:+ cxx_flags += ["-g", "-UNDEBUG"]+ extra_link_args += ["-O0", "-g"]++ extra_compile_args = {"cxx": cxx_flags}++ define_macros = []+ extensions = []++ this_dir = os.path.dirname(os.path.curdir)+ sources = glob.glob(+ os.path.join(this_dir, library_name, "csrc", "**", "*.cpp"), recursive=True+ )++ if len(sources) == 0:+ print("No source files found for extension, skipping extension compilation")+ return None++ extensions.append(+ extension(+ name=f"{library_name}._C",+ sources=sources,+ define_macros=define_macros,+ extra_compile_args=extra_compile_args,+ extra_link_args=extra_link_args,+ libraries=["c10", "torch", "torch_cpu", "torch_python"] if IS_MACOS else [],+ )+ )++ print(extensions)++ return extensions+++setup(+ name=library_name,+ version="0.0.1",+ packages=find_packages(),+ ext_modules=get_extensions(),+ install_requires=[],+ description="Box projection based UV unwrapper",+ long_description=open("README.md").read(),+ long_description_content_type="text/markdown",+ cmdclass={"build_ext": BuildExtension},+)diff --git a/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/__init__.py b/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/__init__.pynew file mode 100644index 000000000..f56e161df--- /dev/null+++ b/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/__init__.py@@ -0,0 +1,6 @@+import torch # noqa: F401++from . import _C # noqa: F401+from .unwrap import Unwrapper++__all__ = ["Unwrapper"]diff --git a/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/bvh.cpp b/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/bvh.cppnew file mode 100644index 000000000..25468f387--- /dev/null+++ b/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/bvh.cpp@@ -0,0 +1,381 @@+++#include "bvh.h"+#include "common.h"+#include <cstring>+#include <iostream>+#include <queue>+#include <tuple>+#include <utility>++namespace UVUnwrapper {+BVH::BVH(Triangle *tri, int *actual_idx, const size_t &num_indices) {+ // Copty tri to triangle+ triangle = new Triangle[num_indices];+ memcpy(triangle, tri, num_indices * sizeof(Triangle));++ // Copy actual_idx to actualIdx+ actualIdx = new int[num_indices];+ memcpy(actualIdx, actual_idx, num_indices * sizeof(int));++ triIdx = new int[num_indices];+ triCount = num_indices;++ bvhNode = new BVHNode[triCount * 2 + 64];+ nodesUsed = 2;+ memset(bvhNode, 0, triCount * 2 * sizeof(BVHNode));++ // populate triangle index array+ for (int i = 0; i < triCount; i++)+ triIdx[i] = i;++ BVHNode &root = bvhNode[0];++ root.start = 0, root.end = triCount;+ AABB centroidBounds;+ UpdateNodeBounds(0, centroidBounds);++ // subdivide recursively+ Subdivide(0, nodesUsed, centroidBounds);+}++BVH::BVH(const BVH &other)+ : BVH(other.triangle, other.triIdx, other.triCount) {}++BVH::BVH(BVH &&other) noexcept // move constructor+ : triIdx(std::exchange(other.triIdx, nullptr)),+ actualIdx(std::exchange(other.actualIdx, nullptr)),+ triangle(std::exchange(other.triangle, nullptr)),+ bvhNode(std::exchange(other.bvhNode, nullptr)) {}++BVH &BVH::operator=(const BVH &other) // copy assignment+{+ return *this = BVH(other);+}++BVH &BVH::operator=(BVH &&other) noexcept // move assignment+{+ std::swap(triIdx, other.triIdx);+ std::swap(actualIdx, other.actualIdx);+ std::swap(triangle, other.triangle);+ std::swap(bvhNode, other.bvhNode);+ std::swap(triCount, other.triCount);+ std::swap(nodesUsed, other.nodesUsed);+ return *this;+}++BVH::~BVH() {+ if (triIdx)+ delete[] triIdx;+ if (triangle)+ delete[] triangle;+ if (actualIdx)+ delete[] actualIdx;+ if (bvhNode)+ delete[] bvhNode;+}++void BVH::UpdateNodeBounds(unsigned int nodeIdx, AABB ¢roidBounds) {+ BVHNode &node = bvhNode[nodeIdx];+#ifndef __ARM_ARCH_ISA_A64+#ifndef _MSC_VER+ if (__builtin_cpu_supports("sse"))+#elif (defined(_M_AMD64) || defined(_M_X64))+ // SSE supported on Windows+ if constexpr (true)+#endif+ {+ __m128 min4 = _mm_set_ps1(FLT_MAX), max4 = _mm_set_ps1(FLT_MIN);+ __m128 cmin4 = _mm_set_ps1(FLT_MAX), cmax4 = _mm_set_ps1(FLT_MIN);+ for (int i = node.start; i < node.end; i += 2) {+ Triangle &leafTri1 = triangle[triIdx[i]];+ __m128 v0, v1, v2, centroid;+ if (i + 1 < node.end) {+ const Triangle leafTri2 = triangle[triIdx[i + 1]];++ v0 = _mm_set_ps(leafTri1.v0.x, leafTri1.v0.y, leafTri2.v0.x,+ leafTri2.v0.y);+ v1 = _mm_set_ps(leafTri1.v1.x, leafTri1.v1.y, leafTri2.v1.x,+ leafTri2.v1.y);+ v2 = _mm_set_ps(leafTri1.v2.x, leafTri1.v2.y, leafTri2.v2.x,+ leafTri2.v2.y);+ centroid = _mm_set_ps(leafTri1.centroid.x, leafTri1.centroid.y,+ leafTri2.centroid.x, leafTri2.centroid.y);+ } else {+ // Otherwise do some duplicated work+ v0 = _mm_set_ps(leafTri1.v0.x, leafTri1.v0.y, leafTri1.v0.x,+ leafTri1.v0.y);+ v1 = _mm_set_ps(leafTri1.v1.x, leafTri1.v1.y, leafTri1.v1.x,+ leafTri1.v1.y);+ v2 = _mm_set_ps(leafTri1.v2.x, leafTri1.v2.y, leafTri1.v2.x,+ leafTri1.v2.y);+ centroid = _mm_set_ps(leafTri1.centroid.x, leafTri1.centroid.y,+ leafTri1.centroid.x, leafTri1.centroid.y);+ }++ min4 = _mm_min_ps(min4, v0);+ max4 = _mm_max_ps(max4, v0);+ min4 = _mm_min_ps(min4, v1);+ max4 = _mm_max_ps(max4, v1);+ min4 = _mm_min_ps(min4, v2);+ max4 = _mm_max_ps(max4, v2);+ cmin4 = _mm_min_ps(cmin4, centroid);+ cmax4 = _mm_max_ps(cmax4, centroid);+ }+ float min_values[4], max_values[4], cmin_values[4], cmax_values[4];+ _mm_store_ps(min_values, min4);+ _mm_store_ps(max_values, max4);+ _mm_store_ps(cmin_values, cmin4);+ _mm_store_ps(cmax_values, cmax4);++ node.bbox.min.x = std::min(min_values[3], min_values[1]);+ node.bbox.min.y = std::min(min_values[2], min_values[0]);+ node.bbox.max.x = std::max(max_values[3], max_values[1]);+ node.bbox.max.y = std::max(max_values[2], max_values[0]);++ centroidBounds.min.x = std::min(cmin_values[3], cmin_values[1]);+ centroidBounds.min.y = std::min(cmin_values[2], cmin_values[0]);+ centroidBounds.max.x = std::max(cmax_values[3], cmax_values[1]);+ centroidBounds.max.y = std::max(cmax_values[2], cmax_values[0]);+ }+#else+ if constexpr (false) {+ }+#endif+ else {+ node.bbox.invalidate();+ centroidBounds.invalidate();++ // Calculate the bounding box for the node+ for (int i = node.start; i < node.end; ++i) {+ const Triangle &tri = triangle[triIdx[i]];+ node.bbox.grow(tri.v0);+ node.bbox.grow(tri.v1);+ node.bbox.grow(tri.v2);+ centroidBounds.grow(tri.centroid);+ }+ }+}++void BVH::Subdivide(unsigned int root_idx, unsigned int &nodePtr,+ AABB &rootCentroidBounds) {+ // Create a queue for the nodes to be subdivided+ std::queue<std::tuple<unsigned int, AABB>> nodeQueue;+ nodeQueue.push(std::make_tuple(root_idx, rootCentroidBounds));++ while (!nodeQueue.empty()) {+ // Get the next node to process from the queue+ auto [node_idx, centroidBounds] = nodeQueue.front();+ nodeQueue.pop();+ BVHNode &node = bvhNode[node_idx];++ // Check if left is -1 and right not or vice versa++ int axis, splitPos;+ float cost = FindBestSplitPlane(node, axis, splitPos, centroidBounds);++ if (cost >= node.calculate_node_cost()) {+ node.left = node.right = -1;+ continue; // Move on to the next node in the queue+ }++ int i = node.start;+ int j = node.end - 1;+ float scale = BINS / (centroidBounds.max[axis] - centroidBounds.min[axis]);+ while (i <= j) {+ int binIdx =+ std::min(BINS - 1, (int)((triangle[triIdx[i]].centroid[axis] -+ centroidBounds.min[axis]) *+ scale));+ if (binIdx < splitPos)+ i++;+ else+ std::swap(triIdx[i], triIdx[j--]);+ }++ int leftCount = i - node.start;+ if (leftCount == 0 || leftCount == (int)node.num_triangles()) {+ node.left = node.right = -1;+ continue; // Move on to the next node in the queue+ }++ int mid = i;++ // Create child nodes+ int leftChildIdx = nodePtr++;+ int rightChildIdx = nodePtr++;+ bvhNode[leftChildIdx].start = node.start;+ bvhNode[leftChildIdx].end = mid;+ bvhNode[rightChildIdx].start = mid;+ bvhNode[rightChildIdx].end = node.end;+ node.left = leftChildIdx;+ node.right = rightChildIdx;++ // Update the bounds for the child nodes and push them onto the queue+ UpdateNodeBounds(leftChildIdx, centroidBounds);+ nodeQueue.push(std::make_tuple(leftChildIdx, centroidBounds));++ UpdateNodeBounds(rightChildIdx, centroidBounds);+ nodeQueue.push(std::make_tuple(rightChildIdx, centroidBounds));+ }+}++float BVH::FindBestSplitPlane(BVHNode &node, int &best_axis, int &best_pos,+ AABB ¢roidBounds) {+ float best_cost = FLT_MAX;++ for (int axis = 0; axis < 2; ++axis) // We use 2 as we have only x and y+ {+ float boundsMin = centroidBounds.min[axis];+ float boundsMax = centroidBounds.max[axis];+ // Or floating point precision+ if ((boundsMin == boundsMax) || (boundsMax - boundsMin < 1e-8f)) {+ continue;+ }++ // populate the bins+ float scale = BINS / (boundsMax - boundsMin);+ float leftCountArea[BINS - 1], rightCountArea[BINS - 1];+ int leftSum = 0, rightSum = 0;+#ifndef __ARM_ARCH_ISA_A64+#ifndef _MSC_VER+ if (__builtin_cpu_supports("sse"))+#elif (defined(_M_AMD64) || defined(_M_X64))+ // SSE supported on Windows+ if constexpr (true)+#endif+ {+ __m128 min4[BINS], max4[BINS];+ unsigned int count[BINS];+ for (unsigned int i = 0; i < BINS; i++)+ min4[i] = _mm_set_ps1(FLT_MAX), max4[i] = _mm_set_ps1(FLT_MIN),+ count[i] = 0;+ for (int i = node.start; i < node.end; i++) {+ Triangle &tri = triangle[triIdx[i]];+ int binIdx =+ std::min(BINS - 1, (int)((tri.centroid[axis] - boundsMin) * scale));+ count[binIdx]++;++ __m128 v0 = _mm_set_ps(tri.v0.x, tri.v0.y, 0.0f, 0.0f);+ __m128 v1 = _mm_set_ps(tri.v1.x, tri.v1.y, 0.0f, 0.0f);+ __m128 v2 = _mm_set_ps(tri.v2.x, tri.v2.y, 0.0f, 0.0f);+ min4[binIdx] = _mm_min_ps(min4[binIdx], v0);+ max4[binIdx] = _mm_max_ps(max4[binIdx], v0);+ min4[binIdx] = _mm_min_ps(min4[binIdx], v1);+ max4[binIdx] = _mm_max_ps(max4[binIdx], v1);+ min4[binIdx] = _mm_min_ps(min4[binIdx], v2);+ max4[binIdx] = _mm_max_ps(max4[binIdx], v2);+ }+ // gather data for the 7 planes between the 8 bins+ __m128 leftMin4 = _mm_set_ps1(FLT_MAX), rightMin4 = leftMin4;+ __m128 leftMax4 = _mm_set_ps1(FLT_MIN), rightMax4 = leftMax4;+ for (int i = 0; i < BINS - 1; i++) {+ leftSum += count[i];+ rightSum += count[BINS - 1 - i];+ leftMin4 = _mm_min_ps(leftMin4, min4[i]);+ rightMin4 = _mm_min_ps(rightMin4, min4[BINS - 2 - i]);+ leftMax4 = _mm_max_ps(leftMax4, max4[i]);+ rightMax4 = _mm_max_ps(rightMax4, max4[BINS - 2 - i]);+ float le[4], re[4];+ _mm_store_ps(le, _mm_sub_ps(leftMax4, leftMin4));+ _mm_store_ps(re, _mm_sub_ps(rightMax4, rightMin4));+ // SSE order goes from back to front+ leftCountArea[i] = leftSum * (le[2] * le[3]); // 2D area calculation+ rightCountArea[BINS - 2 - i] =+ rightSum * (re[2] * re[3]); // 2D area calculation+ }+ }+#else+ if constexpr (false) {+ }+#endif+ else {+ struct Bin {+ AABB bounds;+ int triCount = 0;+ } bin[BINS];+ for (int i = node.start; i < node.end; i++) {+ Triangle &tri = triangle[triIdx[i]];+ int binIdx =+ std::min(BINS - 1, (int)((tri.centroid[axis] - boundsMin) * scale));+ bin[binIdx].triCount++;+ bin[binIdx].bounds.grow(tri.v0);+ bin[binIdx].bounds.grow(tri.v1);+ bin[binIdx].bounds.grow(tri.v2);+ }+ // gather data for the 7 planes between the 8 bins+ AABB leftBox, rightBox;+ for (int i = 0; i < BINS - 1; i++) {+ leftSum += bin[i].triCount;+ leftBox.grow(bin[i].bounds);+ leftCountArea[i] = leftSum * leftBox.area();+ rightSum += bin[BINS - 1 - i].triCount;+ rightBox.grow(bin[BINS - 1 - i].bounds);+ rightCountArea[BINS - 2 - i] = rightSum * rightBox.area();+ }+ }++ // calculate SAH cost for the 7 planes+ scale = (boundsMax - boundsMin) / BINS;+ for (int i = 0; i < BINS - 1; i++) {+ const float planeCost = leftCountArea[i] + rightCountArea[i];+ if (planeCost < best_cost)+ best_axis = axis, best_pos = i + 1, best_cost = planeCost;+ }+ }+ return best_cost;+}++std::vector<int> BVH::Intersect(Triangle &tri_intersect) {+ /**+ * @brief Intersect a triangle with the BVH+ *+ * @param triangle the triangle to intersect+ *+ * @return -1 for no intersection, the index of the intersected triangle+ * otherwise+ */++ const int max_stack_size = 64;+ int node_stack[max_stack_size];+ int stack_size = 0;+ std::vector<int> intersected_triangles;++ node_stack[stack_size++] = 0; // Start with the root node (index 0)+ while (stack_size > 0) {+ int node_idx = node_stack[--stack_size];+ const BVHNode &node = bvhNode[node_idx];+ if (node.is_leaf()) {+ for (int i = node.start; i < node.end; ++i) {+ const Triangle &tri = triangle[triIdx[i]];+ // Check that the triangle is not the same as the intersected triangle+ if (tri == tri_intersect)+ continue;+ if (tri_intersect.overlaps(tri)) {+ intersected_triangles.push_back(actualIdx[triIdx[i]]);+ }+ }+ } else {+ // Check right child first+ if (bvhNode[node.right].bbox.overlaps(tri_intersect)) {+ if (stack_size < max_stack_size) {+ node_stack[stack_size++] = node.right;+ } else {+ throw std::runtime_error("Node stack overflow");+ }+ }++ // Check left child+ if (bvhNode[node.left].bbox.overlaps(tri_intersect)) {+ if (stack_size < max_stack_size) {+ node_stack[stack_size++] = node.left;+ } else {+ throw std::runtime_error("Node stack overflow");+ }+ }+ }+ }+ return intersected_triangles; // Return all intersected triangle indices+}++} // namespace UVUnwrapperdiff --git a/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/bvh.h b/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/bvh.hnew file mode 100644index 000000000..91f48f4f7--- /dev/null+++ b/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/bvh.h@@ -0,0 +1,118 @@+#pragma once++#include <cfloat>+#include <cmath>+#ifndef __ARM_ARCH_ISA_A64+#include <immintrin.h>+#endif+#include <limits>+#include <vector>++#include "common.h"+#include "intersect.h"+/**+ * Based on https://github.com/jbikker/bvh_article released under the unlicense.+ */++// bin count for binned BVH building+#define BINS 8++namespace UVUnwrapper {+// minimalist triangle struct+struct alignas(32) Triangle {+ uv_float2 v0;+ uv_float2 v1;+ uv_float2 v2;+ uv_float2 centroid;++ bool overlaps(const Triangle &other) {+ // return tri_tri_overlap_test_2d(v0, v1, v2, other.v0, other.v1, other.v2);+ return triangle_triangle_intersection(v0, v1, v2, other.v0, other.v1,+ other.v2);+ }++ bool operator==(const Triangle &rhs) const {+ return v0 == rhs.v0 && v1 == rhs.v1 && v2 == rhs.v2;+ }+};++// minimalist AABB struct with grow functionality+struct alignas(16) AABB {+ // Init bounding boxes with max/min+ uv_float2 min = {FLT_MAX, FLT_MAX};+ uv_float2 max = {FLT_MIN, FLT_MIN};++ void grow(const uv_float2 &p) {+ min.x = std::min(min.x, p.x);+ min.y = std::min(min.y, p.y);+ max.x = std::max(max.x, p.x);+ max.y = std::max(max.y, p.y);+ }++ void grow(const AABB &b) {+ if (b.min.x != FLT_MAX) {+ grow(b.min);+ grow(b.max);+ }+ }++ bool overlaps(const Triangle &tri) {+ return triangle_aabb_intersection(min, max, tri.v0, tri.v1, tri.v2);+ }++ float area() const {+ uv_float2 extent = {max.x - min.x, max.y - min.y};+ return extent.x * extent.y;+ }++ void invalidate() {+ min = {FLT_MAX, FLT_MAX};+ max = {FLT_MIN, FLT_MIN};+ }+};++// 32-byte BVH node struct+struct alignas(32) BVHNode {+ AABB bbox; // 16+ int start = 0, end = 0; // 8+ int left, right;++ int num_triangles() const { return end - start; }++ bool is_leaf() const { return left == -1 && right == -1; }++ float calculate_node_cost() {+ float area = bbox.area();+ return num_triangles() * area;+ }+};++class BVH {+public:+ BVH() = default;+ BVH(BVH &&other) noexcept;+ BVH(const BVH &other);+ BVH &operator=(const BVH &other);+ BVH &operator=(BVH &&other) noexcept;+ BVH(Triangle *tri, int *actual_idx, const size_t &num_indices);+ ~BVH();++ std::vector<int> Intersect(Triangle &triangle);++private:+ void Subdivide(unsigned int node_idx, unsigned int &nodePtr,+ AABB ¢roidBounds);+ void UpdateNodeBounds(unsigned int nodeIdx, AABB ¢roidBounds);+ float FindBestSplitPlane(BVHNode &node, int &axis, int &splitPos,+ AABB ¢roidBounds);++public:+ int *triIdx = nullptr;+ int *actualIdx = nullptr;+ unsigned int triCount;+ unsigned int nodesUsed;+ BVHNode *bvhNode = nullptr;+ Triangle *triangle = nullptr;+};++} // namespace UVUnwrapperdiff --git a/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/common.h b/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/common.hnew file mode 100644index 000000000..5b6adb02a--- /dev/null+++ b/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/common.h@@ -0,0 +1,493 @@+#pragma once++#include <array>+#include <cmath>+#include <iostream>+#include <stdexcept>++const float EPSILON = 1e-7f;++// Structure to represent a 2D point or vector+union alignas(8) uv_float2 {+ struct {+ float x, y;+ };++ float data[2];++ float &operator[](size_t idx) {+ if (idx > 1)+ throw std::runtime_error("bad index");+ return data[idx];+ }++ const float &operator[](size_t idx) const {+ if (idx > 1)+ throw std::runtime_error("bad index");+ return data[idx];+ }++ bool operator==(const uv_float2 &rhs) const {+ return x == rhs.x && y == rhs.y;+ }+};++// Do not align as this is specifically tweaked for BVHNode+union uv_float3 {+ struct {+ float x, y, z;+ };++ float data[3];++ float &operator[](size_t idx) {+ if (idx > 3)+ throw std::runtime_error("bad index");+ return data[idx];+ }++ const float &operator[](size_t idx) const {+ if (idx > 3)+ throw std::runtime_error("bad index");+ return data[idx];+ }++ bool operator==(const uv_float3 &rhs) const {+ return x == rhs.x && y == rhs.y && z == rhs.z;+ }+};++union alignas(16) uv_float4 {+ struct {+ float x, y, z, w;+ };++ float data[4];++ float &operator[](size_t idx) {+ if (idx > 3)+ throw std::runtime_error("bad index");+ return data[idx];+ }++ const float &operator[](size_t idx) const {+ if (idx > 3)+ throw std::runtime_error("bad index");+ return data[idx];+ }++ bool operator==(const uv_float4 &rhs) const {+ return x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w;+ }+};++union alignas(8) uv_int2 {+ struct {+ int x, y;+ };++ int data[2];++ int &operator[](size_t idx) {+ if (idx > 1)+ throw std::runtime_error("bad index");+ return data[idx];+ }++ const int &operator[](size_t idx) const {+ if (idx > 1)+ throw std::runtime_error("bad index");+ return data[idx];+ }++ bool operator==(const uv_int2 &rhs) const { return x == rhs.x && y == rhs.y; }+};++union alignas(4) uv_int3 {+ struct {+ int x, y, z;+ };++ int data[3];++ int &operator[](size_t idx) {+ if (idx > 2)+ throw std::runtime_error("bad index");+ return data[idx];+ }++ const int &operator[](size_t idx) const {+ if (idx > 2)+ throw std::runtime_error("bad index");+ return data[idx];+ }++ bool operator==(const uv_int3 &rhs) const {+ return x == rhs.x && y == rhs.y && z == rhs.z;+ }+};++union alignas(16) uv_int4 {+ struct {+ int x, y, z, w;+ };++ int data[4];++ int &operator[](size_t idx) {+ if (idx > 3)+ throw std::runtime_error("bad index");+ return data[idx];+ }++ const int &operator[](size_t idx) const {+ if (idx > 3)+ throw std::runtime_error("bad index");+ return data[idx];+ }++ bool operator==(const uv_int4 &rhs) const {+ return x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w;+ }+};++inline float calc_mean(float a, float b, float c) { return (a + b + c) / 3; }++// Create a triangle centroid+inline uv_float2 triangle_centroid(const uv_float2 &v0, const uv_float2 &v1,+ const uv_float2 &v2) {+ return {calc_mean(v0.x, v1.x, v2.x), calc_mean(v0.y, v1.y, v2.y)};+}++inline uv_float3 triangle_centroid(const uv_float3 &v0, const uv_float3 &v1,+ const uv_float3 &v2) {+ return {calc_mean(v0.x, v1.x, v2.x), calc_mean(v0.y, v1.y, v2.y),+ calc_mean(v0.z, v1.z, v2.z)};+}++// Helper functions for vector math+inline uv_float2 operator-(const uv_float2 &a, const uv_float2 &b) {+ return {a.x - b.x, a.y - b.y};+}++inline uv_float3 operator-(const uv_float3 &a, const uv_float3 &b) {+ return {a.x - b.x, a.y - b.y, a.z - b.z};+}++inline uv_float2 operator+(const uv_float2 &a, const uv_float2 &b) {+ return {a.x + b.x, a.y + b.y};+}++inline uv_float3 operator+(const uv_float3 &a, const uv_float3 &b) {+ return {a.x + b.x, a.y + b.y, a.z + b.z};+}++inline uv_float2 operator*(const uv_float2 &a, float scalar) {+ return {a.x * scalar, a.y * scalar};+}++inline uv_float3 operator*(const uv_float3 &a, float scalar) {+ return {a.x * scalar, a.y * scalar, a.z * scalar};+}++inline float dot(const uv_float2 &a, const uv_float2 &b) {+ return a.x * b.x + a.y * b.y;+}++inline float dot(const uv_float3 &a, const uv_float3 &b) {+ return a.x * b.x + a.y * b.y + a.z * b.z;+}++inline float cross(const uv_float2 &a, const uv_float2 &b) {+ return a.x * b.y - a.y * b.x;+}++inline uv_float3 cross(const uv_float3 &a, const uv_float3 &b) {+ return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x};+}++inline uv_float2 abs_vec(const uv_float2 &v) {+ return {std::abs(v.x), std::abs(v.y)};+}++inline uv_float2 min_vec(const uv_float2 &a, const uv_float2 &b) {+ return {std::min(a.x, b.x), std::min(a.y, b.y)};+}++inline uv_float2 max_vec(const uv_float2 &a, const uv_float2 &b) {+ return {std::max(a.x, b.x), std::max(a.y, b.y)};+}++inline float distance_to(const uv_float2 &a, const uv_float2 &b) {+ return std::sqrt(std::pow(a.x - b.x, 2) + std::pow(a.y - b.y, 2));+}++inline float distance_to(const uv_float3 &a, const uv_float3 &b) {+ return std::sqrt(std::pow(a.x - b.x, 2) + std::pow(a.y - b.y, 2) ++ std::pow(a.z - b.z, 2));+}++inline uv_float2 normalize(const uv_float2 &v) {+ float len = std::sqrt(v.x * v.x + v.y * v.y);+ return {v.x / len, v.y / len};+}++inline uv_float3 normalize(const uv_float3 &v) {+ float len = std::sqrt(v.x * v.x + v.y * v.y + v.z * v.z);+ return {v.x / len, v.y / len, v.z / len};+}++inline float magnitude(const uv_float3 &v) {+ return std::sqrt(v.x * v.x + v.y * v.y + v.z * v.z);+}++struct Matrix4 {+ std::array<std::array<float, 4>, 4> m;++ Matrix4() {+ for (auto &row : m) {+ row.fill(0.0f);+ }+ m[3][3] = 1.0f; // Identity matrix for 4th row and column+ }++ void set(float m00, float m01, float m02, float m03, float m10, float m11,+ float m12, float m13, float m20, float m21, float m22, float m23,+ float m30, float m31, float m32, float m33) {+ m[0][0] = m00;+ m[0][1] = m01;+ m[0][2] = m02;+ m[0][3] = m03;+ m[1][0] = m10;+ m[1][1] = m11;+ m[1][2] = m12;+ m[1][3] = m13;+ m[2][0] = m20;+ m[2][1] = m21;+ m[2][2] = m22;+ m[2][3] = m23;+ m[3][0] = m30;+ m[3][1] = m31;+ m[3][2] = m32;+ m[3][3] = m33;+ }++ float determinant() const {+ return m[0][3] * m[1][2] * m[2][1] * m[3][0] -+ m[0][2] * m[1][3] * m[2][1] * m[3][0] -+ m[0][3] * m[1][1] * m[2][2] * m[3][0] ++ m[0][1] * m[1][3] * m[2][2] * m[3][0] ++ m[0][2] * m[1][1] * m[2][3] * m[3][0] -+ m[0][1] * m[1][2] * m[2][3] * m[3][0] -+ m[0][3] * m[1][2] * m[2][0] * m[3][1] ++ m[0][2] * m[1][3] * m[2][0] * m[3][1] ++ m[0][3] * m[1][0] * m[2][2] * m[3][1] -+ m[0][0] * m[1][3] * m[2][2] * m[3][1] -+ m[0][2] * m[1][0] * m[2][3] * m[3][1] ++ m[0][0] * m[1][2] * m[2][3] * m[3][1] ++ m[0][3] * m[1][1] * m[2][0] * m[3][2] -+ m[0][1] * m[1][3] * m[2][0] * m[3][2] -+ m[0][3] * m[1][0] * m[2][1] * m[3][2] ++ m[0][0] * m[1][3] * m[2][1] * m[3][2] ++ m[0][1] * m[1][0] * m[2][3] * m[3][2] -+ m[0][0] * m[1][1] * m[2][3] * m[3][2] -+ m[0][2] * m[1][1] * m[2][0] * m[3][3] ++ m[0][1] * m[1][2] * m[2][0] * m[3][3] ++ m[0][2] * m[1][0] * m[2][1] * m[3][3] -+ m[0][0] * m[1][2] * m[2][1] * m[3][3] -+ m[0][1] * m[1][0] * m[2][2] * m[3][3] ++ m[0][0] * m[1][1] * m[2][2] * m[3][3];+ }++ Matrix4 operator*(const Matrix4 &other) const {+ Matrix4 result;+ for (int row = 0; row < 4; ++row) {+ for (int col = 0; col < 4; ++col) {+ result.m[row][col] =+ m[row][0] * other.m[0][col] + m[row][1] * other.m[1][col] ++ m[row][2] * other.m[2][col] + m[row][3] * other.m[3][col];+ }+ }+ return result;+ }++ Matrix4 operator*(float scalar) const {+ Matrix4 result = *this;+ for (auto &row : result.m) {+ for (auto &element : row) {+ element *= scalar;+ }+ }+ return result;+ }++ Matrix4 operator+(const Matrix4 &other) const {+ Matrix4 result;+ for (int i = 0; i < 4; ++i) {+ for (int j = 0; j < 4; ++j) {+ result.m[i][j] = m[i][j] + other.m[i][j];+ }+ }+ return result;+ }++ Matrix4 operator-(const Matrix4 &other) const {+ Matrix4 result;+ for (int i = 0; i < 4; ++i) {+ for (int j = 0; j < 4; ++j) {+ result.m[i][j] = m[i][j] - other.m[i][j];+ }+ }+ return result;+ }++ float trace() const { return m[0][0] + m[1][1] + m[2][2] + m[3][3]; }++ Matrix4 identity() const {+ Matrix4 identity;+ identity.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);+ return identity;+ }++ Matrix4 power(int exp) const {+ if (exp == 0)+ return identity();+ if (exp == 1)+ return *this;++ Matrix4 result = *this;+ for (int i = 1; i < exp; ++i) {+ result = result * (*this);+ }+ return result;+ }++ void print() {+ // Print all entries in 4 rows with 4 columns+ for (int i = 0; i < 4; ++i) {+ for (int j = 0; j < 4; ++j) {+ std::cout << m[i][j] << " ";+ }+ std::cout << std::endl;+ }+ }++ bool invert() {+ double inv[16], det;+ double mArr[16];++ // Convert the matrix to a 1D array for easier manipulation+ for (int i = 0; i < 4; ++i) {+ for (int j = 0; j < 4; ++j) {+ mArr[i * 4 + j] = static_cast<double>(m[i][j]);+ }+ }++ inv[0] = mArr[5] * mArr[10] * mArr[15] - mArr[5] * mArr[11] * mArr[14] -+ mArr[9] * mArr[6] * mArr[15] + mArr[9] * mArr[7] * mArr[14] ++ mArr[13] * mArr[6] * mArr[11] - mArr[13] * mArr[7] * mArr[10];++ inv[4] = -mArr[4] * mArr[10] * mArr[15] + mArr[4] * mArr[11] * mArr[14] ++ mArr[8] * mArr[6] * mArr[15] - mArr[8] * mArr[7] * mArr[14] -+ mArr[12] * mArr[6] * mArr[11] + mArr[12] * mArr[7] * mArr[10];++ inv[8] = mArr[4] * mArr[9] * mArr[15] - mArr[4] * mArr[11] * mArr[13] -+ mArr[8] * mArr[5] * mArr[15] + mArr[8] * mArr[7] * mArr[13] ++ mArr[12] * mArr[5] * mArr[11] - mArr[12] * mArr[7] * mArr[9];++ inv[12] = -mArr[4] * mArr[9] * mArr[14] + mArr[4] * mArr[10] * mArr[13] ++ mArr[8] * mArr[5] * mArr[14] - mArr[8] * mArr[6] * mArr[13] -+ mArr[12] * mArr[5] * mArr[10] + mArr[12] * mArr[6] * mArr[9];++ inv[1] = -mArr[1] * mArr[10] * mArr[15] + mArr[1] * mArr[11] * mArr[14] ++ mArr[9] * mArr[2] * mArr[15] - mArr[9] * mArr[3] * mArr[14] -+ mArr[13] * mArr[2] * mArr[11] + mArr[13] * mArr[3] * mArr[10];++ inv[5] = mArr[0] * mArr[10] * mArr[15] - mArr[0] * mArr[11] * mArr[14] -+ mArr[8] * mArr[2] * mArr[15] + mArr[8] * mArr[3] * mArr[14] ++ mArr[12] * mArr[2] * mArr[11] - mArr[12] * mArr[3] * mArr[10];++ inv[9] = -mArr[0] * mArr[9] * mArr[15] + mArr[0] * mArr[11] * mArr[13] ++ mArr[8] * mArr[1] * mArr[15] - mArr[8] * mArr[3] * mArr[13] -+ mArr[12] * mArr[1] * mArr[11] + mArr[12] * mArr[3] * mArr[9];++ inv[13] = mArr[0] * mArr[9] * mArr[14] - mArr[0] * mArr[10] * mArr[13] -+ mArr[8] * mArr[1] * mArr[14] + mArr[8] * mArr[2] * mArr[13] ++ mArr[12] * mArr[1] * mArr[10] - mArr[12] * mArr[2] * mArr[9];++ inv[2] = mArr[1] * mArr[6] * mArr[15] - mArr[1] * mArr[7] * mArr[14] -+ mArr[5] * mArr[2] * mArr[15] + mArr[5] * mArr[3] * mArr[14] ++ mArr[13] * mArr[2] * mArr[7] - mArr[13] * mArr[3] * mArr[6];++ inv[6] = -mArr[0] * mArr[6] * mArr[15] + mArr[0] * mArr[7] * mArr[14] ++ mArr[4] * mArr[2] * mArr[15] - mArr[4] * mArr[3] * mArr[14] -+ mArr[12] * mArr[2] * mArr[7] + mArr[12] * mArr[3] * mArr[6];++ inv[10] = mArr[0] * mArr[5] * mArr[15] - mArr[0] * mArr[7] * mArr[13] -+ mArr[4] * mArr[1] * mArr[15] + mArr[4] * mArr[3] * mArr[13] ++ mArr[12] * mArr[1] * mArr[7] - mArr[12] * mArr[3] * mArr[5];++ inv[14] = -mArr[0] * mArr[5] * mArr[14] + mArr[0] * mArr[6] * mArr[13] ++ mArr[4] * mArr[1] * mArr[14] - mArr[4] * mArr[2] * mArr[13] -+ mArr[12] * mArr[1] * mArr[6] + mArr[12] * mArr[2] * mArr[5];++ inv[3] = -mArr[1] * mArr[6] * mArr[11] + mArr[1] * mArr[7] * mArr[10] ++ mArr[5] * mArr[2] * mArr[11] - mArr[5] * mArr[3] * mArr[10] -+ mArr[9] * mArr[2] * mArr[7] + mArr[9] * mArr[3] * mArr[6];++ inv[7] = mArr[0] * mArr[6] * mArr[11] - mArr[0] * mArr[7] * mArr[10] -+ mArr[4] * mArr[2] * mArr[11] + mArr[4] * mArr[3] * mArr[10] ++ mArr[8] * mArr[2] * mArr[7] - mArr[8] * mArr[3] * mArr[6];++ inv[11] = -mArr[0] * mArr[5] * mArr[11] + mArr[0] * mArr[7] * mArr[9] ++ mArr[4] * mArr[1] * mArr[11] - mArr[4] * mArr[3] * mArr[9] -+ mArr[8] * mArr[1] * mArr[7] + mArr[8] * mArr[3] * mArr[5];++ inv[15] = mArr[0] * mArr[5] * mArr[10] - mArr[0] * mArr[6] * mArr[9] -+ mArr[4] * mArr[1] * mArr[10] + mArr[4] * mArr[2] * mArr[9] ++ mArr[8] * mArr[1] * mArr[6] - mArr[8] * mArr[2] * mArr[5];++ det = mArr[0] * inv[0] + mArr[1] * inv[4] + mArr[2] * inv[8] ++ mArr[3] * inv[12];++ if (fabs(det) < 1e-6) {+ return false;+ }++ det = 1.0 / det;++ for (int i = 0; i < 16; i++) {+ inv[i] *= det;+ }++ // Convert the 1D array back to the 4x4 matrix+ for (int i = 0; i < 4; ++i) {+ for (int j = 0; j < 4; ++j) {+ m[i][j] = static_cast<float>(inv[i * 4 + j]);+ }+ }++ return true;+ }+};++inline void apply_matrix4(uv_float3 &v, const Matrix4 matrix) {+ float newX = v.x * matrix.m[0][0] + v.y * matrix.m[0][1] ++ v.z * matrix.m[0][2] + matrix.m[0][3];+ float newY = v.x * matrix.m[1][0] + v.y * matrix.m[1][1] ++ v.z * matrix.m[1][2] + matrix.m[1][3];+ float newZ = v.x * matrix.m[2][0] + v.y * matrix.m[2][1] ++ v.z * matrix.m[2][2] + matrix.m[2][3];+ float w = v.x * matrix.m[3][0] + v.y * matrix.m[3][1] + v.z * matrix.m[3][2] ++ matrix.m[3][3];++ if (std::fabs(w) > EPSILON) {+ newX /= w;+ newY /= w;+ newZ /= w;+ }++ v.x = newX;+ v.y = newY;+ v.z = newZ;+}diff --git a/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/intersect.cpp b/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/intersect.cppnew file mode 100644index 000000000..8d54b2c7f--- /dev/null+++ b/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/intersect.cpp@@ -0,0 +1,702 @@+#include "intersect.h"+#include "bvh.h"+#include <algorithm>+#include <cmath>+#include <iostream>+#include <stdexcept>+#include <vector>++bool triangle_aabb_intersection(const uv_float2 &aabbMin,+ const uv_float2 &aabbMax, const uv_float2 &v0,+ const uv_float2 &v1, const uv_float2 &v2) {+ // Convert the min and max aabb defintion to left, right, top, bottom+ float l = aabbMin.x;+ float r = aabbMax.x;+ float t = aabbMin.y;+ float b = aabbMax.y;++ int b0 = ((v0.x > l) ? 1 : 0) | ((v0.y > t) ? 2 : 0) | ((v0.x > r) ? 4 : 0) |+ ((v0.y > b) ? 8 : 0);+ if (b0 == 3)+ return true;++ int b1 = ((v1.x > l) ? 1 : 0) | ((v1.y > t) ? 2 : 0) | ((v1.x > r) ? 4 : 0) |+ ((v1.y > b) ? 8 : 0);+ if (b1 == 3)+ return true;++ int b2 = ((v2.x > l) ? 1 : 0) | ((v2.y > t) ? 2 : 0) | ((v2.x > r) ? 4 : 0) |+ ((v2.y > b) ? 8 : 0);+ if (b2 == 3)+ return true;++ float m, c, s;++ int i0 = b0 ^ b1;+ if (i0 != 0) {+ if (v1.x != v0.x) {+ m = (v1.y - v0.y) / (v1.x - v0.x);+ c = v0.y - (m * v0.x);+ if (i0 & 1) {+ s = m * l + c;+ if (s >= t && s <= b)+ return true;+ }+ if (i0 & 2) {+ s = (t - c) / m;+ if (s >= l && s <= r)+ return true;+ }+ if (i0 & 4) {+ s = m * r + c;+ if (s >= t && s <= b)+ return true;+ }+ if (i0 & 8) {+ s = (b - c) / m;+ if (s >= l && s <= r)+ return true;+ }+ } else {+ if (l == v0.x || r == v0.x)+ return true;+ if (v0.x > l && v0.x < r)+ return true;+ }+ }++ int i1 = b1 ^ b2;+ if (i1 != 0) {+ if (v2.x != v1.x) {+ m = (v2.y - v1.y) / (v2.x - v1.x);+ c = v1.y - (m * v1.x);+ if (i1 & 1) {+ s = m * l + c;+ if (s >= t && s <= b)+ return true;+ }+ if (i1 & 2) {+ s = (t - c) / m;+ if (s >= l && s <= r)+ return true;+ }+ if (i1 & 4) {+ s = m * r + c;+ if (s >= t && s <= b)+ return true;+ }+ if (i1 & 8) {+ s = (b - c) / m;+ if (s >= l && s <= r)+ return true;+ }+ } else {+ if (l == v1.x || r == v1.x)+ return true;+ if (v1.x > l && v1.x < r)+ return true;+ }+ }++ int i2 = b0 ^ b2;+ if (i2 != 0) {+ if (v2.x != v0.x) {+ m = (v2.y - v0.y) / (v2.x - v0.x);+ c = v0.y - (m * v0.x);+ if (i2 & 1) {+ s = m * l + c;+ if (s >= t && s <= b)+ return true;+ }+ if (i2 & 2) {+ s = (t - c) / m;+ if (s >= l && s <= r)+ return true;+ }+ if (i2 & 4) {+ s = m * r + c;+ if (s >= t && s <= b)+ return true;+ }+ if (i2 & 8) {+ s = (b - c) / m;+ if (s >= l && s <= r)+ return true;+ }+ } else {+ if (l == v0.x || r == v0.x)+ return true;+ if (v0.x > l && v0.x < r)+ return true;+ }+ }++ // Bounding box check+ float tbb_l = std::min(v0.x, std::min(v1.x, v2.x));+ float tbb_t = std::min(v0.y, std::min(v1.y, v2.y));+ float tbb_r = std::max(v0.x, std::max(v1.x, v2.x));+ float tbb_b = std::max(v0.y, std::max(v1.y, v2.y));++ if (tbb_l <= l && tbb_r >= r && tbb_t <= t && tbb_b >= b) {+ float v0x = v2.x - v0.x;+ float v0y = v2.y - v0.y;+ float v1x = v1.x - v0.x;+ float v1y = v1.y - v0.y;+ float v2x, v2y;++ float dot00, dot01, dot02, dot11, dot12, invDenom, u, v;++ // Top-left corner+ v2x = l - v0.x;+ v2y = t - v0.y;++ dot00 = v0x * v0x + v0y * v0y;+ dot01 = v0x * v1x + v0y * v1y;+ dot02 = v0x * v2x + v0y * v2y;+ dot11 = v1x * v1x + v1y * v1y;+ dot12 = v1x * v2x + v1y * v2y;++ invDenom = 1.0f / (dot00 * dot11 - dot01 * dot01);+ u = (dot11 * dot02 - dot01 * dot12) * invDenom;+ v = (dot00 * dot12 - dot01 * dot02) * invDenom;++ if (u >= 0 && v >= 0 && (u + v) <= 1)+ return true;++ // Bottom-left corner+ v2x = l - v0.x;+ v2y = b - v0.y;++ dot02 = v0x * v2x + v0y * v2y;+ dot12 = v1x * v2x + v1y * v2y;++ u = (dot11 * dot02 - dot01 * dot12) * invDenom;+ v = (dot00 * dot12 - dot01 * dot02) * invDenom;++ if (u >= 0 && v >= 0 && (u + v) <= 1)+ return true;++ // Bottom-right corner+ v2x = r - v0.x;+ v2y = b - v0.y;++ dot02 = v0x * v2x + v0y * v2y;+ dot12 = v1x * v2x + v1y * v2y;++ u = (dot11 * dot02 - dot01 * dot12) * invDenom;+ v = (dot00 * dot12 - dot01 * dot02) * invDenom;++ if (u >= 0 && v >= 0 && (u + v) <= 1)+ return true;++ // Top-right corner+ v2x = r - v0.x;+ v2y = t - v0.y;++ dot02 = v0x * v2x + v0y * v2y;+ dot12 = v1x * v2x + v1y * v2y;++ u = (dot11 * dot02 - dot01 * dot12) * invDenom;+ v = (dot00 * dot12 - dot01 * dot02) * invDenom;++ if (u >= 0 && v >= 0 && (u + v) <= 1)+ return true;+ }++ return false;+}++void tri_winding(uv_float2 &a, uv_float2 &b, uv_float2 &c) {+ float det = (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));++ // If the determinant is negative, the triangle is oriented clockwise+ if (det < 0) {+ // Swap vertices b and c to ensure counter-clockwise winding+ std::swap(b, c);+ }+}++struct Triangle {+ uv_float3 a, b, c;++ Triangle(const uv_float2 &p1, const uv_float2 &q1, const uv_float2 &r1)+ : a({p1.x, p1.y, 0}), b({q1.x, q1.y, 0}), c({r1.x, r1.y, 0}) {}++ Triangle(const uv_float3 &p1, const uv_float3 &q1, const uv_float3 &r1)+ : a(p1), b(q1), c(r1) {}++ void getNormal(uv_float3 &normal) const {+ uv_float3 u = b - a;+ uv_float3 v = c - a;+ normal = normalize(cross(u, v));+ }+};++bool isTriDegenerated(const Triangle &tri) {+ uv_float3 u = tri.a - tri.b;+ uv_float3 v = tri.a - tri.c;+ uv_float3 cr = cross(u, v);+ return fabs(cr.x) < EPSILON && fabs(cr.y) < EPSILON && fabs(cr.z) < EPSILON;+}++int orient3D(const uv_float3 &a, const uv_float3 &b, const uv_float3 &c,+ const uv_float3 &d) {+ Matrix4 _matrix4;+ _matrix4.set(a.x, a.y, a.z, 1, b.x, b.y, b.z, 1, c.x, c.y, c.z, 1, d.x, d.y,+ d.z, 1);+ float det = _matrix4.determinant();++ if (det < -EPSILON)+ return -1;+ else if (det > EPSILON)+ return 1;+ else+ return 0;+}++int orient2D(const uv_float2 &a, const uv_float2 &b, const uv_float2 &c) {+ float det = (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));++ if (det < -EPSILON)+ return -1;+ else if (det > EPSILON)+ return 1;+ else+ return 0;+}++int orient2D(const uv_float3 &a, const uv_float3 &b, const uv_float3 &c) {+ uv_float2 a_2d = {a.x, a.y};+ uv_float2 b_2d = {b.x, b.y};+ uv_float2 c_2d = {c.x, c.y};+ return orient2D(a_2d, b_2d, c_2d);+}++void permuteTriLeft(Triangle &tri) {+ uv_float3 tmp = tri.a;+ tri.a = tri.b;+ tri.b = tri.c;+ tri.c = tmp;+}++void permuteTriRight(Triangle &tri) {+ uv_float3 tmp = tri.c;+ tri.c = tri.b;+ tri.b = tri.a;+ tri.a = tmp;+}++void makeTriCounterClockwise(Triangle &tri) {+ if (orient2D(tri.a, tri.b, tri.c) < 0) {+ uv_float3 tmp = tri.c;+ tri.c = tri.b;+ tri.b = tmp;+ }+}++void intersectPlane(const uv_float3 &a, const uv_float3 &b, const uv_float3 &p,+ const uv_float3 &n, uv_float3 &target) {+ uv_float3 u = b - a;+ uv_float3 v = a - p;+ float dot1 = dot(n, u);+ float dot2 = dot(n, v);+ u = u * (-dot2 / dot1);+ target = a + u;+}++void computeLineIntersection(const Triangle &t1, const Triangle &t2,+ std::vector<uv_float3> &target) {+ uv_float3 n1, n2;+ t1.getNormal(n1);+ t2.getNormal(n2);++ int o1 = orient3D(t1.a, t1.c, t2.b, t2.a);+ int o2 = orient3D(t1.a, t1.b, t2.c, t2.a);++ uv_float3 i1, i2;++ if (o1 > 0) {+ if (o2 > 0) {+ intersectPlane(t1.a, t1.c, t2.a, n2, i1);+ intersectPlane(t2.a, t2.c, t1.a, n1, i2);+ } else {+ intersectPlane(t1.a, t1.c, t2.a, n2, i1);+ intersectPlane(t1.a, t1.b, t2.a, n2, i2);+ }+ } else {+ if (o2 > 0) {+ intersectPlane(t2.a, t2.b, t1.a, n1, i1);+ intersectPlane(t2.a, t2.c, t1.a, n1, i2);+ } else {+ intersectPlane(t2.a, t2.b, t1.a, n1, i1);+ intersectPlane(t1.a, t1.b, t2.a, n2, i2);+ }+ }++ target.push_back(i1);+ if (distance_to(i1, i2) >= EPSILON) {+ target.push_back(i2);+ }+}++void makeTriAVertexAlone(Triangle &tri, int oa, int ob, int oc) {+ // Permute a, b, c so that a is alone on its side+ if (oa == ob) {+ // c is alone, permute right so c becomes a+ permuteTriRight(tri);+ } else if (oa == oc) {+ // b is alone, permute so b becomes a+ permuteTriLeft(tri);+ } else if (ob != oc) {+ // In case a, b, c have different orientation, put a on positive side+ if (ob > 0) {+ permuteTriLeft(tri);+ } else if (oc > 0) {+ permuteTriRight(tri);+ }+ }+}++void makeTriAVertexPositive(Triangle &tri, const Triangle &other) {+ int o = orient3D(other.a, other.b, other.c, tri.a);+ if (o < 0) {+ std::swap(tri.b, tri.c);+ }+}++bool crossIntersect(Triangle &t1, Triangle &t2, int o1a, int o1b, int o1c,+ std::vector<uv_float3> *target = nullptr) {+ int o2a = orient3D(t1.a, t1.b, t1.c, t2.a);+ int o2b = orient3D(t1.a, t1.b, t1.c, t2.b);+ int o2c = orient3D(t1.a, t1.b, t1.c, t2.c);++ if (o2a == o2b && o2a == o2c) {+ return false;+ }++ // Make a vertex alone on its side for both triangles+ makeTriAVertexAlone(t1, o1a, o1b, o1c);+ makeTriAVertexAlone(t2, o2a, o2b, o2c);++ // Ensure the vertex on the positive side+ makeTriAVertexPositive(t2, t1);+ makeTriAVertexPositive(t1, t2);++ int o1 = orient3D(t1.a, t1.b, t2.a, t2.b);+ int o2 = orient3D(t1.a, t1.c, t2.c, t2.a);++ if (o1 <= 0 && o2 <= 0) {+ if (target) {+ computeLineIntersection(t1, t2, *target);+ }+ return true;+ }++ return false;+}++void linesIntersect2d(const uv_float3 &a1, const uv_float3 &b1,+ const uv_float3 &a2, const uv_float3 &b2,+ uv_float3 &target) {+ float dx1 = a1.x - b1.x;+ float dx2 = a2.x - b2.x;+ float dy1 = a1.y - b1.y;+ float dy2 = a2.y - b2.y;++ float D = dx1 * dy2 - dx2 * dy1;++ float n1 = a1.x * b1.y - a1.y * b1.x;+ float n2 = a2.x * b2.y - a2.y * b2.x;++ target.x = (n1 * dx2 - n2 * dx1) / D;+ target.y = (n1 * dy2 - n2 * dy1) / D;+ target.z = 0;+}++void clipTriangle(const Triangle &t1, const Triangle &t2,+ std::vector<uv_float3> &target) {+ std::vector<uv_float3> clip = {t1.a, t1.b, t1.c};+ std::vector<uv_float3> output = {t2.a, t2.b, t2.c};+ std::vector<int> orients(output.size() * 3, 0);+ uv_float3 inter;++ for (int i = 0; i < 3; ++i) {+ const int i_prev = (i + 2) % 3;+ std::vector<uv_float3> input;+ std::copy(output.begin(), output.end(), std::back_inserter(input));+ output.clear();++ for (size_t j = 0; j < input.size(); ++j) {+ orients[j] = orient2D(clip[i_prev], clip[i], input[j]);+ }++ for (size_t j = 0; j < input.size(); ++j) {+ const int j_prev = (j - 1 + input.size()) % input.size();++ if (orients[j] >= 0) {+ if (orients[j_prev] < 0) {+ linesIntersect2d(clip[i_prev], clip[i], input[j_prev], input[j],+ inter);+ output.push_back({inter.x, inter.y, inter.z});+ }+ output.push_back({input[j].x, input[j].y, input[j].z});+ } else if (orients[j_prev] >= 0) {+ linesIntersect2d(clip[i_prev], clip[i], input[j_prev], input[j], inter);+ output.push_back({inter.x, inter.y, inter.z});+ }+ }+ }++ // Clear duplicated points+ for (const auto &point : output) {+ int j = 0;+ bool sameFound = false;+ while (!sameFound && j < target.size()) {+ sameFound = distance_to(point, target[j]) <= 1e-6;+ j++;+ }++ if (!sameFound) {+ target.push_back(point);+ }+ }+}++bool intersectionTypeR1(const Triangle &t1, const Triangle &t2) {+ const uv_float3 &p1 = t1.a;+ const uv_float3 &q1 = t1.b;+ const uv_float3 &r1 = t1.c;+ const uv_float3 &p2 = t2.a;+ const uv_float3 &r2 = t2.c;++ if (orient2D(r2, p2, q1) >= 0) { // I+ if (orient2D(r2, p1, q1) >= 0) { // II.a+ if (orient2D(p1, p2, q1) >= 0) { // III.a+ return true;+ } else {+ if (orient2D(p1, p2, r1) >= 0) { // IV.a+ if (orient2D(q1, r1, p2) >= 0) { // V+ return true;+ }+ }+ }+ }+ } else {+ if (orient2D(r2, p2, r1) >= 0) { // II.b+ if (orient2D(q1, r1, r2) >= 0) { // III.b+ if (orient2D(p1, p2, r1) >= 0) { // IV.b (diverges from paper)+ return true;+ }+ }+ }+ }++ return false;+}++bool intersectionTypeR2(const Triangle &t1, const Triangle &t2) {+ const uv_float3 &p1 = t1.a;+ const uv_float3 &q1 = t1.b;+ const uv_float3 &r1 = t1.c;+ const uv_float3 &p2 = t2.a;+ const uv_float3 &q2 = t2.b;+ const uv_float3 &r2 = t2.c;++ if (orient2D(r2, p2, q1) >= 0) { // I+ if (orient2D(q2, r2, q1) >= 0) { // II.a+ if (orient2D(p1, p2, q1) >= 0) { // III.a+ if (orient2D(p1, q2, q1) <= 0) { // IV.a+ return true;+ }+ } else {+ if (orient2D(p1, p2, r1) >= 0) { // IV.b+ if (orient2D(r2, p2, r1) <= 0) { // V.a+ return true;+ }+ }+ }+ } else {+ if (orient2D(p1, q2, q1) <= 0) { // III.b+ if (orient2D(q2, r2, r1) >= 0) { // IV.c+ if (orient2D(q1, r1, q2) >= 0) { // V.b+ return true;+ }+ }+ }+ }+ } else {+ if (orient2D(r2, p2, r1) >= 0) { // II.b+ if (orient2D(q1, r1, r2) >= 0) { // III.c+ if (orient2D(r1, p1, p2) >= 0) { // IV.d+ return true;+ }+ } else {+ if (orient2D(q1, r1, q2) >= 0) { // IV.e+ if (orient2D(q2, r2, r1) >= 0) { // V.c+ return true;+ }+ }+ }+ }+ }++ return false;+}++bool coplanarIntersect(Triangle &t1, Triangle &t2,+ std::vector<uv_float3> *target = nullptr) {+ uv_float3 normal, u, v;+ t1.getNormal(normal);+ normal = normalize(normal);+ u = normalize(t1.a - t1.b);+ v = cross(normal, u);++ // Move basis to t1.a+ u = u + t1.a;+ v = v + t1.a;+ normal = normal + t1.a;++ Matrix4 _matrix;+ _matrix.set(t1.a.x, u.x, v.x, normal.x, t1.a.y, u.y, v.y, normal.y, t1.a.z,+ u.z, v.z, normal.z, 1, 1, 1, 1);++ Matrix4 _affineMatrix;+ _affineMatrix.set(0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1);++ _matrix.invert(); // Invert the _matrix+ _matrix = _affineMatrix * _matrix;++ // Apply transformation+ apply_matrix4(t1.a, _matrix);+ apply_matrix4(t1.b, _matrix);+ apply_matrix4(t1.c, _matrix);+ apply_matrix4(t2.a, _matrix);+ apply_matrix4(t2.b, _matrix);+ apply_matrix4(t2.c, _matrix);++ makeTriCounterClockwise(t1);+ makeTriCounterClockwise(t2);++ const uv_float3 &p1 = t1.a;+ const uv_float3 &p2 = t2.a;+ const uv_float3 &q2 = t2.b;+ const uv_float3 &r2 = t2.c;++ int o_p2q2 = orient2D(p2, q2, p1);+ int o_q2r2 = orient2D(q2, r2, p1);+ int o_r2p2 = orient2D(r2, p2, p1);++ bool intersecting = false;+ if (o_p2q2 >= 0) {+ if (o_q2r2 >= 0) {+ if (o_r2p2 >= 0) {+ // + + ++ intersecting = true;+ } else {+ // + + -+ intersecting = intersectionTypeR1(t1, t2);+ }+ } else {+ if (o_r2p2 >= 0) {+ // + - ++ permuteTriRight(t2);+ intersecting = intersectionTypeR1(t1, t2);+ } else {+ // + - -+ intersecting = intersectionTypeR2(t1, t2);+ }+ }+ } else {+ if (o_q2r2 >= 0) {+ if (o_r2p2 >= 0) {+ // - + ++ permuteTriLeft(t2);+ intersecting = intersectionTypeR1(t1, t2);+ } else {+ // - + -+ permuteTriLeft(t2);+ intersecting = intersectionTypeR2(t1, t2);+ }+ } else {+ if (o_r2p2 >= 0) {+ // - - ++ permuteTriRight(t2);+ intersecting = intersectionTypeR2(t1, t2);+ } else {+ // - - -+ std::cerr << "Triangles should not be flat." << std::endl;+ return false;+ }+ }+ }++ if (intersecting && target) {+ clipTriangle(t1, t2, *target);++ _matrix.invert();+ // Apply the transform to each target point+ for (int i = 0; i < target->size(); ++i) {+ apply_matrix4(target->at(i), _matrix);+ }+ }++ return intersecting;+}++// Helper function to calculate the area of a polygon+float polygon_area(const std::vector<uv_float3> &polygon) {+ if (polygon.size() < 3)+ return 0.0f; // Not a polygon++ uv_float3 normal = {0.0f, 0.0f, 0.0f}; // Initialize normal vector++ // Calculate the cross product of edges around the polygon+ for (size_t i = 0; i < polygon.size(); ++i) {+ uv_float3 p1 = polygon[i];+ uv_float3 p2 = polygon[(i + 1) % polygon.size()];++ normal = normal + cross(p1, p2); // Accumulate the normal vector+ }++ float area =+ magnitude(normal) / 2.0f; // Area is half the magnitude of the normal+ return area;+}++bool triangle_triangle_intersection(uv_float2 p1, uv_float2 q1, uv_float2 r1,+ uv_float2 p2, uv_float2 q2, uv_float2 r2) {+ Triangle t1(p1, q1, r1);+ Triangle t2(p2, q2, r2);++ if (isTriDegenerated(t1) || isTriDegenerated(t2)) {+ // std::cerr << "Degenerated triangles provided, skipping." << std::endl;+ return false;+ }++ int o1a = orient3D(t2.a, t2.b, t2.c, t1.a);+ int o1b = orient3D(t2.a, t2.b, t2.c, t1.b);+ int o1c = orient3D(t2.a, t2.b, t2.c, t1.c);++ std::vector<uv_float3> intersections;+ bool intersects;++ if (o1a == o1b && o1a == o1c) // [[likely]]+ {+ intersects = o1a == 0 && coplanarIntersect(t1, t2, &intersections);+ } else // [[unlikely]]+ {+ intersects = crossIntersect(t1, t2, o1a, o1b, o1c, &intersections);+ }++ if (intersects) {+ float area = polygon_area(intersections);++ // std::cout << "Intersection area: " << area << std::endl;+ if (area < 1e-10f || std::isfinite(area) == false) {+ // std::cout<<"Invalid area: " << area << std::endl;+ return false; // Ignore intersection if the area is too small+ }+ }++ return intersects;+}diff --git a/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/intersect.h b/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/intersect.hnew file mode 100644index 000000000..9ecfe8055--- /dev/null+++ b/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/intersect.h@@ -0,0 +1,10 @@+#pragma once++#include "common.h"+#include <vector>++bool triangle_aabb_intersection(const uv_float2 &aabb_min,+ const uv_float2 &aabb_max, const uv_float2 &v0,+ const uv_float2 &v1, const uv_float2 &v2);+bool triangle_triangle_intersection(uv_float2 p1, uv_float2 q1, uv_float2 r1,+ uv_float2 p2, uv_float2 q2, uv_float2 r2);diff --git a/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/unwrapper.cpp b/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/unwrapper.cppnew file mode 100644index 000000000..e76bd62b1--- /dev/null+++ b/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/csrc/unwrapper.cpp@@ -0,0 +1,271 @@+#include "bvh.h"+#include <ATen/ATen.h>+#include <ATen/Context.h>+#include <chrono>+#include <cmath>+#include <cstring>+#include <omp.h>+#include <set>+#include <torch/extension.h>+#include <vector>++// #define TIMING++#if defined(_MSC_VER)+#include <BaseTsd.h>+typedef SSIZE_T ssize_t;+#endif++namespace UVUnwrapper {+void create_bvhs(BVH *bvhs, Triangle *triangles,+ std::vector<std::set<int>> &triangle_per_face, int num_faces,+ int start, int end) {+#pragma omp parallel for+ for (int i = start; i < end; i++) {+ int num_triangles = triangle_per_face[i].size();+ Triangle *triangles_per_face = new Triangle[num_triangles];+ int *indices = new int[num_triangles];+ int j = 0;+ for (int idx : triangle_per_face[i]) {+ triangles_per_face[j] = triangles[idx];+ indices[j++] = idx;+ }+ // Each thread writes to it's own memory space+ // First check if the number of triangles is 0+ if (num_triangles == 0) {+ bvhs[i - start] = std::move(BVH()); // Default constructor+ } else {+ bvhs[i - start] = std::move(+ BVH(triangles_per_face, indices,+ num_triangles)); // BVH now handles memory of triangles_per_face+ }+ delete[] triangles_per_face;+ }+}++void perform_intersection_check(BVH *bvhs, int num_bvhs, Triangle *triangles,+ uv_float3 *vertex_tri_centroids,+ int64_t *assign_indices_ptr,+ ssize_t num_indices, int offset,+ std::vector<std::set<int>> &triangle_per_face) {+ std::vector<std::pair<int, int>>+ unique_intersections; // Store unique intersections as pairs of triangle+ // indices++// Step 1: Detect intersections in parallel+#pragma omp parallel for+ for (int i = 0; i < num_indices; i++) {+ if (assign_indices_ptr[i] < offset) {+ continue;+ }++ Triangle cur_tri = triangles[i];+ auto &cur_bvh = bvhs[assign_indices_ptr[i] - offset];++ if (cur_bvh.bvhNode == nullptr) {+ continue;+ }++ std::vector<int> intersections = cur_bvh.Intersect(cur_tri);++ if (!intersections.empty()) {++#pragma omp critical+ {+ for (int intersect : intersections) {+ if (i != intersect) {+ // Ensure we only store unique pairs (A, B) where A < B to avoid+ // duplication+ if (i < intersect) {+ unique_intersections.push_back(std::make_pair(i, intersect));+ } else {+ unique_intersections.push_back(std::make_pair(intersect, i));+ }+ }+ }+ }+ }+ }++ // Step 2: Process unique intersections+ for (int idx = 0; idx < unique_intersections.size(); idx++) {+ int first = unique_intersections[idx].first;+ int second = unique_intersections[idx].second;++ int i_idx = assign_indices_ptr[first];++ int norm_idx = i_idx % 6;+ int axis = (norm_idx < 2) ? 0 : (norm_idx < 4) ? 1 : 2;+ bool use_max = (i_idx % 2) == 1;++ float pos_a = vertex_tri_centroids[first][axis];+ float pos_b = vertex_tri_centroids[second][axis];+ // Sort the intersections based on vertex_tri_centroids along the specified+ // axis+ if (use_max) {+ if (pos_a < pos_b) {+ std::swap(first, second);+ }+ } else {+ if (pos_a > pos_b) {+ std::swap(first, second);+ }+ }++ // Update the unique intersections+ unique_intersections[idx].first = first;+ unique_intersections[idx].second = second;+ }++ // Now only get the second intersections from the pair and put them in a set+ // The second intersection should always be the occluded triangle+ std::set<int> second_intersections;+ for (int idx = 0; idx < (int)unique_intersections.size(); idx++) {+ int second = unique_intersections[idx].second;+ second_intersections.insert(second);+ }++ for (int int_idx : second_intersections) {+ // Move the second (occluded) triangle by 6+ int intersect_idx = assign_indices_ptr[int_idx];+ int new_index = intersect_idx + 6;+ new_index = std::clamp(new_index, 0, 12);++ assign_indices_ptr[int_idx] = new_index;+ triangle_per_face[intersect_idx].erase(int_idx);+ triangle_per_face[new_index].insert(int_idx);+ }+}++torch::Tensor assign_faces_uv_to_atlas_index(torch::Tensor vertices,+ torch::Tensor indices,+ torch::Tensor face_uv,+ torch::Tensor face_index) {+ // Get the number of faces+ int num_faces = indices.size(0);+ torch::Tensor assign_indices =+ torch::empty(+ {+ num_faces,+ },+ torch::TensorOptions().dtype(torch::kInt64).device(torch::kCPU))+ .contiguous();++ auto vert_accessor = vertices.accessor<float, 2>();+ auto indices_accessor = indices.accessor<int64_t, 2>();+ auto face_uv_accessor = face_uv.accessor<float, 2>();++ const int64_t *face_index_ptr = face_index.contiguous().data_ptr<int64_t>();+ int64_t *assign_indices_ptr = assign_indices.data_ptr<int64_t>();+ // copy face_index to assign_indices+ memcpy(assign_indices_ptr, face_index_ptr, num_faces * sizeof(int64_t));++#ifdef TIMING+ auto start = std::chrono::high_resolution_clock::now();+#endif+ uv_float3 *vertex_tri_centroids = new uv_float3[num_faces];+ Triangle *triangles = new Triangle[num_faces];++ // Use std::set to store triangles for each face+ std::vector<std::set<int>> triangle_per_face;+ triangle_per_face.resize(13);++#pragma omp parallel for+ for (int i = 0; i < num_faces; i++) {+ int face_idx = i * 3;+ triangles[i].v0 = {face_uv_accessor[face_idx + 0][0],+ face_uv_accessor[face_idx + 0][1]};+ triangles[i].v1 = {face_uv_accessor[face_idx + 1][0],+ face_uv_accessor[face_idx + 1][1]};+ triangles[i].v2 = {face_uv_accessor[face_idx + 2][0],+ face_uv_accessor[face_idx + 2][1]};+ triangles[i].centroid =+ triangle_centroid(triangles[i].v0, triangles[i].v1, triangles[i].v2);++ uv_float3 v0 = {vert_accessor[indices_accessor[i][0]][0],+ vert_accessor[indices_accessor[i][0]][1],+ vert_accessor[indices_accessor[i][0]][2]};+ uv_float3 v1 = {vert_accessor[indices_accessor[i][1]][0],+ vert_accessor[indices_accessor[i][1]][1],+ vert_accessor[indices_accessor[i][1]][2]};+ uv_float3 v2 = {vert_accessor[indices_accessor[i][2]][0],+ vert_accessor[indices_accessor[i][2]][1],+ vert_accessor[indices_accessor[i][2]][2]};+ vertex_tri_centroids[i] = triangle_centroid(v0, v1, v2);++// Assign the triangle to the face index+#pragma omp critical+ { triangle_per_face[face_index_ptr[i]].insert(i); }+ }++#ifdef TIMING+ auto start_bvh = std::chrono::high_resolution_clock::now();+#endif++ BVH *bvhs = new BVH[6];+ create_bvhs(bvhs, triangles, triangle_per_face, num_faces, 0, 6);++#ifdef TIMING+ auto end_bvh = std::chrono::high_resolution_clock::now();+ std::chrono::duration<double> elapsed_seconds = end_bvh - start_bvh;+ std::cout << "BVH build time: " << elapsed_seconds.count() << "s\n";++ auto start_intersection_1 = std::chrono::high_resolution_clock::now();+#endif++ perform_intersection_check(bvhs, 6, triangles, vertex_tri_centroids,+ assign_indices_ptr, num_faces, 0,+ triangle_per_face);++#ifdef TIMING+ auto end_intersection_1 = std::chrono::high_resolution_clock::now();+ elapsed_seconds = end_intersection_1 - start_intersection_1;+ std::cout << "Intersection 1 time: " << elapsed_seconds.count() << "s\n";+#endif+ // Create 6 new bvhs and delete the old ones+ BVH *new_bvhs = new BVH[6];+ create_bvhs(new_bvhs, triangles, triangle_per_face, num_faces, 6, 12);++#ifdef TIMING+ auto end_bvh2 = std::chrono::high_resolution_clock::now();+ elapsed_seconds = end_bvh2 - end_intersection_1;+ std::cout << "BVH 2 build time: " << elapsed_seconds.count() << "s\n";+ auto start_intersection_2 = std::chrono::high_resolution_clock::now();+#endif++ perform_intersection_check(new_bvhs, 6, triangles, vertex_tri_centroids,+ assign_indices_ptr, num_faces, 6,+ triangle_per_face);++#ifdef TIMING+ auto end_intersection_2 = std::chrono::high_resolution_clock::now();+ elapsed_seconds = end_intersection_2 - start_intersection_2;+ std::cout << "Intersection 2 time: " << elapsed_seconds.count() << "s\n";+ elapsed_seconds = end_intersection_2 - start;+ std::cout << "Total time: " << elapsed_seconds.count() << "s\n";+#endif++ // Cleanup+ delete[] vertex_tri_centroids;+ delete[] triangles;+ delete[] bvhs;+ delete[] new_bvhs;++ return assign_indices;+}++// Registers _C as a Python extension module.+PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {}++// Defines the operators+TORCH_LIBRARY(UVUnwrapper, m) {+ m.def("assign_faces_uv_to_atlas_index(Tensor vertices, Tensor indices, "+ "Tensor face_uv, Tensor face_index) -> Tensor");+}++// Registers CPP implementations+TORCH_LIBRARY_IMPL(UVUnwrapper, CPU, m) {+ m.impl("assign_faces_uv_to_atlas_index", &assign_faces_uv_to_atlas_index);+}++} // namespace UVUnwrapperdiff --git a/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/unwrap.py b/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/unwrap.pynew file mode 100644index 000000000..658656449--- /dev/null+++ b/apps/forge-desktop/api/uv_unwrapper/uv_unwrapper/unwrap.py@@ -0,0 +1,669 @@+import math+from typing import Tuple++import torch+import torch.nn as nn+import torch.nn.functional as F+from torch import Tensor+++class Unwrapper(nn.Module):+ def __init__(self):+ super().__init__()++ def _box_assign_vertex_to_cube_face(+ self,+ vertex_positions: Tensor,+ vertex_normals: Tensor,+ triangle_idxs: Tensor,+ bbox: Tensor,+ ) -> Tuple[Tensor, Tensor]:+ """+ Assigns each vertex to a cube face based on the face normal++ Args:+ vertex_positions (Tensor, Nv 3, float): Vertex positions+ vertex_normals (Tensor, Nv 3, float): Vertex normals+ triangle_idxs (Tensor, Nf 3, int): Triangle indices+ bbox (Tensor, 2 3, float): Bounding box of the mesh++ Returns:+ Tensor, Nf 3 2, float: UV coordinates+ Tensor, Nf, int: Cube face indices+ """++ # Test to not have a scaled model to fit the space better+ # bbox_min = bbox[:1].mean(-1, keepdim=True)+ # bbox_max = bbox[1:].mean(-1, keepdim=True)+ # v_pos_normalized = (vertex_positions - bbox_min) / (bbox_max - bbox_min)++ # Create a [0, 1] normalized vertex position+ v_pos_normalized = (vertex_positions - bbox[:1]) / (bbox[1:] - bbox[:1])+ # And to [-1, 1]+ v_pos_normalized = 2.0 * v_pos_normalized - 1.0++ # Get all vertex positions for each triangle+ # Now how do we define to which face the triangle belongs? Mean face pos? Max vertex pos?+ v0 = v_pos_normalized[triangle_idxs[:, 0]]+ v1 = v_pos_normalized[triangle_idxs[:, 1]]+ v2 = v_pos_normalized[triangle_idxs[:, 2]]+ tri_stack = torch.stack([v0, v1, v2], dim=1)++ vn0 = vertex_normals[triangle_idxs[:, 0]]+ vn1 = vertex_normals[triangle_idxs[:, 1]]+ vn2 = vertex_normals[triangle_idxs[:, 2]]+ tri_stack_nrm = torch.stack([vn0, vn1, vn2], dim=1)++ # Just average the normals per face+ face_normal = F.normalize(torch.sum(tri_stack_nrm, 1), eps=1e-6, dim=-1)++ # Now decide based on the face normal in which box map we project+ # abs_x, abs_y, abs_z = tri_stack_nrm.abs().unbind(-1)+ abs_x, abs_y, abs_z = tri_stack.abs().unbind(-1)++ axis = torch.tensor(+ [+ [1, 0, 0], # 0+ [-1, 0, 0], # 1+ [0, 1, 0], # 2+ [0, -1, 0], # 3+ [0, 0, 1], # 4+ [0, 0, -1], # 5+ ],+ device=face_normal.device,+ dtype=face_normal.dtype,+ )+ face_normal_axis = (face_normal[:, None] * axis[None]).sum(-1)+ index = face_normal_axis.argmax(-1)++ max_axis, uc, vc = (+ torch.ones_like(abs_x),+ torch.zeros_like(tri_stack[..., :1]),+ torch.zeros_like(tri_stack[..., :1]),+ )+ mask_pos_x = index == 0+ max_axis[mask_pos_x] = abs_x[mask_pos_x]+ uc[mask_pos_x] = tri_stack[mask_pos_x][..., 1:2]+ vc[mask_pos_x] = -tri_stack[mask_pos_x][..., -1:]++ mask_neg_x = index == 1+ max_axis[mask_neg_x] = abs_x[mask_neg_x]+ uc[mask_neg_x] = tri_stack[mask_neg_x][..., 1:2]+ vc[mask_neg_x] = -tri_stack[mask_neg_x][..., -1:]++ mask_pos_y = index == 2+ max_axis[mask_pos_y] = abs_y[mask_pos_y]+ uc[mask_pos_y] = tri_stack[mask_pos_y][..., 0:1]+ vc[mask_pos_y] = -tri_stack[mask_pos_y][..., -1:]++ mask_neg_y = index == 3+ max_axis[mask_neg_y] = abs_y[mask_neg_y]+ uc[mask_neg_y] = tri_stack[mask_neg_y][..., 0:1]+ vc[mask_neg_y] = -tri_stack[mask_neg_y][..., -1:]++ mask_pos_z = index == 4+ max_axis[mask_pos_z] = abs_z[mask_pos_z]+ uc[mask_pos_z] = tri_stack[mask_pos_z][..., 0:1]+ vc[mask_pos_z] = tri_stack[mask_pos_z][..., 1:2]++ mask_neg_z = index == 5+ max_axis[mask_neg_z] = abs_z[mask_neg_z]+ uc[mask_neg_z] = tri_stack[mask_neg_z][..., 0:1]+ vc[mask_neg_z] = -tri_stack[mask_neg_z][..., 1:2]++ # UC from [-1, 1] to [0, 1]+ max_dim_div = max_axis.max(dim=0, keepdim=True).values+ uc = ((uc[..., 0] / max_dim_div + 1.0) * 0.5).clip(0, 1)+ vc = ((vc[..., 0] / max_dim_div + 1.0) * 0.5).clip(0, 1)++ uv = torch.stack([uc, vc], dim=-1)++ return uv, index++ def _assign_faces_uv_to_atlas_index(+ self,+ vertex_positions: Tensor,+ triangle_idxs: Tensor,+ face_uv: Tensor,+ face_index: Tensor,+ ) -> Tensor: # noqa: F821+ """+ Assigns the face UV to the atlas index++ Args:+ vertex_positions (Float[Tensor, "Nv 3"]): Vertex positions+ triangle_idxs (Integer[Tensor, "Nf 3"]): Triangle indices+ face_uv (Float[Tensor, "Nf 3 2"]): Face UV coordinates+ face_index (Integer[Tensor, "Nf"]): Face indices++ Returns:+ Integer[Tensor, "Nf"]: Atlas index+ """+ return torch.ops.UVUnwrapper.assign_faces_uv_to_atlas_index(+ vertex_positions.cpu(),+ triangle_idxs.cpu(),+ face_uv.view(-1, 2).cpu(),+ face_index.cpu(),+ ).to(vertex_positions.device)++ def _find_slice_offset_and_scale(+ self, index: Tensor+ ) -> Tuple[Tensor, Tensor, Tensor, Tensor]: # noqa: F821+ """+ Find the slice offset and scale++ Args:+ index (Integer[Tensor, "Nf"]): Atlas index++ Returns:+ Float[Tensor, "Nf"]: Offset x+ Float[Tensor, "Nf"]: Offset y+ Float[Tensor, "Nf"]: Division x+ Float[Tensor, "Nf"]: Division y+ """++ # 6 due to the 6 cube faces+ off = 1 / 3+ dupl_off = 1 / 6++ # Here, we need to decide how to pack the textures in the case of overlap+ def x_offset_calc(x, i):+ offset_calc = i // 6+ # Initial coordinates - just 3x2 grid+ if offset_calc == 0:+ return off * x+ else:+ # Smaller 3x2 grid plus eventual shift to right for+ # second overlap+ return dupl_off * x + min(offset_calc - 1, 1) * 0.5++ def y_offset_calc(x, i):+ offset_calc = i // 6+ # Initial coordinates - just a 3x2 grid+ if offset_calc == 0:+ return off * x+ else:+ # Smaller coordinates in the lowest row+ return dupl_off * x + off * 2++ offset_x = torch.zeros_like(index, dtype=torch.float32)+ offset_y = torch.zeros_like(index, dtype=torch.float32)+ offset_x_vals = [0, 1, 2, 0, 1, 2]+ offset_y_vals = [0, 0, 0, 1, 1, 1]+ for i in range(index.max().item() + 1):+ mask = index == i+ if not mask.any():+ continue+ offset_x[mask] = x_offset_calc(offset_x_vals[i % 6], i)+ offset_y[mask] = y_offset_calc(offset_y_vals[i % 6], i)++ div_x = torch.full_like(index, 6 // 2, dtype=torch.float32)+ # All overlap elements are saved in half scale+ div_x[index >= 6] = 6+ div_y = div_x.clone() # Same for y+ # Except for the random overlaps+ div_x[index >= 12] = 2+ # But the random overlaps are saved in a large block in the lower thirds+ div_y[index >= 12] = 3++ return offset_x, offset_y, div_x, div_y++ def _calculate_tangents(+ self,+ vertex_positions: Tensor,+ vertex_normals: Tensor,+ triangle_idxs: Tensor,+ face_uv: Tensor,+ ) -> Tensor:+ """+ Calculate the tangents for each triangle++ Args:+ vertex_positions (Float[Tensor, "Nv 3"]): Vertex positions+ vertex_normals (Float[Tensor, "Nv 3"]): Vertex normals+ triangle_idxs (Integer[Tensor, "Nf 3"]): Triangle indices+ face_uv (Float[Tensor, "Nf 3 2"]): Face UV coordinates++ Returns:+ Float[Tensor, "Nf 3 4"]: Tangents+ """+ vn_idx = [None] * 3+ pos = [None] * 3+ tex = face_uv.unbind(1)+ for i in range(0, 3):+ pos[i] = vertex_positions[triangle_idxs[:, i]]+ # t_nrm_idx is always the same as t_pos_idx+ vn_idx[i] = triangle_idxs[:, i]++ if(torch.backends.mps.is_available()):+ tangents = torch.zeros_like(vertex_normals).contiguous()+ tansum = torch.zeros_like(vertex_normals).contiguous()+ else:+ tangents = torch.zeros_like(vertex_normals)+ tansum = torch.zeros_like(vertex_normals)++ # Compute tangent space for each triangle+ duv1 = tex[1] - tex[0]+ duv2 = tex[2] - tex[0]+ dpos1 = pos[1] - pos[0]+ dpos2 = pos[2] - pos[0]++ tng_nom = dpos1 * duv2[..., 1:2] - dpos2 * duv1[..., 1:2]++ denom = duv1[..., 0:1] * duv2[..., 1:2] - duv1[..., 1:2] * duv2[..., 0:1]++ # Avoid division by zero for degenerated texture coordinates+ denom_safe = denom.clip(1e-6)+ tang = tng_nom / denom_safe++ # Update all 3 vertices+ for i in range(0, 3):+ idx = vn_idx[i][:, None].repeat(1, 3)+ tangents.scatter_add_(0, idx, tang) # tangents[n_i] = tangents[n_i] + tang+ tansum.scatter_add_(+ 0, idx, torch.ones_like(tang)+ ) # tansum[n_i] = tansum[n_i] + 1+ # Also normalize it. Here we do not normalize the individual triangles first so larger area+ # triangles influence the tangent space more+ tangents = tangents / tansum++ # Normalize and make sure tangent is perpendicular to normal+ tangents = F.normalize(tangents, dim=1)+ tangents = F.normalize(+ tangents+ - (tangents * vertex_normals).sum(-1, keepdim=True) * vertex_normals+ )++ return tangents++ def _rotate_uv_slices_consistent_space(+ self,+ vertex_positions: Tensor,+ vertex_normals: Tensor,+ triangle_idxs: Tensor,+ uv: Tensor,+ index: Tensor,+ ) -> Tensor:+ """+ Rotate the UV slices so they are in a consistent space++ Args:+ vertex_positions (Float[Tensor, "Nv 3"]): Vertex positions+ vertex_normals (Float[Tensor, "Nv 3"]): Vertex normals+ triangle_idxs (Integer[Tensor, "Nf 3"]): Triangle indices+ uv (Float[Tensor, "Nf 3 2"]): UV coordinates+ index (Integer[Tensor, "Nf"]): Atlas index++ Returns:+ Float[Tensor, "Nf 3 2"]: Rotated UV coordinates+ """++ tangents = self._calculate_tangents(+ vertex_positions, vertex_normals, triangle_idxs, uv+ )+ pos_stack = torch.stack(+ [+ -vertex_positions[..., 1],+ vertex_positions[..., 0],+ torch.zeros_like(vertex_positions[..., 0]),+ ],+ dim=-1,+ )+ expected_tangents = F.normalize(+ torch.linalg.cross(+ vertex_normals,+ torch.linalg.cross(pos_stack, vertex_normals, dim=-1),+ dim=-1,+ ),+ -1,+ )++ actual_tangents = tangents[triangle_idxs]+ expected_tangents = expected_tangents[triangle_idxs]++ def rotation_matrix_2d(theta):+ c, s = torch.cos(theta), torch.sin(theta)+ return torch.tensor([[c, -s], [s, c]])++ # Now find the rotation+ index_mod = index % 6 # Shouldn't happen. Just for safety+ for i in range(6):+ mask = index_mod == i+ if not mask.any():+ continue++ actual_mean_tangent = actual_tangents[mask].mean(dim=(0, 1))+ expected_mean_tangent = expected_tangents[mask].mean(dim=(0, 1))++ dot_product = torch.dot(actual_mean_tangent, expected_mean_tangent)+ cross_product = (+ actual_mean_tangent[0] * expected_mean_tangent[1]+ - actual_mean_tangent[1] * expected_mean_tangent[0]+ )+ angle = torch.atan2(cross_product, dot_product)++ rot_matrix = rotation_matrix_2d(angle).to(mask.device)+ # Center the uv coordinate to be in the range of -1 to 1 and 0 centered+ uv_cur = uv[mask] * 2 - 1 # Center it first+ # Rotate it+ uv[mask] = torch.einsum("ij,nfj->nfi", rot_matrix, uv_cur)++ # Rescale uv[mask] to be within the 0-1 range+ uv[mask] = (uv[mask] - uv[mask].min()) / (uv[mask].max() - uv[mask].min())++ return uv++ def _handle_slice_uvs(+ self,+ uv: Tensor,+ index: Tensor, # noqa: F821+ island_padding: float,+ max_index: int = 6 * 2,+ ) -> Tensor: # noqa: F821+ """+ Handle the slice UVs++ Args:+ uv (Float[Tensor, "Nf 3 2"]): UV coordinates+ index (Integer[Tensor, "Nf"]): Atlas index+ island_padding (float): Island padding+ max_index (int): Maximum index++ Returns:+ Float[Tensor, "Nf 3 2"]: Updated UV coordinates++ """+ uc, vc = uv.unbind(-1)++ # Get the second slice (The first overlap)+ index_filter = [index == i for i in range(6, max_index)]++ # Normalize them to always fully fill the atlas patch+ for i, fi in enumerate(index_filter):+ if fi.sum() > 0:+ # Scale the slice but only up to a factor of 2+ # This keeps the texture resolution with the first slice in line (Half space in UV)+ uc[fi] = (uc[fi] - uc[fi].min()) / (uc[fi].max() - uc[fi].min()).clip(+ 0.5+ )+ vc[fi] = (vc[fi] - vc[fi].min()) / (vc[fi].max() - vc[fi].min()).clip(+ 0.5+ )++ uc_padded = (uc * (1 - 2 * island_padding) + island_padding).clip(0, 1)+ vc_padded = (vc * (1 - 2 * island_padding) + island_padding).clip(0, 1)++ return torch.stack([uc_padded, vc_padded], dim=-1)++ def _handle_remaining_uvs(+ self,+ uv: Tensor,+ index: Tensor, # noqa: F821+ island_padding: float,+ ) -> Tensor:+ """+ Handle the remaining UVs (The ones that are not slices)++ Args:+ uv (Float[Tensor, "Nf 3 2"]): UV coordinates+ index (Integer[Tensor, "Nf"]): Atlas index+ island_padding (float): Island padding++ Returns:+ Float[Tensor, "Nf 3 2"]: Updated UV coordinates+ """+ uc, vc = uv.unbind(-1)+ # Get all remaining elements+ remaining_filter = index >= 6 * 2+ squares_left = remaining_filter.sum()++ if squares_left == 0:+ return uv++ uc = uc[remaining_filter]+ vc = vc[remaining_filter]++ # Or remaining triangles are distributed in a rectangle+ # The rectangle takes 0.5 of the entire uv space in width and 1/3 in height+ ratio = 0.5 * (1 / 3) # 1.5+ # sqrt(744/(0.5*(1/3)))++ mult = math.sqrt(squares_left / ratio)+ num_square_width = int(math.ceil(0.5 * mult))+ num_square_height = int(math.ceil(squares_left / num_square_width))++ width = 1 / num_square_width+ height = 1 / num_square_height++ # The idea is again to keep the texture resolution consistent with the first slice+ # This only occupys half the region in the texture chart but the scaling on the squares+ # assumes full coverage.+ clip_val = min(width, height) * 1.5+ # Now normalize the UVs with taking into account the maximum scaling+ uc = (uc - uc.min(dim=1, keepdim=True).values) / (+ uc.amax(dim=1, keepdim=True) - uc.amin(dim=1, keepdim=True)+ ).clip(clip_val)+ vc = (vc - vc.min(dim=1, keepdim=True).values) / (+ vc.amax(dim=1, keepdim=True) - vc.amin(dim=1, keepdim=True)+ ).clip(clip_val)+ # Add a small padding+ uc = (+ uc * (1 - island_padding * num_square_width * 0.5)+ + island_padding * num_square_width * 0.25+ ).clip(0, 1)+ vc = (+ vc * (1 - island_padding * num_square_height * 0.5)+ + island_padding * num_square_height * 0.25+ ).clip(0, 1)++ uc = uc * width+ vc = vc * height++ # And calculate offsets for each element+ idx = torch.arange(uc.shape[0], device=uc.device, dtype=torch.int32)+ x_idx = idx % num_square_width+ y_idx = idx // num_square_width+ # And move each triangle to its own spot+ uc = uc + x_idx[:, None] * width+ vc = vc + y_idx[:, None] * height++ uc = (uc * (1 - 2 * island_padding * 0.5) + island_padding * 0.5).clip(0, 1)+ vc = (vc * (1 - 2 * island_padding * 0.5) + island_padding * 0.5).clip(0, 1)++ uv[remaining_filter] = torch.stack([uc, vc], dim=-1)++ return uv++ def _distribute_individual_uvs_in_atlas(+ self,+ face_uv: Tensor,+ assigned_faces: Tensor,+ offset_x: Tensor,+ offset_y: Tensor,+ div_x: Tensor,+ div_y: Tensor,+ island_padding: float,+ ) -> Tensor:+ """+ Distribute the individual UVs in the atlas++ Args:+ face_uv (Float[Tensor, "Nf 3 2"]): Face UV coordinates+ assigned_faces (Integer[Tensor, "Nf"]): Assigned faces+ offset_x (Float[Tensor, "Nf"]): Offset x+ offset_y (Float[Tensor, "Nf"]): Offset y+ div_x (Float[Tensor, "Nf"]): Division x+ div_y (Float[Tensor, "Nf"]): Division y+ island_padding (float): Island padding++ Returns:+ Float[Tensor, "Nf 3 2"]: Updated UV coordinates+ """+ # Place the slice first+ placed_uv = self._handle_slice_uvs(face_uv, assigned_faces, island_padding)+ # Then handle the remaining overlap elements+ placed_uv = self._handle_remaining_uvs(+ placed_uv, assigned_faces, island_padding+ )++ uc, vc = placed_uv.unbind(-1)+ uc = uc / div_x[:, None] + offset_x[:, None]+ vc = vc / div_y[:, None] + offset_y[:, None]++ uv = torch.stack([uc, vc], dim=-1).view(-1, 2)++ return uv++ def _get_unique_face_uv(+ self,+ uv: Tensor,+ ) -> Tuple[Tensor, Tensor]:+ """+ Get the unique face UV++ Args:+ uv (Float[Tensor, "Nf 3 2"]): UV coordinates++ Returns:+ Float[Tensor, "Utex 3"]: Unique UV coordinates+ Integer[Tensor, "Nf"]: Vertex index+ """+ unique_uv, unique_idx = torch.unique(uv, return_inverse=True, dim=0)+ # And add the face to uv index mapping+ vtex_idx = unique_idx.view(-1, 3)++ return unique_uv, vtex_idx++ def _align_mesh_with_main_axis(+ self, vertex_positions: Tensor, vertex_normals: Tensor+ ) -> Tuple[Tensor, Tensor]:+ """+ Align the mesh with the main axis++ Args:+ vertex_positions (Float[Tensor, "Nv 3"]): Vertex positions+ vertex_normals (Float[Tensor, "Nv 3"]): Vertex normals++ Returns:+ Float[Tensor, "Nv 3"]: Rotated vertex positions+ Float[Tensor, "Nv 3"]: Rotated vertex normals+ """++ # Use pca to find the 2 main axis (third is derived by cross product)+ # Set the random seed so it's repeatable+ torch.manual_seed(0)+ _, _, v = torch.pca_lowrank(vertex_positions, q=2)+ main_axis, seconday_axis = v[:, 0], v[:, 1]++ main_axis = F.normalize(main_axis, eps=1e-6, dim=-1) # 3,+ # Orthogonalize the second axis+ seconday_axis = F.normalize(+ seconday_axis+ - (seconday_axis * main_axis).sum(-1, keepdim=True) * main_axis,+ eps=1e-6,+ dim=-1,+ ) # 3,+ # Create perpendicular third axis+ third_axis = F.normalize(+ torch.cross(main_axis, seconday_axis, dim=-1), dim=-1, eps=1e-6+ ) # 3,++ # Check to which canonical axis each aligns+ main_axis_max_idx = main_axis.abs().argmax().item()+ seconday_axis_max_idx = seconday_axis.abs().argmax().item()+ third_axis_max_idx = third_axis.abs().argmax().item()++ # Now sort the axes based on the argmax so they align with thecanonoical axes+ # If two axes have the same argmax move one of them+ all_possible_axis = {0, 1, 2}+ cur_index = 1+ while (+ len(set([main_axis_max_idx, seconday_axis_max_idx, third_axis_max_idx]))+ != 3+ ):+ # Find missing axis+ missing_axis = all_possible_axis - set(+ [main_axis_max_idx, seconday_axis_max_idx, third_axis_max_idx]+ )+ missing_axis = missing_axis.pop()+ # Just assign it to third axis as it had the smallest contribution to the+ # overall shape+ if cur_index == 1:+ third_axis_max_idx = missing_axis+ elif cur_index == 2:+ seconday_axis_max_idx = missing_axis+ else:+ raise ValueError("Could not find 3 unique axis")+ cur_index += 1++ if len({main_axis_max_idx, seconday_axis_max_idx, third_axis_max_idx}) != 3:+ raise ValueError("Could not find 3 unique axis")++ axes = [None] * 3+ axes[main_axis_max_idx] = main_axis+ axes[seconday_axis_max_idx] = seconday_axis+ axes[third_axis_max_idx] = third_axis+ # Create rotation matrix from the individual axes+ rot_mat = torch.stack(axes, dim=1).T++ # Now rotate the vertex positions and vertex normals so the mesh aligns with the main axis+ vertex_positions = torch.einsum("ij,nj->ni", rot_mat, vertex_positions)+ vertex_normals = torch.einsum("ij,nj->ni", rot_mat, vertex_normals)++ return vertex_positions, vertex_normals++ def forward(+ self,+ vertex_positions: Tensor,+ vertex_normals: Tensor,+ triangle_idxs: Tensor,+ island_padding: float,+ ) -> Tuple[Tensor, Tensor]:+ """+ Unwrap the mesh++ Args:+ vertex_positions (Float[Tensor, "Nv 3"]): Vertex positions+ vertex_normals (Float[Tensor, "Nv 3"]): Vertex normals+ triangle_idxs (Integer[Tensor, "Nf 3"]): Triangle indices+ island_padding (float): Island padding++ Returns:+ Float[Tensor, "Utex 3"]: Unique UV coordinates+ Integer[Tensor, "Nf"]: Vertex index+ """+ vertex_positions, vertex_normals = self._align_mesh_with_main_axis(+ vertex_positions, vertex_normals+ )+ bbox = torch.stack(+ [vertex_positions.min(dim=0).values, vertex_positions.max(dim=0).values],+ dim=0,+ ) # 2, 3++ face_uv, face_index = self._box_assign_vertex_to_cube_face(+ vertex_positions, vertex_normals, triangle_idxs, bbox+ )++ face_uv = self._rotate_uv_slices_consistent_space(+ vertex_positions, vertex_normals, triangle_idxs, face_uv, face_index+ )++ assigned_atlas_index = self._assign_faces_uv_to_atlas_index(+ vertex_positions, triangle_idxs, face_uv, face_index+ )++ offset_x, offset_y, div_x, div_y = self._find_slice_offset_and_scale(+ assigned_atlas_index+ )++ placed_uv = self._distribute_individual_uvs_in_atlas(+ face_uv,+ assigned_atlas_index,+ offset_x,+ offset_y,+ div_x,+ div_y,+ island_padding,+ )++ return self._get_unique_face_uv(placed_uv)diff --git a/apps/forge-desktop/arch/decisions/AMD-ROCM-SUPPORT.md b/apps/forge-desktop/arch/decisions/AMD-ROCM-SUPPORT.mdnew file mode 100644index 000000000..09671fc76--- /dev/null+++ b/apps/forge-desktop/arch/decisions/AMD-ROCM-SUPPORT.md@@ -0,0 +1,100 @@+# AMD-ROCM-SUPPORT++- Status: proposed+- Date: 2026-08-17++## Decision++Modly supports AMD Radeon GPUs through ROCm on Linux and Windows. Detection is+automatic and requires no ROCm installation on the user's machine.++Scope and operating rules:++- Detection is centralised in `electron/main/gpu-detect.ts` and produces, for AMD+ machines, a compute target plus the pip index and requirements an extension's+ torch install must end up using.+- NVIDIA keeps detection priority. On a machine with both vendors the existing+ CUDA behaviour is unchanged.+- AMD machines report `gpu_sm = 0` and `cuda_version = 0`, never a synthesised+ compute capability.+- Extensions are told the flavour via a `torch_flavor` setup argument. Extensions+ that ignore it are corrected by a rewrite shim in `electron/main/setup-launcher.ts`.+- The ROCm wheel source differs by platform: `download.pytorch.org/whl/rocm7.2`+ on Linux, `repo.amd.com/rocm/whl-multi-arch/` on Windows.+- Every automatic choice has an environment-variable override. See+ `docs/running-on-amd-rocm.md`.++## Context++Modly never installs PyTorch itself. Each extension ships a `setup.py` that+creates its own venv and installs torch from an index it hardcodes — and those+scripts are third-party code in separate GitHub repositories that Modly cannot+edit. Before this work `detectGpuInfo()` only probed `nvidia-smi`, so an AMD+machine was reported as `accelerator: 'cpu'` with `gpu_sm: 0`, which sent every+extension down its legacy CUDA 11.8 branch and installed a torch that cannot see+the GPU at all.++That leaves two distinct problems, and both have to be solved:++- Extensions that *do* understand AMD were never told. The official+ `modly-hunyuan3d-mini-extension` has accepted a `torch_flavor: "rocm"` argument+ for some time; Modly simply never sent it.+- Extensions that don't understand AMD — `triposg`, `trellis2`, and the rest —+ hardcode `--index-url .../whl/cu124` and have no branch to select. Passing an+ argument achieves nothing for them.++The wheel sources are also not symmetric across platforms. `download.pytorch.org`+publishes no ROCm wheels for Windows at all; AMD's own multi-arch index does, but+there the compute target is selected by a pip extra (`torch[device-gfx1200]`)+rather than by the index URL, which means Windows needs the compute target+*before* the install, not after.++## Consequences++- **A rewrite shim is unavoidable.** Correcting extensions we cannot edit means+ intercepting their pip calls. The launcher already patched `subprocess` for two+ other compatibility fixes, so ROCm redirection joins those rather than+ introducing a new mechanism.+- **The decision is made in TypeScript, applied in Python.** The launcher is an+ inline Python string that cannot be unit-tested in isolation, so index and+ requirement resolution lives in `gpu-detect.ts` and reaches the launcher as+ environment variables. The launcher is separately exercised end-to-end by+ `setup-launcher.test.mjs`, which runs it against the command shapes the+ official extensions actually use.+- **`gpu_sm = 0` is load-bearing, not a placeholder.** Extensions written before+ `torch_flavor` branch on that number, and 0 selects their most conservative+ path. It also keeps them off `rembg[gpu]`, whose `onnxruntime-gpu` is+ CUDA-only. Reporting a synthesised capability instead would break both.+ PyTorch's HIP build answers the whole `torch.cuda` API, so+ `get_device_capability()` reports `(12, 0)` for a gfx1200 Radeon —+ indistinguishable from an sm_120 Blackwell. `api/routers/extensions.py` asks+ `nvidia-smi` rather than torch for this reason (and because Modly's main venv+ carries no torch at all).+- **Compute-target discovery is platform-specific.** Linux reads+ `gfx_target_version` from the kernel's KFD topology, which needs no ROCm+ install and no external binary. Windows has no equivalent, so it maps PCI+ device ids from `Win32_VideoController` through a table keyed by silicon. That+ table is a maintenance surface: new AMD silicon needs an entry, and an unmapped+ AMD card falls back to CPU with an actionable message rather than guessing a+ wheel.+- **The Linux and Windows torch versions diverge.** Linux gets unpinned wheels+ from the pytorch.org ROCm index (currently torch 2.11+); Windows gets a pinned+ pair from AMD's index. Extension code written against torch 2.6/2.7 may not+ survive that jump, which is why `MODLY_ROCM_INDEX` and `MODLY_ROCM_TORCH_SPEC`+ exist as first-class escape hatches rather than debug affordances.+- **Linux is verified, Windows is not.** On a Radeon RX 9060 XT (gfx1200),+ `torch 2.13.0+rocm7.2` loads, rocBLAS and MIOpen kernels execute, 14 GB of the+ card's 16 GB allocates and reads back cleanly ([ROCm #6295](https://github.com/ROCm/ROCm/issues/6295),+ which reports this card capped near 8 GB, did not reproduce), and a full+ image-to-3D generation completes through the normal `ExtensionProcess` path in+ 221 s. For Windows the wheel URLs, `cp311` availability and index layout were+ checked, but no end-to-end run has been performed.+- **This work also required fixing an unrelated AppImage bug** to be verifiable+ at all. `ensureStableEmbeddedPython()` copied the bundled runtime with+ `fs.cp`, which rewrites relative symlinks into absolute paths pointing back at+ the ephemeral `/tmp/.mount_Modly-XXXXXX/` mount — so the "stable" copy was not+ stable, and every extension venv built from it died on the next launch with a+ misleading `No module named 'PIL'`. See `electron/main/copy-runtime.ts`.+- **Texture generation is out of scope.** `api/texture_baker` already carries a+ HIP build path, but those native extensions are not built as part of standard+ extension setup, so texture generation is not covered by this ADR.diff --git a/apps/forge-desktop/arch/decisions/APPLE-SILICON-SUPPORT.md b/apps/forge-desktop/arch/decisions/APPLE-SILICON-SUPPORT.mdnew file mode 100644index 000000000..c49c15351--- /dev/null+++ b/apps/forge-desktop/arch/decisions/APPLE-SILICON-SUPPORT.md@@ -0,0 +1,114 @@+# APPLE-SILICON-SUPPORT++- Status: proposed+- Date: 2026-04-23++## Decision++Modly supports macOS on Apple Silicon (`darwin/arm64`) as a first-class+platform. This ADR consolidates the runtime, packaging, extension, and+workflow rules needed to run the image-to-mesh pipeline reliably on 16 GB+unified-memory Macs.++Scope and operating rules:++- macOS support targets Apple Silicon only. See `package.json:99`.+- Intel macOS, universal binaries, and Rosetta fallback are out of scope.+- Model weights stay separate from extension code and are installed per node. See `api/routers/model.py:76` and `api/runner.py:101`.+- The Mac workflow is sequential and memory-budgeted: one heavy generative+ stage resident at a time. See `src/areas/workflows/workflowRunStore.ts:185`.+- Download/install state must be observable and resumable. See `electron/main/model-downloader.ts:116`.+- Releasing GPU memory means terminating the owning subprocess. See `api/services/extension_process.py:205` and `electron/main/index.ts:105`.+- Generation progress and cancel behavior must remain visible and responsive in+ the UI. See `api/services/extension_process.py:135` and `src/areas/workflows/workflowRunStore.ts:232`.++## Context++Apple Silicon changes the constraints under which Modly runs:++- Unified memory means overlapping heavy GPU stages can destabilize the whole+ machine on 16 GB systems.+- Metal/MPS memory is not returned predictably by Python-side cleanup alone;+ process exit is the reliable release boundary.+- Large model downloads need byte-level visibility, stall detection, and proper+ resume behavior to avoid appearing hung or silently reinstalling from zero.+- Extension manifests now need per-node distribution metadata because one+ extension can expose multiple model variants that share code but differ in+ weights, defaults, and required artifacts.+- Workflow graphs need preflight validation before execution so invalid wiring+ is reported without replacing the current mesh view with a terminal error+ state.+- The renderer needs progress text that stays live through long native phases+ and a cancel path that clears UI state immediately even if backend teardown+ takes longer.++## Consequences++- Packaging:+ Modly packages macOS as an Apple Silicon build path only, including the+ embedded Python runtime in the app bundle. See `package.json:99`.++- Extension and model distribution:+ Extension payloads contain code, manifests, setup scripts, and lightweight+ assets. Model nodes declare their own `download_check`, can narrow downloads+ with `hf_include_prefixes` and `hf_skip_prefixes`, and may provide+ node-specific `params_schema` and `param_defaults` with top-level fallback.+ See `api/routers/model.py:76`, `api/runner.py:84`, and+ `electron/main/model-downloader.ts:116`.++- Runtime selection and defaults:+ The runner resolves the active node from `MODEL_DIR` so multi-node extensions+ use the correct schema, model directory, and node-specific metadata. Workflow+ submission merges displayed parameter defaults under user overrides before the+ request reaches Python. See `api/runner.py:84` and+ `src/areas/workflows/workflowRunStore.ts:207`.++- Mesh optimization path handling:+ Smooth and decimate operations accept both workspace-relative meshes and+ imported absolute-path meshes, then write optimized output back into the+ workspace so the result remains visible and reusable in the app. See+ `api/routers/optimize.py:42` and `src/areas/generate/GeneratePage.tsx:331`.++- Memory-budgeted workflow:+ Heavy stages hand off through files and unload before the next heavy stage+ begins. CPU-oriented stages can run between GPU-heavy stages without+ competing for MPS residency. See `electron/main/index.ts:105`,+ `api/services/extension_process.py:214`, and+ `src/areas/workflows/workflowRunStore.ts:142`.++- Download behavior:+ The downloader emits byte-level progress, file context, and stall state.+ Partial downloads are preserved as `.part` files. Resume is attempted against+ the resolved final URL so `Range` works even when upstream redirects to a CDN.+ Install completion is verified by the declared `download_check`, not by+ directory existence alone. See `electron/main/model-downloader.ts:10`,+ `electron/main/model-downloader.ts:31`, and `api/routers/model.py:84`.++- Subprocess lifecycle:+ Extension subprocesses are owned as a full process tree. On Unix, the Python+ bridge runs as its own process-group leader and Modly kills the process group+ on quit. Free-memory/unload operations hard-stop the subprocess. Cancel first+ sends a cooperative request, then escalates to a kill after a short grace+ period if native code is still blocking. See `api/services/extension_process.py:78`+ and `electron/main/index.ts:112`.++- Observability and UX:+ Generator stderr stays available for tqdm-style progress parsing, long phases+ surface readable status text, and cancel clears renderer job state+ immediately. Workflow editors run a preflight pass before execution and+ surface wiring problems through inline warnings and toasts instead of+ replacing the current mesh view. Error output in the HUD remains+ copyable/selectable. The top bar includes a live RAM indicator backed by a+ main-process `system:memory` IPC call; macOS uses `vm_stat` to approximate+ Activity Monitor's "Memory Used" semantics and other platforms fall back to+ `total - free`. macOS uses native window controls instead of custom+ right-side controls. See+ `api/services/extension_process.py:135`,+ `src/areas/workflows/preflight.ts:51`,+ `src/areas/generate/components/WorkflowPanel.tsx:425`,+ `src/areas/workflows/WorkflowsPage.tsx:847`,+ `src/shared/components/ui/Toast.tsx:4`,+ `electron/main/ipc-handlers.ts:372`,+ `src/shared/components/layout/MemoryIndicator.tsx:9`,+ `src/shared/components/layout/TopBar.tsx:4`, and+ `src/areas/setup/FirstRunSetup.tsx:258`.diff --git a/apps/forge-desktop/arch/decisions/README.md b/apps/forge-desktop/arch/decisions/README.mdnew file mode 100644index 000000000..925441ea0--- /dev/null+++ b/apps/forge-desktop/arch/decisions/README.md@@ -0,0 +1,11 @@+# Architecture Decisions++This directory stores architecture decision records for Modly.++The current Apple Silicon support work is documented in one consolidated ADR so+the platform scope, runtime assumptions, and operational constraints stay in a+single reviewable document.++Current ADRs:+- [APPLE-SILICON-SUPPORT](./APPLE-SILICON-SUPPORT.md)+- [AMD-ROCM-SUPPORT](./AMD-ROCM-SUPPORT.md)diff --git a/apps/forge-desktop/docs/app-screenshot.png b/apps/forge-desktop/docs/app-screenshot.pngnew file mode 100644index 000000000..c59c1320bBinary files /dev/null and b/apps/forge-desktop/docs/app-screenshot.png differdiff --git a/apps/forge-desktop/docs/install-extension.png b/apps/forge-desktop/docs/install-extension.pngnew file mode 100644index 000000000..f64b545f5Binary files /dev/null and b/apps/forge-desktop/docs/install-extension.png differdiff --git a/apps/forge-desktop/docs/install-from-github.png b/apps/forge-desktop/docs/install-from-github.pngnew file mode 100644index 000000000..1de4163aeBinary files /dev/null and b/apps/forge-desktop/docs/install-from-github.png differdiff --git a/apps/forge-desktop/docs/install-models.png b/apps/forge-desktop/docs/install-models.pngnew file mode 100644index 000000000..1c4ca09bdBinary files /dev/null and b/apps/forge-desktop/docs/install-models.png differdiff --git a/apps/forge-desktop/docs/running-on-amd-rocm.md b/apps/forge-desktop/docs/running-on-amd-rocm.mdnew file mode 100644index 000000000..5fe60f8aa--- /dev/null+++ b/apps/forge-desktop/docs/running-on-amd-rocm.md@@ -0,0 +1,193 @@+# Running Modly on an AMD GPU (ROCm)++Modly's default GPU path is NVIDIA/CUDA (plus Metal/MPS on Apple Silicon). This page+covers the AMD path: how Modly detects a Radeon card, which PyTorch wheels it steers+extensions to, and what to do when the automatic choice is wrong.++Nothing here needs a manual setup: install the app, install an extension, and the AMD+path is taken automatically when an AMD GPU is present.++---++## 1. Requirements++| | Linux | Windows |+|---|---|---|+| GPU | RDNA 2 or newer discrete Radeon (see the table below) | same |+| Driver | in-tree `amdgpu` kernel driver — any recent distro kernel | Adrenalin with the ROCm runtime (26.2.2 or newer) |+| ROCm install | **not required** — the PyTorch ROCm wheels bundle their own runtime | not required |+| Device access | `/dev/kfd` and `/dev/dri/renderD*` must be readable by your user | n/a |++On most distributions `/dev/kfd` is world-accessible. If it is not, add yourself to the+`render` group and log back in:++```bash+ls -l /dev/kfd # crw-rw-rw- → nothing to do+sudo usermod -aG render "$USER"+```++Integrated (APU) graphics are not mapped by the Windows detection table. They work on+Linux whenever the kernel publishes a compute target, but they are not a target Modly+tests against.++---++## 2. How detection works++Detection lives in `electron/main/gpu-detect.ts` and runs before an extension's+`setup.py`, in this order:++1. `MODLY_TORCH_FLAVOR` (`cuda` / `rocm` / `cpu`) — an explicit override wins over everything.+2. Apple Silicon → MPS.+3. `nvidia-smi` → CUDA. **NVIDIA keeps priority**: on a machine with both vendors,+ nothing about the existing CUDA behaviour changes.+4. AMD:+ - **Linux** — reads `gfx_target_version` from the kernel's KFD topology+ (`/sys/class/kfd/kfd/topology/nodes/*/properties`). No ROCm install and no external+ binary involved; the `amdgpu` driver publishes this on its own.+ - **Windows** — reads the PCI device id from `Win32_VideoController` via PowerShell+ and maps it to a compute target.+5. Otherwise → CPU.++You can check what was detected in the logs (Settings → Logs), on the line beginning+`[ext-setup] accelerator=`:++```+[ext-setup] accelerator=rocm gfx=gfx1200 torch_index=https://download.pytorch.org/whl/rocm7.2+```++### Supported compute targets++| Silicon | Compute target | Cards |+|---|---|---|+| Navi 44 | `gfx1200` | RX 9060 XT |+| Navi 48 | `gfx1201` | RX 9070, RX 9070 XT, RX 9070 GRE, AI PRO R9700 |+| Navi 31 | `gfx1100` | RX 7900 XT/XTX/GRE, PRO W7800/W7900 |+| Navi 32 | `gfx1101` | RX 7700 XT, RX 7800 XT, PRO W7700 |+| Navi 33 | `gfx1102` | RX 7600 series, PRO W7500/W7600 |+| Navi 21 | `gfx1030` | RX 6800/6800 XT/6900 XT/6950 XT, PRO W6800 |+| Navi 22/23/24 | `gfx1031` / `gfx1032` / `gfx1034` | RX 6700 / 6600 / 6400 series |++On Linux the target is read from the kernel, so any AMD GPU the kernel knows about is+picked up — the table above only bounds the *Windows* mapping. AMD officially supports+`gfx1030`, `gfx110x` and `gfx120x`; the RDNA 2 mid-range entries work in practice but+are not part of AMD's supported matrix.++---++## 3. Which wheels get installed++Modly does not install PyTorch itself — each extension's `setup.py` does, from an index+it hardcodes. On an AMD machine Modly corrects that choice two ways:++- It passes `torch_flavor: "rocm"` in the setup arguments. Extensions that know about+ AMD (the official `hunyuan3d-mini` one does) branch on it themselves.+- For every extension that doesn't, a compatibility shim in the setup launcher rewrites+ the pip command: the CUDA (or CPU) index is swapped for the ROCm one, and the pinned+ `torch==…` requirements are replaced. Non-torch installs are left untouched.++| Platform | Index | Requirements |+|---|---|---|+| Linux | `https://download.pytorch.org/whl/rocm7.2` | `torch`, `torchvision`, unpinned |+| Windows | `https://repo.amd.com/rocm/whl-multi-arch/` | `torch[device-gfxNNNN]==2.11.0+rocm7.14.0` and matching `torchvision` |++The two differ because `download.pytorch.org` publishes no ROCm wheels for Windows at+all. AMD's multi-arch index does, and there the compute target is selected by a pip+extra rather than by the index URL.++`sm` and `cuda_version` are deliberately reported as `0` for AMD. Extensions written+before `torch_flavor` existed branch on those numbers, and `0` sends them down their+most conservative path — which also keeps them off `rembg[gpu]`, whose `onnxruntime-gpu`+is CUDA-only.++---++## 4. Verifying an install++After installing an extension (or running **Repair** on it from the Models page), check+what actually landed in its venv:++```bash+# Linux; adjust to your extensions directory+EXT=~/Documents/Modly/extensions/hunyuan3d-mini+"$EXT/venv/bin/python" -c "import torch; print(torch.__version__, '| hip', torch.version.hip, '| avail', torch.cuda.is_available(), '|', torch.cuda.get_device_name(0))"+```++Expected: a `+rocm…` version, a non-null `hip`, `True`, and your card's name. A version+ending in `+cu118` or `+cu124` means the AMD path was not taken — check the detection+line in the logs.++Then confirm real VRAM is usable, not just that the device opens:++```bash+"$EXT/venv/bin/python" -c "import torch; x = torch.empty(5_000_000_000, dtype=torch.float16, device='cuda'); torch.cuda.synchronize(); print('10 GB allocated OK')"+```++---++## 5. Escape hatches++All of these are environment variables read at detection time — set them before+launching Modly.++| Variable | Effect |+|---|---|+| `MODLY_TORCH_FLAVOR` | `cuda` / `rocm` / `cpu`. Forces the path, skipping detection entirely. |+| `MODLY_ROCM_GFX` | Forces the compute target (e.g. `gfx1201`). Needed for an AMD card the Windows table doesn't map. |+| `MODLY_ROCM_INDEX` | Overrides the pip index, e.g. `https://download.pytorch.org/whl/rocm6.4` to fall back to torch 2.8/2.9. |+| `MODLY_ROCM_TORCH_SPEC` | Overrides the requirements entirely, space-separated: `"torch==2.9.1 torchvision==0.24.1"`. |+| `HSA_OVERRIDE_GFX_VERSION` | ROCm's own override, for cards without native kernels (e.g. `10.3.0` on an unsupported RDNA 2 part). Not needed on RDNA 3/4. |++After changing any of these, run **Repair** on the extension so its venv is rebuilt.++---++## 6. Troubleshooting++| Symptom | Cause | Fix |+|---|---|---|+| Logs say `accelerator=cpu` on an AMD machine | `/dev/kfd` missing or unreadable (Linux), or an unmapped PCI id (Windows) | Check `ls -l /dev/kfd`; on Windows set `MODLY_ROCM_GFX` |+| `torch.__version__` ends in `+cu118` | Extension venv predates AMD support | Run **Repair** on the extension |+| `torch.cuda.is_available()` is `False` with a ROCm build | Device nodes not accessible from the process | Add your user to the `render` group, log back in |+| `HIP error: invalid device function` | Wheel has no kernels for your card | Set `HSA_OVERRIDE_GFX_VERSION` to a supported nearby target |+| Extension imports fail after install (`diffusers`/`transformers`) | The ROCm index only carries recent torch (2.11+), newer than some extensions expect | `MODLY_ROCM_INDEX=https://download.pytorch.org/whl/rocm6.4`, then **Repair** |+| Allocations above ~8 GB segfault on a 16 GB RX 9060 XT | [ROCm issue #6295](https://github.com/ROCm/ROCm/issues/6295) — did not reproduce on torch 2.13.0+rocm7.2 (see below) | If you hit it, pin an older stack via `MODLY_ROCM_INDEX` |++---++## 7. Verified configuration and limitations++The Linux path was measured end to end on a Radeon RX 9060 XT (Navi 44, gfx1200,+16 GB), CachyOS kernel 7.1.8, with the stack this page installs by default:++- `torch 2.13.0+rocm7.2` / `torchvision 0.28.0+rocm7.2`, HIP runtime 7.2.53211+- Detection reported `gfx1200`; `torch.cuda.is_available()` is `True` and+ `get_device_properties(0).gcnArchName` is `gfx1200`+- rocBLAS (fp16 matmul) and MIOpen (conv2d) kernels both execute — no+ `no kernel image is available` failures+- Allocations of 4/6/8/10/12/14 GB all succeeded, filled and read back.+ [ROCm #6295](https://github.com/ROCm/ROCm/issues/6295), which reports this exact+ card capped near 8 GB with a segfault, **did not reproduce** on this stack.+ It remains open upstream, so it may still affect older ROCm builds.+- A full image-to-3D generation with `hunyuan3d-mini` completed through the normal+ `ExtensionProcess` subprocess path: model load 18 s, generation 221 s, 15.8 MB GLB.++### Attention kernels++During generation PyTorch emits:++> Mem Efficient attention on Current AMD GPU is still experimental. Enable it with+> `TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1`++Generation works without it — `scaled_dot_product_attention` falls back to a+slower path. Setting `TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1` before launching+Modly enables the memory-efficient kernels, at the cost of running code AMD still+labels experimental on RDNA 3/4. Modly does not set it for you.++Limitations:++- **Windows is untested** by the Modly maintainers. The wheel URLs and the `cp311`+ availability were verified, but no end-to-end run has been done on that path.+- **Texture generation** relies on optional native extensions (`texture_baker`,+ `uv_unwrapper`) whose CUDA kernels have a HIP path but are not built as part of the+ standard extension setup.diff --git a/apps/forge-desktop/docs/running-on-jetson.md b/apps/forge-desktop/docs/running-on-jetson.mdnew file mode 100644index 000000000..4d21bdcba--- /dev/null+++ b/apps/forge-desktop/docs/running-on-jetson.md@@ -0,0 +1,326 @@+# Running Modly headless on an NVIDIA Jetson (AGX Orin, JetPack 6)++This guide explains how to run Modly's image-to-3D generation on an **NVIDIA Jetson**,+a platform Modly does not officially target. Jetson is `aarch64` with NVIDIA's+Tegra/L4T CUDA stack, so the desktop installers and the stock extension `setup.py`+(which assume `x86_64` + the standard CUDA wheels) don't work as-is.++The good news: **Modly's FastAPI backend is fully standalone and HTTP-driven**, so you+don't need Electron, a display, or the GUI. You run the backend on the Jetson and drive+it with `curl`. The only real work is building the model extension's venv with the+**Jetson-native** PyTorch and working around a broken ONNX Runtime.++> Verified on: **Jetson AGX Orin Developer Kit, 64 GB, JetPack 6.2 (L4T R36.4),+> Python 3.10, CUDA 12.6, compute capability sm_87.**+> Model: the base **Hunyuan3D-2 Mini** extension (`hunyuan3d-mini`), mesh-only+> (no texture). ~6 GB VRAM-class model; comfortable on a 32–64 GB Orin.++---++## TL;DR++The stock setup gets three things wrong on Jetson. After a normal headless install you must:++1. **Replace PyTorch.** The pinned `torch 2.5.1+cu124` SBSA wheel has **no `sm_87`+ kernels** (loads, but every kernel fails with *"no kernel image is available"*).+ Install the Jetson build from the [jetson-ai-lab](https://pypi.jetson-ai-lab.io) index.+2. **Pin `numpy < 2`.** The Jetson torch wheel is compiled against NumPy 1.x, so+ `torch.from_numpy` raises *"Numpy is not available"* under NumPy 2.+3. **Bypass `rembg` / ONNX Runtime.** ONNX Runtime crashes hard on the Tegra CPU+ (*"Unknown CPU vendor"* → C++ abort / segfault). Patch the extension's background+ removal to a NumPy/SciPy implementation.++Full steps below.++---++## 1. System prerequisites++```bash+sudo apt update+sudo apt install -y git python3-venv python3-pip+python3 --version # expect 3.10.x on JetPack 6+cat /etc/nv_tegra_release # confirm L4T R36.x (JetPack 6)+/usr/local/cuda/bin/nvcc --version | grep release # confirm CUDA 12.x+free -h # confirm enough unified memory (16 GB+ recommended)+```++Set up working directories and environment:++```bash+export EXTENSIONS_DIR=$HOME/.modly/extensions+export MODELS_DIR=$HOME/.modly/models+export WORKSPACE_DIR=$HOME/.modly/workspace+mkdir -p "$EXTENSIONS_DIR" "$MODELS_DIR" "$WORKSPACE_DIR"+```++---++## 2. Clone Modly and build the API backend venv++The backend itself contains **no PyTorch**; it's just the FastAPI orchestrator plus+mesh post-processing (`trimesh`, `pymeshlab`). `pymeshlab` has `aarch64` wheels, so this+installs cleanly.++```bash+git clone https://github.com/lightningpixel/modly.git ~/modly+cd ~/modly/api+python3 -m venv .venv+./.venv/bin/pip install -U pip+./.venv/bin/pip install -r requirements.txt+```++---++## 3. Fetch the model extension++```bash+git clone https://github.com/lightningpixel/modly-hunyuan3d-mini-extension.git \+ "$EXTENSIONS_DIR/hunyuan3d-mini"+```++The base **Hunyuan3D-2 Mini** extension is the best starting point on Jetson:++- mesh-only generation needs **no native/C++ build** (the texture path's+ `custom_rasterizer` / `differentiable_renderer` are only imported when+ `enable_texture=true`);+- the `hy3dgen` source and model weights **auto-download at runtime**;+- it has no `diso` dependency.++---++## 4. Build the extension venv (with the Jetson fixes)++Create the venv:++```bash+EXT="$EXTENSIONS_DIR/hunyuan3d-mini"+python3 -m venv "$EXT/venv"+"$EXT/venv/bin/pip" install -U pip+```++### 4a. Install Jetson-native PyTorch (not the cu124 SBSA wheels)++> Do **not** run the extension's stock `setup.py` on Jetson; its ARM64 branch installs+> generic server-ARM (SBSA) `torch 2.5.1+cu124` wheels that **do not contain `sm_87`+> kernels**. They import fine and report `cuda available: True`, but the first real+> kernel throws `RuntimeError: CUDA error: no kernel image is available for execution on the device`.++Install from the jetson-ai-lab index instead (pick the channel matching your JetPack:+`jp6/cu126` for JetPack 6.2):++```bash+"$EXT/venv/bin/pip" install --no-deps \+ --index-url https://pypi.jetson-ai-lab.io/jp6/cu126 \+ torch==2.8.0 torchvision==0.23.0+```++> **Do not add `--extra-index-url https://pypi.org/simple` here.** pip will prefer the+> newer PyPI `torch` (e.g. 2.12 with a CUDA-13 dependency stack) which needs a CUDA-13+> driver JetPack 6.2 doesn't have. Keep it to the jetson-ai-lab index only.+> Other available pairings on that index: torch `2.9.1`/`2.10.0`/`2.11.0` ↔+> torchvision `0.24.1`/`0.25.0`/`0.26.0`.++### 4b. Install the rest of the dependencies, pinned for NumPy 1.x++The Jetson torch wheel is built against NumPy 1.x. Under NumPy 2 you get+`RuntimeError: Numpy is not available` from `torch.from_numpy` (the diffusion scheduler+uses it during model load). Pin NumPy `<2` and an OpenCV build that allows it:++```bash+"$EXT/venv/bin/pip" install \+ Pillow "numpy==1.26.4" trimesh pymeshlab "opencv-python-headless==4.10.0.84" \+ huggingface_hub "diffusers>=0.31.0" "transformers>=4.46.0" accelerate \+ einops scipy scikit-image+```++> `rembg` / `onnxruntime` are intentionally **omitted**; see §4c.++### 4c. Bypass `rembg` / ONNX Runtime (background removal)++ONNX Runtime is unusable on this Tegra CPU. The generic PyPI `aarch64` wheel aborts on+import/inference with:++```+onnxruntime cpuid_info warning: Unknown CPU vendor. cpuinfo_vendor value: 0+Assertion '__n < this->size()' failed.+```++and the jetson-ai-lab `onnxruntime-gpu` build segfaults during inference. Because these+are native C++ aborts (not Python exceptions), the extension's `try/except` fallback+can't catch them, so the whole subprocess dies (*"Subprocess died during generation"*).++`rembg` is only used for background removal in `_preprocess`. Replace it with a+dependency-free NumPy/SciPy remover. Save this as `patch_preprocess.py`:++```python+import re, sys+GEN = sys.argv[1]+src = open(GEN, encoding="utf-8").read()+NEW = ''' def _preprocess(self, image_bytes: bytes) -> Image.Image:+ # rembg/onnxruntime is unusable on Jetson's Tegra CPU; use a+ # dependency-free background remover (numpy + scipy, no onnxruntime).+ import numpy as np+ img = Image.open(io.BytesIO(image_bytes)).convert("RGBA")+ arr = np.array(img)+ if arr.shape[2] == 4 and int(arr[..., 3].min()) < 250:+ return img # already has an alpha cutout+ rgb = arr[..., :3].astype(np.float32)+ h, w = rgb.shape[:2]+ b = max(2, min(h, w) // 50)+ border = np.concatenate([+ rgb[:b, :, :].reshape(-1, 3), rgb[-b:, :, :].reshape(-1, 3),+ rgb[:, :b, :].reshape(-1, 3), rgb[:, -b:, :].reshape(-1, 3),+ ], axis=0)+ bg = np.median(border, axis=0)+ dist = np.sqrt(((rgb - bg) ** 2).sum(axis=2))+ thr = max(25.0, float(np.percentile(dist, 35)))+ alpha = (dist > thr).astype(np.uint8) * 255+ try:+ from scipy import ndimage+ lbl, n = ndimage.label(alpha > 0)+ if n > 1:+ sizes = ndimage.sum(np.ones_like(lbl), lbl, range(1, n + 1))+ keep = int(np.argmax(sizes)) + 1+ alpha = np.where(lbl == keep, 255, 0).astype(np.uint8)+ alpha = ndimage.binary_fill_holes(alpha > 0).astype(np.uint8) * 255+ except Exception:+ pass+ out = arr.copy()+ out[..., 3] = alpha+ return Image.fromarray(out, "RGBA")++'''+pat = re.compile(r" def _preprocess\(self, image_bytes: bytes\) -> Image\.Image:.*?(?=\n def )", re.DOTALL)+assert pat.search(src), "_preprocess block not found"+open(GEN, "w", encoding="utf-8").write(pat.sub(NEW.rstrip("\n") + "\n", src, count=1))+print("patched")+```++Apply it (a backup is kept):++```bash+cp -n "$EXT/generator.py" "$EXT/generator.py.orig"+python3 patch_preprocess.py "$EXT/generator.py"+"$EXT/venv/bin/python" -c "import ast; ast.parse(open('$EXT/generator.py').read()); print('parses OK')"+```++> **Caveat:** this remover is a simple border-colour key + largest-blob + hole-fill. It+> works well on clean/plain backgrounds (product shots, objects on a wall/floor) but+> poorly on busy scenes. A proper fix would be a working Jetson ONNX Runtime, or making+> background removal optional in the extension.++### 4d. Verify the GPU actually runs a kernel++```bash+"$EXT/venv/bin/python" - <<'PY'+import numpy as np, torch+print("torch", torch.__version__, "| cuda", torch.cuda.is_available(),+ "| dev", torch.cuda.get_device_name(0), "| cap", torch.cuda.get_device_capability(0))+a = torch.randn(512, 512, device="cuda", dtype=torch.float16)+print("matmul OK:", float((a @ a).float().sum()))+print("from_numpy OK:", torch.from_numpy(np.arange(3, dtype="float32")).cuda().sum().item())+PY+```++Expect `cap (8, 7)`, a finite `matmul OK`, and `from_numpy OK: 3.0`. If `matmul`+fails with *"no kernel image"*, your torch wheel is wrong (see 4a). If `from_numpy`+fails, NumPy is ≥2 (see 4b).++---++## 5. Run the backend (headless)++```bash+cd ~/modly/api+EXTENSIONS_DIR=$HOME/.modly/extensions \+MODELS_DIR=$HOME/.modly/models \+WORKSPACE_DIR=$HOME/.modly/workspace \+./.venv/bin/uvicorn main:app --host 0.0.0.0 --port 8000+```++> Optional: `export HF_TOKEN=hf_...` before launching to avoid HuggingFace rate-limits+> on the one-time ~4 GB weight download.++Check it (from the Jetson, or from another machine using the Jetson's IP):++```bash+curl http://127.0.0.1:8000/health # {"status":"ok"}+curl http://127.0.0.1:8000/model/all # lists hunyuan3d-mini/generate+curl http://127.0.0.1:8000/extensions/errors # {} == no load errors+```++---++## 6. Generate a mesh++```bash+# Submit (first run downloads weights + hy3dgen, then loads on CUDA)+curl -s -X POST http://127.0.0.1:8000/generate/from-image \+ -F image=@your_object.png \+ -F model_id=hunyuan3d-mini/generate \+ -F remesh=none -F enable_texture=false \+ -F 'params={"num_inference_steps":50,"octree_resolution":512,"guidance_scale":5.5,"seed":42}'+# -> {"job_id":"..."}++# Poll until "done"+curl http://127.0.0.1:8000/generate/status/<job_id>++# The result is served from the workspace; download it+curl -O http://127.0.0.1:8000/workspace/Default/<file>.glb+```++`params` options for this model: `num_inference_steps` (10/30/50),+`octree_resolution` (256/380/512; higher = more detail + VRAM), `guidance_scale`,+`seed`. A 64 GB Orin handles `50 / 512` comfortably.++---++## 7. Performance: max out the Orin++A fresh Jetson is often in a power-limited `nvpmodel` (fewer CPU cores, lower clocks),+which slows the CPU-bound model-load and pre/post-processing. For full speed:++```bash+sudo nvpmodel -m 0 # MAXN (all cores)+sudo jetson_clocks # lock max clocks+```++Watch utilisation during a run with `tegrastats` (expect `GR3D_FREQ` near 100% during+diffusion).++---++## Troubleshooting++| Symptom | Cause | Fix |+|---|---|---|+| `CUDA error: no kernel image is available for execution on the device` | torch wheel has no `sm_87` kernels (generic SBSA build) | Install Jetson torch from jetson-ai-lab (§4a) |+| `RuntimeError: Numpy is not available` (in `from_numpy`) | torch built against NumPy 1.x, but NumPy ≥2 installed | `pip install "numpy==1.26.4"` + OpenCV `4.10.0.84` (§4b) |+| `Subprocess died during generation` at *"Removing background"*; log shows `Unknown CPU vendor` / `Assertion '__n < this->size()'` / segfault | ONNX Runtime broken on Tegra CPU | Patch `_preprocess` to drop `rembg` (§4c) |+| `opencv-python-headless ... requires numpy>=2` | newer OpenCV forces NumPy 2 | pin `opencv-python-headless==4.10.0.84` |+| Edits to the extension venv don't take effect | the backend keeps a long-lived extension subprocess that survives errors | restart the backend so it respawns the subprocess |++---++## Known limitations++- **No textures.** This guide covers mesh-only generation. `enable_texture=true`+ requires building `custom_rasterizer` and `differentiable_renderer` (CUDA C+++ extensions) from source for `aarch64`, not covered here.+- **Background removal is approximate** (see §4c caveat).+- Single-image 3D infers unseen sides; the back/underside are model guesses. Output+ meshes are typically not watertight.++---++## Notes for a proper upstream fix++If Modly wants first-class Jetson support, the cleanest changes would be:++1. In the extension `setup.py`, detect Tegra (`/etc/nv_tegra_release`) and install torch+ from the jetson-ai-lab index for the detected JetPack/CUDA, pinning `numpy<2`.+2. Make background removal pluggable / optional, or ship a non-ONNX fallback, so a broken+ ONNX Runtime can't hard-crash generation.+3. Document the headless backend (`uvicorn main:app` + the three env vars) as a supported+ way to run generation without Electron.diff --git a/apps/forge-desktop/electron.vite.config.ts b/apps/forge-desktop/electron.vite.config.tsnew file mode 100644index 000000000..69a998da7--- /dev/null+++ b/apps/forge-desktop/electron.vite.config.ts@@ -0,0 +1,39 @@+import { defineConfig, externalizeDepsPlugin } from 'electron-vite'+import react from '@vitejs/plugin-react'+import { resolve } from 'path'++export default defineConfig({+ main: {+ plugins: [externalizeDepsPlugin()],+ build: {+ lib: {+ entry: resolve('electron/main/index.ts')+ }+ }+ },+ preload: {+ plugins: [externalizeDepsPlugin()],+ build: {+ lib: {+ entry: resolve('electron/preload/index.ts')+ }+ }+ },+ renderer: {+ root: 'src',+ build: {+ rollupOptions: {+ input: resolve('src/index.html')+ }+ },+ resolve: {+ alias: {+ '@': resolve('src'),+ '@areas': resolve('src/areas'),+ '@shared': resolve('src/shared'),+ '@styles': resolve('src/styles')+ }+ },+ plugins: [react()]+ }+})diff --git a/apps/forge-desktop/electron/main/artifact-registry-service.test.ts b/apps/forge-desktop/electron/main/artifact-registry-service.test.tsnew file mode 100644index 000000000..276e90a1d--- /dev/null+++ b/apps/forge-desktop/electron/main/artifact-registry-service.test.ts@@ -0,0 +1,242 @@+import assert from 'node:assert/strict'+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import test from 'node:test'++import {+ classifyAssetLibraryCandidate,+ listWorkspaceAssetLibrary,+ normalizeWorkspaceAssetPath,+ openWorkspaceAssetLibraryEntry,+ readWorkspaceAssetLibraryEntry,+ registerWorkspaceAssetLibraryIpcHandlers,+} from './artifact-registry-service.ts'++async function withWorkspace(run: (workspaceDir: string) => Promise<void>) {+ const workspaceDir = await mkdtemp(path.join(tmpdir(), 'modly-library-'))+ try {+ await run(workspaceDir)+ } finally {+ await rm(workspaceDir, { recursive: true, force: true })+ }+}++test('normalizes only workspace-relative paths under allowed Workflows and Exports roots', () => withWorkspace(async (workspaceDir) => {+ assert.equal(normalizeWorkspaceAssetPath(workspaceDir, 'Workflows/checkpoints/hero.glb').workspacePath, 'Workflows/checkpoints/hero.glb')+ assert.equal(normalizeWorkspaceAssetPath(workspaceDir, 'Exports/hero.glb').workspacePath, 'Exports/hero.glb')+ assert.throws(() => normalizeWorkspaceAssetPath(workspaceDir, '../secret.glb'), /traversal|escape|relative/i)+ assert.throws(() => normalizeWorkspaceAssetPath(workspaceDir, '/tmp/secret.glb'), /absolute/i)+ assert.throws(() => normalizeWorkspaceAssetPath(workspaceDir, 'Workflows/%2e%2e/secret.glb'), /encoded/i)+ assert.throws(() => normalizeWorkspaceAssetPath(workspaceDir, 'Collections/hero.glb'), /allowed workspace library roots/i)+}))++test('classifies supported assets by capability instead of extension category', () => {+ assert.deepEqual(classifyAssetLibraryCandidate({ workspacePath: 'Workflows/a.glb' }), {+ capability: 'mesh', state: 'ready', previewKind: '3d-model', openable: true,+ })+ assert.deepEqual(classifyAssetLibraryCandidate({ workspacePath: 'Workflows/rigged.gltf', hasRigMetadata: true }), {+ capability: 'rigged-mesh', state: 'ready', previewKind: '3d-model', openable: true,+ })+ assert.equal(classifyAssetLibraryCandidate({ workspacePath: 'Workflows/motion.bvh' }).capability, 'animation-motion')+ assert.equal(classifyAssetLibraryCandidate({ workspacePath: 'Workflows/scan.splat' }).openable, false)+ assert.equal(classifyAssetLibraryCandidate({ workspacePath: 'Workflows/notes.txt' }).state, 'unsupported')+})++test('lists Workflows and Exports assets while skipping hidden, cache, and internal files', () => withWorkspace(async (workspaceDir) => {+ await mkdir(path.join(workspaceDir, 'Workflows/checkpoints'), { recursive: true })+ await mkdir(path.join(workspaceDir, 'Workflows/.hidden'), { recursive: true })+ await mkdir(path.join(workspaceDir, 'Workflows/cache'), { recursive: true })+ await mkdir(path.join(workspaceDir, 'Exports'), { recursive: true })+ await writeFile(path.join(workspaceDir, 'Workflows/checkpoints/hero.glb'), 'glb')+ await writeFile(path.join(workspaceDir, 'Workflows/checkpoints/hero.rigmeta.json'), '{}')+ await writeFile(path.join(workspaceDir, 'Workflows/.hidden/private.glb'), 'glb')+ await writeFile(path.join(workspaceDir, 'Workflows/cache/temp.glb'), 'glb')+ await writeFile(path.join(workspaceDir, 'Exports/exported.ply'), 'ply')++ const result = await listWorkspaceAssetLibrary({ workspaceDir })+ assert.equal(result.success, true)+ assert.deepEqual(result.success && result.entries.map((entry) => entry.workspacePath), [+ 'Exports/exported.ply',+ 'Workflows/checkpoints/hero.glb',+ ])+ assert.equal(result.success && result.entries.find((entry) => entry.workspacePath.endsWith('hero.glb'))?.capability, 'rigged-mesh')+ assert.equal(result.success && result.entries.find((entry) => entry.workspacePath.endsWith('exported.ply'))?.openable, false)+}))++test('registers a generated scene directory through its canonical manifest artifact', () => withWorkspace(async (workspaceDir) => {+ await mkdir(path.join(workspaceDir, 'Workflows/world'), { recursive: true })+ await writeFile(path.join(workspaceDir, 'Workflows/world/scene-manifest.json'), JSON.stringify({+ schema: 'modly.scene-manifest.v1', sceneRoot: '.', assets: [],+ }))+ const result = await listWorkspaceAssetLibrary({ workspaceDir })+ assert.equal(result.success, true)+ const scene = result.success && result.entries.find((entry) => entry.workspacePath === 'Workflows/world/scene-manifest.json')+ assert.equal(scene && scene.capability, 'scene-manifest')+ assert.equal(scene && scene.state, 'ready')+}))++test('reads and opens only safe GLB/GLTF workspace assets', () => withWorkspace(async (workspaceDir) => {+ await mkdir(path.join(workspaceDir, 'Workflows/checkpoints'), { recursive: true })+ await mkdir(path.join(workspaceDir, 'Exports'), { recursive: true })+ await writeFile(path.join(workspaceDir, 'Workflows/checkpoints/hero.glb'), 'glb')+ await writeFile(path.join(workspaceDir, 'Exports/static.ply'), 'ply')++ const read = await readWorkspaceAssetLibraryEntry({ workspaceDir, workspacePath: 'Workflows/checkpoints/hero.glb' })+ assert.equal(read.success, true)+ assert.equal(read.success && read.preview.kind, '3d-model')+ const opened = await openWorkspaceAssetLibraryEntry({ workspaceDir, workspacePath: 'Workflows/checkpoints/hero.glb' })+ assert.equal(opened.success, true)+ assert.equal(opened.success && opened.entry.openable, true)+ const blocked = await openWorkspaceAssetLibraryEntry({ workspaceDir, workspacePath: 'Exports/static.ply' })+ assert.equal(blocked.success, false)+ assert.equal(!blocked.success && blocked.error.code, 'not-openable')+ const unsafe = await readWorkspaceAssetLibraryEntry({ workspaceDir, workspacePath: '../secret.glb' })+ assert.equal(unsafe.success, false)+ assert.equal(!unsafe.success && unsafe.error.code, 'unsafe-path')+}))++test('Electron read/open boundary rejects Windows absolute and UNC workspace paths', () => withWorkspace(async (workspaceDir) => {+ await mkdir(path.join(workspaceDir, 'Workflows/checkpoints'), { recursive: true })+ await writeFile(path.join(workspaceDir, 'Workflows/checkpoints/hero.glb'), 'glb')++ const unsafeWorkspacePaths = [+ 'C:\\Users\\x\\asset.glb',+ 'C:/Users/x/asset.glb',+ '\\\\server\\share\\asset.glb',+ ]++ for (const workspacePath of unsafeWorkspacePaths) {+ const read = await readWorkspaceAssetLibraryEntry({ workspaceDir, workspacePath })+ const opened = await openWorkspaceAssetLibraryEntry({ workspaceDir, workspacePath })++ assert.equal(read.success, false, `${workspacePath} should be rejected for read`)+ assert.equal(!read.success && read.error.code, 'unsafe-path')+ assert.equal(opened.success, false, `${workspacePath} should be rejected for open`)+ assert.equal(!opened.success && opened.error.code, 'unsafe-path')+ }+}))++test('Electron read/open boundary rejects Windows absolute and UNC sourceWorkspacePath values', () => withWorkspace(async (workspaceDir) => {+ await mkdir(path.join(workspaceDir, 'Workflows/checkpoints'), { recursive: true })+ await writeFile(path.join(workspaceDir, 'Workflows/checkpoints/hero.glb'), 'glb')+ await writeFile(path.join(workspaceDir, 'Workflows/checkpoints/hero.landmarks.v1.json'), JSON.stringify({+ sourceWorkspacePath: 'Workflows/checkpoints/hero.glb',+ }))++ const unsafeSourcePaths = [+ 'C:\\Users\\x\\asset.glb',+ 'C:/Users/x/asset.glb',+ '\\\\server\\share\\asset.glb',+ ]++ for (const sourceWorkspacePath of unsafeSourcePaths) {+ const read = await readWorkspaceAssetLibraryEntry({+ workspaceDir,+ workspacePath: 'Workflows/checkpoints/hero.landmarks.v1.json',+ sourceWorkspacePath,+ })+ const opened = await openWorkspaceAssetLibraryEntry({+ workspaceDir,+ workspacePath: 'Workflows/checkpoints/hero.landmarks.v1.json',+ sourceWorkspacePath,+ })++ assert.equal(read.success, false, `${sourceWorkspacePath} should be rejected as read source`)+ assert.equal(!read.success && read.error.code, 'unsafe-path')+ assert.equal(opened.success, false, `${sourceWorkspacePath} should be rejected as open source`)+ assert.equal(!opened.success && opened.error.code, 'unsafe-path')+ }+}))++test('enriches sidecars with safe source, manifest, artifact, version, and provenance metadata', () => withWorkspace(async (workspaceDir) => {+ await mkdir(path.join(workspaceDir, 'Workflows/checkpoints'), { recursive: true })+ await writeFile(path.join(workspaceDir, 'Workflows/checkpoints/hero.glb'), 'glb')+ await writeFile(path.join(workspaceDir, 'Workflows/checkpoints/hero.scene.json'), JSON.stringify({ schema: 'scene-manifest' }))+ await writeFile(path.join(workspaceDir, 'Workflows/checkpoints/hero.landmarks.v1.json'), JSON.stringify({+ sourceWorkspacePath: 'Workflows/checkpoints/hero.glb',+ manifestWorkspacePath: 'Workflows/checkpoints/hero.scene.json',+ artifactId: 'artifact-hero',+ versionId: 'version-1',+ provenance: { workflowId: 'wf-1', workflowNodeId: 'node-1' },+ }))++ const read = await readWorkspaceAssetLibraryEntry({ workspaceDir, workspacePath: 'Workflows/checkpoints/hero.landmarks.v1.json' })++ assert.equal(read.success, true)+ if (!read.success) return+ assert.equal(read.entry.source?.workspacePath, 'Workflows/checkpoints/hero.glb')+ assert.equal(read.entry.manifest?.workspacePath, 'Workflows/checkpoints/hero.scene.json')+ assert.equal(read.entry.manifest?.capability, 'scene-manifest')+ assert.equal(read.entry.artifactId, 'artifact-hero')+ assert.equal(read.entry.versionId, 'version-1')+ assert.equal(read.entry.provenance?.workflowId, 'wf-1')+}))++test('fails closed for unsafe, self, missing, and mismatched sourceWorkspacePath opens', () => withWorkspace(async (workspaceDir) => {+ await mkdir(path.join(workspaceDir, 'Workflows/checkpoints'), { recursive: true })+ await writeFile(path.join(workspaceDir, 'Workflows/checkpoints/hero.glb'), 'glb')+ await writeFile(path.join(workspaceDir, 'Workflows/checkpoints/other.glb'), 'glb')+ await writeFile(path.join(workspaceDir, 'Workflows/checkpoints/hero.landmarks.v1.json'), JSON.stringify({+ sourceWorkspacePath: 'Workflows/checkpoints/hero.glb',+ }))+ await writeFile(path.join(workspaceDir, 'Workflows/checkpoints/self.landmarks.v1.json'), JSON.stringify({+ sourceWorkspacePath: 'Workflows/checkpoints/self.landmarks.v1.json',+ }))+ await writeFile(path.join(workspaceDir, 'Workflows/checkpoints/missing.landmarks.v1.json'), JSON.stringify({+ sourceWorkspacePath: 'Workflows/checkpoints/missing.glb',+ }))++ const opened = await openWorkspaceAssetLibraryEntry({+ workspaceDir,+ workspacePath: 'Workflows/checkpoints/hero.landmarks.v1.json',+ sourceWorkspacePath: 'Workflows/checkpoints/hero.glb',+ })+ assert.equal(opened.success, true)+ assert.equal(opened.success && opened.entry.source?.workspacePath, 'Workflows/checkpoints/hero.glb')++ const unsafe = await openWorkspaceAssetLibraryEntry({ workspaceDir, workspacePath: 'Workflows/checkpoints/hero.landmarks.v1.json', sourceWorkspacePath: '../secret.glb' })+ const self = await openWorkspaceAssetLibraryEntry({ workspaceDir, workspacePath: 'Workflows/checkpoints/self.landmarks.v1.json', sourceWorkspacePath: 'Workflows/checkpoints/self.landmarks.v1.json' })+ const missing = await openWorkspaceAssetLibraryEntry({ workspaceDir, workspacePath: 'Workflows/checkpoints/missing.landmarks.v1.json', sourceWorkspacePath: 'Workflows/checkpoints/missing.glb' })+ const mismatched = await openWorkspaceAssetLibraryEntry({ workspaceDir, workspacePath: 'Workflows/checkpoints/hero.landmarks.v1.json', sourceWorkspacePath: 'Workflows/checkpoints/other.glb' })++ assert.equal(unsafe.success, false)+ assert.equal(!unsafe.success && unsafe.error.code, 'unsafe-path')+ assert.equal(self.success, false)+ assert.equal(!self.success && self.error.code, 'not-openable')+ assert.equal(missing.success, false)+ assert.equal(!missing.success && missing.error.code, 'not-openable')+ assert.equal(mismatched.success, false)+ assert.equal(!mismatched.success && mismatched.error.code, 'not-openable')+}))++test('IPC read and open handlers forward sourceWorkspacePath without trusting malformed payloads', async () => {+ const handlers = new Map<string, (event: unknown, payload: unknown) => Promise<unknown>>()+ registerWorkspaceAssetLibraryIpcHandlers({+ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) },+ getWorkspaceDir: () => '/tmp/modly-workspace',+ })++ const result = await handlers.get('workspace:library:open')?.({}, {+ workspacePath: 'Workflows/hero.landmarks.v1.json',+ sourceWorkspacePath: '../secret.glb',+ })++ assert.equal(typeof (result as { success?: unknown }).success, 'boolean')+ assert.equal((result as { success: boolean, error?: { code: string } }).error?.code, 'unsafe-path')+})++test('registers workspace library IPC handlers with structured results', async () => {+ const handlers = new Map<string, (event: unknown, payload: unknown) => Promise<unknown>>()+ registerWorkspaceAssetLibraryIpcHandlers({+ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) },+ getWorkspaceDir: () => '/tmp/modly-workspace',+ })++ assert.equal(typeof handlers.get('workspace:library:list'), 'function')+ assert.equal(typeof handlers.get('workspace:library:read'), 'function')+ assert.equal(typeof handlers.get('workspace:library:open'), 'function')+ const result = await handlers.get('workspace:library:read')?.({}, { workspacePath: '../escape.glb' })+ assert.equal(typeof (result as { success?: unknown }).success, 'boolean')+ assert.equal((result as { success: boolean, error?: { code: string } }).error?.code, 'unsafe-path')+})diff --git a/apps/forge-desktop/electron/main/artifact-registry-service.ts b/apps/forge-desktop/electron/main/artifact-registry-service.tsnew file mode 100644index 000000000..2acb657fb--- /dev/null+++ b/apps/forge-desktop/electron/main/artifact-registry-service.ts@@ -0,0 +1,367 @@+import { readdir, readFile, stat } from 'node:fs/promises'+import { basename, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'++import type {+ AssetCapability,+ AssetEntryState,+ AssetLibraryEntry,+ AssetLibraryError,+ AssetLibraryListResult,+ AssetLibraryOpenResult,+ AssetLibraryPreviewKind,+ AssetLibraryPreviewPayload,+ AssetLibraryReadResult,+ AssetLibrarySourceScope,+} from '../../src/shared/types/assetLibrary'+import type { ArtifactProvenance } from '../../src/shared/types/artifacts'++const WINDOWS_ABSOLUTE_PATH = /^[a-zA-Z]:[\\/]/+const ENCODED_ESCAPE_PATTERN = /%2e|%2f|%5c/i+const ALLOWED_ROOTS = ['Workflows', 'Exports'] as const+const SKIPPED_DIRS = new Set(['tmp', 'temp', 'cache'])+const INTERNAL_SUFFIXES = ['.artifact.json', '.rigmeta.json'] as const+const TEXT_EXTENSIONS = new Set(['json', 'txt', 'md'])+const INTRINSIC_MOTION_EXTENSIONS = new Set(['bvh', 'npz'])+const MESH_EXTENSIONS = new Set(['glb', 'gltf', 'obj', 'stl', 'ply', 'splat'])++export interface AssetLibraryClassificationCandidate {+ workspacePath: string+ hasRigMetadata?: boolean+}++export interface AssetLibraryClassification {+ capability?: AssetCapability+ state: AssetEntryState+ previewKind: AssetLibraryPreviewKind+ openable: boolean+ nonOpenableReason?: string+}++export interface NormalizedWorkspaceAssetPath {+ workspacePath: string+ absolutePath: string+}++export interface WorkspaceAssetLibraryRequest {+ workspaceDir: string+}++export interface WorkspaceAssetLibraryReadRequest extends WorkspaceAssetLibraryRequest {+ workspacePath: string+ sourceWorkspacePath?: string+}++interface AssetLibraryMetadata {+ sourceWorkspacePath?: string+ manifestWorkspacePath?: string+ artifactId?: string+ versionId?: string+ provenance?: ArtifactProvenance+ warnings: string[]+}++export interface IpcMainLike {+ handle(channel: string, handler: (event: unknown, payload?: unknown) => Promise<unknown>): void+}++export interface WorkspaceAssetLibraryIpcDeps {+ ipcMain: IpcMainLike+ getWorkspaceDir: () => string+}++function libraryError(code: AssetLibraryError['code'], message: string): AssetLibraryError {+ return { code, message }+}++function normalizeSeparators(input: string): string {+ return input.replace(/\\/g, '/')+}++function isWindowsAbsolutePath(input: string): boolean {+ return WINDOWS_ABSOLUTE_PATH.test(input) || input.startsWith('\\\\')+}++function assertSafeWorkspaceRelativePath(workspacePath: string): string {+ const normalized = normalizeSeparators(workspacePath.trim())+ if (!normalized || normalized === '.') throw new Error('Workspace library path must be workspace-relative and non-empty')+ if (ENCODED_ESCAPE_PATTERN.test(normalized)) throw new Error('Workspace library path must not contain encoded path escapes')+ if (isAbsolute(normalized) || isWindowsAbsolutePath(workspacePath)) throw new Error('Workspace library path must not be absolute')+ const segments = normalized.split('/').filter((segment) => segment && segment !== '.')+ if (segments.some((segment) => segment === '..')) throw new Error('Workspace library path must not contain traversal segments')+ if (!ALLOWED_ROOTS.includes(segments[0] as typeof ALLOWED_ROOTS[number])) {+ throw new Error('Workspace library path must stay under allowed workspace library roots')+ }+ return segments.join('/')+}++export function normalizeWorkspaceAssetPath(workspaceDir: string, workspacePath: string): NormalizedWorkspaceAssetPath {+ const safePath = assertSafeWorkspaceRelativePath(workspacePath)+ const root = resolve(workspaceDir)+ const absolutePath = resolve(root, ...safePath.split('/'))+ const back = relative(root, absolutePath)+ if (!back || back.startsWith('..') || isAbsolute(back)) throw new Error('Workspace library path escapes the workspace root')+ return { workspacePath: safePath, absolutePath }+}++function extensionOf(workspacePath: string): string {+ return extname(workspacePath).slice(1).toLowerCase()+}++function isGlbOrGltf(workspacePath: string): boolean {+ return /\.(glb|gltf)$/i.test(workspacePath)+}++function sourceScopeFor(workspacePath: string): AssetLibrarySourceScope {+ return workspacePath.startsWith('Exports/') ? 'exports' : 'workflows'+}++export function classifyAssetLibraryCandidate(candidate: AssetLibraryClassificationCandidate): AssetLibraryClassification {+ const extension = extensionOf(candidate.workspacePath)++ if (candidate.workspacePath.endsWith('.landmarks.v1.json')) {+ return { capability: 'landmarks-sidecar', state: 'ready', previewKind: 'text', openable: false, nonOpenableReason: 'Landmark sidecars require opening their source mesh.' }+ }+ if (candidate.workspacePath.endsWith('.world.json')) {+ return { capability: 'generated-world', state: 'ready', previewKind: 'text', openable: false, nonOpenableReason: 'Generated worlds are list-only in this release.' }+ }+ if (candidate.workspacePath.endsWith('.scene.json') || candidate.workspacePath.endsWith('/scene-manifest.json')) {+ return { capability: 'scene-manifest', state: 'ready', previewKind: 'text', openable: false, nonOpenableReason: 'Scene manifests are list-only in this release.' }+ }+ if (INTRINSIC_MOTION_EXTENSIONS.has(extension)) {+ return { capability: 'animation-motion', state: 'ready', previewKind: 'binary', openable: false, nonOpenableReason: 'Motion files are list-only in this release.' }+ }+ if (extension === 'glb' || extension === 'gltf') {+ return { capability: candidate.hasRigMetadata ? 'rigged-mesh' : 'mesh', state: 'ready', previewKind: '3d-model', openable: true }+ }+ if (MESH_EXTENSIONS.has(extension)) {+ return { capability: 'mesh', state: 'ready', previewKind: 'binary', openable: false, nonOpenableReason: `.${extension} workspace assets are list-only in this release.` }+ }+ if (TEXT_EXTENSIONS.has(extension)) {+ return { state: 'unsupported', previewKind: 'text', openable: false, nonOpenableReason: 'Unsupported workspace asset.' }+ }+ return { state: 'unsupported', previewKind: 'binary', openable: false, nonOpenableReason: 'Unsupported workspace asset.' }+}++function stringField(value: unknown): string | undefined {+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined+}++function objectField(value: unknown): Record<string, unknown> | undefined {+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : undefined+}++function manifestCapabilityFor(workspacePath: string): 'generated-world' | 'scene-manifest' | undefined {+ if (workspacePath.endsWith('.world.json')) return 'generated-world'+ if (workspacePath.endsWith('.scene.json')) return 'scene-manifest'+ if (workspacePath.endsWith('/scene-manifest.json')) return 'scene-manifest'+ return undefined+}++async function safeLinkedWorkspacePath(workspaceDir: string, ownerWorkspacePath: string, candidate: unknown, expected?: { mustBeMesh?: boolean, mustBeManifest?: boolean }): Promise<{ workspacePath?: string, warning?: string }> {+ const raw = stringField(candidate)+ if (!raw) return {}+ let normalized: NormalizedWorkspaceAssetPath+ try {+ normalized = normalizeWorkspaceAssetPath(workspaceDir, raw)+ } catch {+ return { warning: 'Ignored unsafe linked workspace path.' }+ }+ if (normalized.workspacePath === ownerWorkspacePath) return { warning: 'Ignored self-linked workspace path.' }+ if (expected?.mustBeMesh && !isGlbOrGltf(normalized.workspacePath)) return { warning: 'Ignored non-GLB/GLTF source workspace path.' }+ if (expected?.mustBeManifest && !manifestCapabilityFor(normalized.workspacePath)) return { warning: 'Ignored non-manifest workspace path.' }+ try {+ await stat(normalized.absolutePath)+ } catch {+ return { warning: 'Ignored missing linked workspace path.' }+ }+ return { workspacePath: normalized.workspacePath }+}++async function readMetadata(workspaceDir: string, workspacePath: string, absolutePath: string): Promise<AssetLibraryMetadata> {+ const metadata: AssetLibraryMetadata = { warnings: [] }+ if (extensionOf(workspacePath) !== 'json') return metadata++ let parsed: Record<string, unknown>+ try {+ parsed = JSON.parse(await readFile(absolutePath, 'utf8')) as Record<string, unknown>+ } catch {+ return metadata+ }++ const sourceRaw = parsed.sourceWorkspacePath ?? parsed.source_workspace_path ?? parsed.sourcePath ?? objectField(parsed.source)?.workspacePath+ const source = await safeLinkedWorkspacePath(workspaceDir, workspacePath, sourceRaw, { mustBeMesh: true })+ if (source.workspacePath) metadata.sourceWorkspacePath = source.workspacePath+ if (source.warning) metadata.warnings.push(source.warning)++ const manifestRaw = parsed.manifestWorkspacePath ?? parsed.manifest_workspace_path ?? objectField(parsed.manifest)?.workspacePath+ const manifest = await safeLinkedWorkspacePath(workspaceDir, workspacePath, manifestRaw, { mustBeManifest: true })+ if (manifest.workspacePath) metadata.manifestWorkspacePath = manifest.workspacePath+ if (manifest.warning) metadata.warnings.push(manifest.warning)++ metadata.artifactId = stringField(parsed.artifactId ?? parsed.artifact_id)+ metadata.versionId = stringField(parsed.versionId ?? parsed.version_id)+ metadata.provenance = objectField(parsed.provenance) as ArtifactProvenance | undefined+ return metadata+}++function shouldSkipDirectory(name: string): boolean {+ return name.startsWith('.') || SKIPPED_DIRS.has(name.toLowerCase())+}++function shouldSkipFile(name: string): boolean {+ return name.startsWith('.') || INTERNAL_SUFFIXES.some((suffix) => name.endsWith(suffix))+}++async function hasRigMetadata(absolutePath: string): Promise<boolean> {+ if (!/\.(glb|gltf)$/i.test(absolutePath)) return false+ const stem = absolutePath.replace(/\.(glb|gltf)$/i, '')+ try {+ await stat(`${stem}.rigmeta.json`)+ return true+ } catch {+ return false+ }+}++async function buildEntry(workspaceDir: string, workspacePath: string): Promise<AssetLibraryEntry> {+ const { absolutePath } = normalizeWorkspaceAssetPath(workspaceDir, workspacePath)+ const stats = await stat(absolutePath)+ const classification = classifyAssetLibraryCandidate({ workspacePath, hasRigMetadata: await hasRigMetadata(absolutePath) })+ const metadata = await readMetadata(workspaceDir, workspacePath, absolutePath)+ const manifestCapability = metadata.manifestWorkspacePath ? manifestCapabilityFor(metadata.manifestWorkspacePath) : undefined+ return {+ id: `library:${workspacePath}`,+ workspacePath,+ displayName: basename(workspacePath),+ sourceScope: sourceScopeFor(workspacePath),+ capability: classification.capability,+ state: classification.state,+ previewKind: classification.previewKind,+ source: metadata.sourceWorkspacePath ? { workspacePath: metadata.sourceWorkspacePath, displayName: basename(metadata.sourceWorkspacePath), role: 'source-mesh' } : undefined,+ manifest: metadata.manifestWorkspacePath && manifestCapability ? { workspacePath: metadata.manifestWorkspacePath, capability: manifestCapability } : undefined,+ artifactId: metadata.artifactId,+ versionId: metadata.versionId,+ provenance: metadata.provenance,+ warnings: metadata.warnings,+ openable: classification.openable,+ nonOpenableReason: classification.nonOpenableReason,+ createdAt: (stats.birthtime.getTime() > 0 ? stats.birthtime : stats.mtime).toISOString(),+ updatedAt: stats.mtime.toISOString(),+ }+}++async function collectFiles(workspaceDir: string, rootName: typeof ALLOWED_ROOTS[number]): Promise<string[]> {+ const root = join(workspaceDir, rootName)+ const files: string[] = []++ async function walk(dir: string): Promise<void> {+ let entries: Awaited<ReturnType<typeof readdir>>+ try {+ entries = await readdir(dir, { withFileTypes: true })+ } catch {+ return+ }+ for (const entry of entries) {+ if (entry.isDirectory()) {+ if (!shouldSkipDirectory(entry.name)) await walk(join(dir, entry.name))+ continue+ }+ if (!entry.isFile() || shouldSkipFile(entry.name)) continue+ files.push(relative(workspaceDir, join(dir, entry.name)).split(sep).join('/'))+ }+ }++ await walk(root)+ return files+}++export async function listWorkspaceAssetLibrary(request: WorkspaceAssetLibraryRequest): Promise<AssetLibraryListResult> {+ try {+ const workspacePaths = (await Promise.all(ALLOWED_ROOTS.map((root) => collectFiles(request.workspaceDir, root)))).flat().sort()+ const entries = await Promise.all(workspacePaths.map((workspacePath) => buildEntry(request.workspaceDir, workspacePath)))+ return { success: true, entries: entries.filter((entry) => entry.state !== 'unsupported') }+ } catch (error) {+ return { success: false, error: libraryError('list-failed', error instanceof Error ? error.message : String(error)) }+ }+}++async function previewEntry(absolutePath: string, entry: AssetLibraryEntry): Promise<AssetLibraryPreviewPayload> {+ if (entry.previewKind === '3d-model') return { kind: '3d-model', viewerKind: extensionOf(entry.workspacePath) as 'glb' | 'gltf' }+ const stats = await stat(absolutePath)+ if (entry.previewKind === 'text') {+ const maxBytes = 64 * 1024+ const content = await readFile(absolutePath, 'utf8')+ return { kind: 'text', content: content.slice(0, maxBytes), byteLength: stats.size, truncated: content.length > maxBytes }+ }+ if (entry.previewKind === 'binary') {+ return { kind: 'binary', binaryKind: extensionOf(entry.workspacePath), byteLength: stats.size, message: 'Binary preview is unavailable.' }+ }+ return { kind: 'none' }+}++export async function readWorkspaceAssetLibraryEntry(request: WorkspaceAssetLibraryReadRequest): Promise<AssetLibraryReadResult> {+ try {+ const normalized = normalizeWorkspaceAssetPath(request.workspaceDir, request.workspacePath)+ const sourceValidation = await validateRequestedSource(request.workspaceDir, normalized.workspacePath, request.sourceWorkspacePath)+ if (!sourceValidation.success) return { success: false, error: sourceValidation.error }+ const entry = await buildEntry(request.workspaceDir, normalized.workspacePath)+ return { success: true, entry, preview: await previewEntry(normalized.absolutePath, entry) }+ } catch (error) {+ return { success: false, error: libraryError('unsafe-path', error instanceof Error ? error.message : String(error)) }+ }+}++async function validateRequestedSource(workspaceDir: string, workspacePath: string, sourceWorkspacePath?: string): Promise<{ success: true } | { success: false, error: AssetLibraryError }> {+ if (!sourceWorkspacePath) return { success: true }+ let source: NormalizedWorkspaceAssetPath+ try {+ source = normalizeWorkspaceAssetPath(workspaceDir, sourceWorkspacePath)+ } catch (error) {+ return { success: false, error: libraryError('unsafe-path', error instanceof Error ? error.message : String(error)) }+ }+ if (source.workspacePath === workspacePath) return { success: false, error: libraryError('not-openable', 'Linked source must not point to the same workspace asset.') }+ if (!isGlbOrGltf(source.workspacePath)) return { success: false, error: libraryError('not-openable', 'Linked source must be a safe .glb/.gltf workspace asset.') }+ try {+ await stat(source.absolutePath)+ } catch {+ return { success: false, error: libraryError('not-openable', 'Linked source workspace asset was not found.') }+ }+ const entry = await buildEntry(workspaceDir, workspacePath)+ if (entry.source?.workspacePath !== source.workspacePath) {+ return { success: false, error: libraryError('not-openable', 'Requested source does not match the indexed library source link.') }+ }+ return { success: true }+}++export async function openWorkspaceAssetLibraryEntry(request: WorkspaceAssetLibraryReadRequest): Promise<AssetLibraryOpenResult> {+ const read = await readWorkspaceAssetLibraryEntry(request)+ if (!read.success) return read+ if (request.sourceWorkspacePath) return { success: true, entry: read.entry }+ if (!read.entry.openable) {+ return { success: false, error: libraryError('not-openable', read.entry.nonOpenableReason ?? 'Workspace asset is not openable.') }+ }+ return { success: true, entry: read.entry }+}++function readPayloadRequest(payload: unknown): { workspacePath?: string, sourceWorkspacePath?: string } {+ if (typeof payload !== 'object' || payload === null) return {}+ const values = payload as { workspacePath?: unknown, sourceWorkspacePath?: unknown }+ return {+ workspacePath: typeof values.workspacePath === 'string' ? values.workspacePath : undefined,+ sourceWorkspacePath: typeof values.sourceWorkspacePath === 'string' ? values.sourceWorkspacePath : undefined,+ }+}++export function registerWorkspaceAssetLibraryIpcHandlers(deps: WorkspaceAssetLibraryIpcDeps): void {+ deps.ipcMain.handle('workspace:library:list', async () => listWorkspaceAssetLibrary({ workspaceDir: deps.getWorkspaceDir() }))+ deps.ipcMain.handle('workspace:library:read', async (_event, payload) => {+ const { workspacePath, sourceWorkspacePath } = readPayloadRequest(payload)+ if (!workspacePath) return { success: false, error: libraryError('invalid-request', 'workspacePath is required.') }+ return readWorkspaceAssetLibraryEntry({ workspaceDir: deps.getWorkspaceDir(), workspacePath, sourceWorkspacePath })+ })+ deps.ipcMain.handle('workspace:library:open', async (_event, payload) => {+ const { workspacePath, sourceWorkspacePath } = readPayloadRequest(payload)+ if (!workspacePath) return { success: false, error: libraryError('invalid-request', 'workspacePath is required.') }+ return openWorkspaceAssetLibraryEntry({ workspaceDir: deps.getWorkspaceDir(), workspacePath, sourceWorkspacePath })+ })+}diff --git a/apps/forge-desktop/electron/main/bounded-file-reader.test.mjs b/apps/forge-desktop/electron/main/bounded-file-reader.test.mjsnew file mode 100644index 000000000..030711802--- /dev/null+++ b/apps/forge-desktop/electron/main/bounded-file-reader.test.mjs@@ -0,0 +1,48 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import test from 'node:test'++const {+ MAX_SCENE_MANIFEST_BYTES,+ readLocalFileBase64,+} = await import(new URL('./bounded-file-reader.ts', import.meta.url).href)++test('the authoritative readFileBase64 IPC delegates to the bounded reader', () => {+ const handlers = readFileSync(resolve('electron/main/ipc-handlers.ts'), 'utf8')+ assert.match(+ handlers,+ /ipcMain\.handle\('fs:readFileBase64',[\s\S]*?readLocalFileBase64\(filePath\)/,+ )+})++test('oversized scene manifests are rejected before their bytes are read', async () => {+ let reads = 0+ await assert.rejects(+ readLocalFileBase64('/workspace/room/scene-manifest.json', {+ statFile: async () => ({ size: MAX_SCENE_MANIFEST_BYTES + 1, isFile: () => true }),+ readBytes: async () => { reads++; return new Uint8Array() },+ }),+ /exceeds the 1 MiB limit/,+ )+ assert.equal(reads, 0)+})++test('scene manifests at the bound are read and encoded', async () => {+ const bytes = new TextEncoder().encode('{"schema":"modly.scene-manifest.v1"}')+ const encoded = await readLocalFileBase64('/workspace/room/scene-manifest.json', {+ statFile: async () => ({ size: MAX_SCENE_MANIFEST_BYTES, isFile: () => true }),+ readBytes: async () => bytes,+ })+ assert.equal(encoded, Buffer.from(bytes).toString('base64'))+})++test('a manifest that grows after stat is rejected before base64 transfer', async () => {+ await assert.rejects(+ readLocalFileBase64('/workspace/room/scene-manifest.json', {+ statFile: async () => ({ size: 1, isFile: () => true }),+ readBytes: async () => new Uint8Array(MAX_SCENE_MANIFEST_BYTES + 1),+ }),+ /exceeds the 1 MiB limit/,+ )+})diff --git a/apps/forge-desktop/electron/main/bounded-file-reader.ts b/apps/forge-desktop/electron/main/bounded-file-reader.tsnew file mode 100644index 000000000..f7b18ba4d--- /dev/null+++ b/apps/forge-desktop/electron/main/bounded-file-reader.ts@@ -0,0 +1,40 @@+import { basename } from 'node:path'+import { readFile, stat } from 'node:fs/promises'++export const SCENE_MANIFEST_FILE_NAME = 'scene-manifest.json'+export const MAX_SCENE_MANIFEST_BYTES = 1024 * 1024++type FileReadDependencies = {+ statFile: (filePath: string) => Promise<{ size: number; isFile: () => boolean }>+ readBytes: (filePath: string) => Promise<Uint8Array>+}++const DEFAULT_DEPENDENCIES: FileReadDependencies = {+ statFile: stat,+ readBytes: readFile,+}++export async function readLocalFileBase64(+ filePath: string,+ dependencies: FileReadDependencies = DEFAULT_DEPENDENCIES,+): Promise<string> {+ if (typeof filePath !== 'string' || filePath.trim().length === 0) {+ throw new Error('fs:readFileBase64 requires a non-empty file path')+ }++ const isSceneManifest = basename(filePath) === SCENE_MANIFEST_FILE_NAME+ if (isSceneManifest) {+ const fileInfo = await dependencies.statFile(filePath)+ if (!fileInfo.isFile()) throw new Error('Scene manifest is not a file')+ if (fileInfo.size > MAX_SCENE_MANIFEST_BYTES) {+ throw new Error('Scene manifest exceeds the 1 MiB limit')+ }+ }++ const bytes = await dependencies.readBytes(filePath)+ // Recheck the transferred bytes in case the file grew between stat and read.+ if (isSceneManifest && bytes.byteLength > MAX_SCENE_MANIFEST_BYTES) {+ throw new Error('Scene manifest exceeds the 1 MiB limit')+ }+ return Buffer.from(bytes).toString('base64')+}diff --git a/apps/forge-desktop/electron/main/builtin-sync.ts b/apps/forge-desktop/electron/main/builtin-sync.tsnew file mode 100644index 000000000..e230ab72f--- /dev/null+++ b/apps/forge-desktop/electron/main/builtin-sync.ts@@ -0,0 +1,38 @@+import { join } from 'path'+import { app } from 'electron'+import { cpSync, existsSync, mkdirSync, rmSync } from 'fs'+import { logger } from './logger'++export function getBuiltinExtensionsDir(): string {+ return join(app.getPath('userData'), 'builtin-extensions')+}++function getBuiltinResourcesDir(): string {+ if (app.isPackaged) {+ return join(process.resourcesPath, 'builtin-extensions')+ }+ // Dev: built-ins compiled to out/builtin-extensions by build-builtins.mjs+ return join(__dirname, '../../out/builtin-extensions')+}++/**+ * Copies built-in extensions from app resources to userData/builtin-extensions.+ * Always overwrites — ensures built-ins are always up to date with the app version.+ */+export function syncBuiltinExtensions(): void {+ const resourcesDir = getBuiltinResourcesDir()++ if (!existsSync(resourcesDir)) {+ logger.info('[builtin-sync] No built-in extensions resources found, skipping.')+ return+ }++ const destDir = getBuiltinExtensionsDir()++ // Wipe dest first so removed extensions don't linger+ if (existsSync(destDir)) rmSync(destDir, { recursive: true, force: true })+ mkdirSync(destDir, { recursive: true })++ cpSync(resourcesDir, destDir, { recursive: true })+ logger.info(`[builtin-sync] Built-in extensions synced to ${destDir}`)+}diff --git a/apps/forge-desktop/electron/main/copy-runtime.test.mjs b/apps/forge-desktop/electron/main/copy-runtime.test.mjsnew file mode 100644index 000000000..b5dcbdb03--- /dev/null+++ b/apps/forge-desktop/electron/main/copy-runtime.test.mjs@@ -0,0 +1,100 @@+/**+ * Guards the symlink property that makes the AppImage's "stable" Python copy+ * actually stable. Getting this wrong is silent at copy time and only breaks on+ * the *next* launch, once the source mount is gone — so it needs a test that+ * checks the links rather than the copy succeeding.+ */+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import {+ mkdtempSync, mkdirSync, writeFileSync, symlinkSync, readlinkSync, rmSync, existsSync,+} from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve, isAbsolute } from 'node:path'++function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-copy-test-')), 'copy-runtime.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('electron/main/copy-runtime.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++const { copyRuntimeTree } = loadModule()++// makeRuntime() below needs symlinkSync, which on Windows requires Developer+// Mode (or elevation) — and the AppImage failure mode this file guards is+// Linux-only anyway.+const symlinkOpts = {+ skip: process.platform === 'win32' && 'symlinks require Developer Mode on Windows',+}++/** Builds a miniature of the bundled runtime: a real binary plus relative links. */+function makeRuntime(root) {+ mkdirSync(join(root, 'bin'), { recursive: true })+ mkdirSync(join(root, 'lib'), { recursive: true })+ writeFileSync(join(root, 'bin', 'python3.11'), '#!/bin/sh\n', 'utf8')+ symlinkSync('python3.11', join(root, 'bin', 'python3'))+ symlinkSync('python3.11', join(root, 'bin', 'python'))+ writeFileSync(join(root, 'lib', 'libpython3.11.so.1.0'), '', 'utf8')+ symlinkSync('libpython3.11.so.1.0', join(root, 'lib', 'libpython3.11.so'))+}++test('copyRuntimeTree keeps relative symlinks relative', symlinkOpts, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'modly-runtime-'))+ const source = join(dir, 'mount', 'python-embed')+ const dest = join(dir, 'stable', 'python-embed')+ makeRuntime(source)++ await copyRuntimeTree(source, dest)++ for (const link of ['bin/python3', 'bin/python', 'lib/libpython3.11.so']) {+ const target = readlinkSync(join(dest, link))+ assert.ok(+ !isAbsolute(target),+ `${link} was rewritten to an absolute path (${target}); it would point back at the source mount`,+ )+ assert.ok(!target.includes(source), `${link} still references the source tree`)+ }++ rmSync(dir, { recursive: true, force: true })+})++test('the copy survives the source being deleted', symlinkOpts, async () => {+ // This is the actual failure mode: the AppImage mount disappears between+ // launches, and every venv built from the copy dies with it.+ const dir = mkdtempSync(join(tmpdir(), 'modly-runtime-'))+ const source = join(dir, 'mount', 'python-embed')+ const dest = join(dir, 'stable', 'python-embed')+ makeRuntime(source)++ await copyRuntimeTree(source, dest)+ rmSync(join(dir, 'mount'), { recursive: true, force: true })++ // existsSync follows symlinks, so this is false for a dangling link — exactly+ // the check generator_registry.py's _venv_python(...).exists() performs.+ assert.ok(existsSync(join(dest, 'bin', 'python3')), 'bin/python3 is dangling after the source went away')+ assert.ok(existsSync(join(dest, 'lib', 'libpython3.11.so')), 'libpython3.11.so is dangling')+})++test('copyRuntimeTree copies regular files and directory structure', symlinkOpts, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'modly-runtime-'))+ const source = join(dir, 'mount', 'python-embed')+ const dest = join(dir, 'stable', 'python-embed')+ makeRuntime(source)++ await copyRuntimeTree(source, dest)++ assert.ok(existsSync(join(dest, 'bin', 'python3.11')))+ assert.ok(existsSync(join(dest, 'lib', 'libpython3.11.so.1.0')))++ rmSync(dir, { recursive: true, force: true })+})diff --git a/apps/forge-desktop/electron/main/copy-runtime.ts b/apps/forge-desktop/electron/main/copy-runtime.tsnew file mode 100644index 000000000..eb062f5cc--- /dev/null+++ b/apps/forge-desktop/electron/main/copy-runtime.ts@@ -0,0 +1,35 @@+/**+ * Copying the bundled Python runtime out of an ephemeral AppImage mount.+ *+ * Kept apart from python-setup.ts (which imports electron) so the symlink+ * behaviour this depends on can be tested — it is subtle, silent when wrong,+ * and only shows up on the *next* launch.+ */++import { cp } from 'fs/promises'++/**+ * Copies a self-contained runtime tree, keeping relative symlinks relative.+ *+ * `verbatimSymlinks` is the whole point. Without it `fs.cp` resolves a relative+ * link (`bin/python3 -> python3.11`) into an absolute path pointing back at the+ * *source* tree. When the source is an AppImage mount at+ * /tmp/.mount_Modly-XXXXXX/ — which is a different path on every launch — the+ * copy silently keeps a hard dependency on a directory that is about to vanish:+ *+ * - `bin/python3` in the "stable" copy points into the old mount+ * - `sys._base_executable` of any venv made from it inherits that path+ * - every extension venv records it in pyvenv.cfg and as a bin/python symlink+ * - on the next launch the mount is gone, so every extension venv is dead+ *+ * The user-visible symptom is remote from the cause: the extension registry+ * finds no usable venv, falls back to importing generator.py in the main API+ * process, and reports a missing third-party module such as `No module named 'PIL'`.+ */+export async function copyRuntimeTree(source: string, destination: string): Promise<void> {+ await cp(source, destination, {+ recursive: true,+ preserveTimestamps: true,+ verbatimSymlinks: true,+ })+}diff --git a/apps/forge-desktop/electron/main/extension-install-recovery.test.mjs b/apps/forge-desktop/electron/main/extension-install-recovery.test.mjsnew file mode 100644index 000000000..81fc77958--- /dev/null+++ b/apps/forge-desktop/electron/main/extension-install-recovery.test.mjs@@ -0,0 +1,693 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import {+ chmodSync,+ existsSync,+ linkSync,+ mkdtempSync,+ mkdirSync,+ readFileSync,+ readdirSync,+ rmSync,+ statSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++// Windows refuses symlink creation unless the process is elevated or Developer+// Mode is on, so probe once rather than letting the test report an EPERM as a+// product failure — that turns a stock Windows checkout into a failing suite.+const symlinksAvailable = (() => {+ const probe = mkdtempSync(join(tmpdir(), 'modly-symlink-probe-'))+ try {+ symlinkSync(join(probe, 'target'), join(probe, 'link'), 'dir')+ return true+ } catch {+ return false+ } finally {+ rmSync(probe, { recursive: true, force: true })+ }+})()++function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-recovery-module-')), 'extension-install-recovery.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('electron/main/extension-install-recovery.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++test('startup reconciliation removes all orphan incomplete folders, including corrupted names', async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-recovery-test-'))+ const corrupted = join(root, 'Broken Extension')+ const valid = join(root, 'later-extension')+ mkdirSync(corrupted)+ mkdirSync(valid)+ writeFileSync(join(corrupted, '.modly-incomplete'), 'installing', 'utf8')+ writeFileSync(join(valid, '.modly-incomplete'), 'installing', 'utf8')++ try {+ const mod = loadModule()+ await mod.reconcileInterruptedExtensionInstalls(root)++ assert.equal(existsSync(corrupted), false)+ assert.equal(existsSync(valid), false)+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('failed update rollback replaces the unvalidated destination with its backup', async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-rollback-test-'))+ const destination = join(root, 'pixal3d')+ const backup = join(root, '.modly-backup-pixal3d-100')+ mkdirSync(destination)+ mkdirSync(backup)+ writeFileSync(join(destination, 'version.txt'), 'new-broken', 'utf8')+ writeFileSync(join(destination, '.modly-registration-pending'), 'pending', 'utf8')+ writeFileSync(join(backup, 'version.txt'), 'old-working', 'utf8')++ try {+ const mod = loadModule()+ const result = await mod.restoreExtensionBackup(destination, backup)++ assert.deepEqual(result, { ok: true })+ assert.equal(readFileSync(join(destination, 'version.txt'), 'utf8'), 'old-working')+ assert.equal(existsSync(join(destination, '.modly-registration-pending')), false)+ assert.equal(existsSync(backup), false)+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('startup restores a parked version when registration was interrupted', async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-pending-recovery-test-'))+ const destination = join(root, 'pixal3d')+ const backup = join(root, '.modly-backup-pixal3d-101')+ mkdirSync(destination)+ mkdirSync(backup)+ writeFileSync(join(destination, 'version.txt'), 'new-unvalidated', 'utf8')+ writeFileSync(join(backup, 'version.txt'), 'old-working', 'utf8')+ writeFileSync(join(root, '.modly-registration-pending-pixal3d-101'), 'pending', 'utf8')++ try {+ const mod = loadModule()+ await mod.reconcileInterruptedExtensionInstalls(root)++ assert.equal(readFileSync(join(destination, 'version.txt'), 'utf8'), 'old-working')+ assert.equal(existsSync(backup), false)+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-101')),+ false,+ )+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('update validation keeps pending state hidden from the destination until commit', async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-update-validation-test-'))+ const destination = join(root, 'pixal3d')+ const backup = join(root, '.modly-backup-pixal3d-104')+ mkdirSync(destination)+ mkdirSync(backup)+ writeFileSync(join(destination, '.modly-incomplete'), 'setup', 'utf8')++ try {+ const mod = loadModule()+ const transaction = await mod.beginExtensionRegistrationTransaction(+ root,+ 'pixal3d',+ '104',+ )+ assert.equal(transaction.ok, true)+ assert.equal(transaction.validationCapability.extensionId, 'pixal3d')+ assert.equal(transaction.validationCapability.destinationName, 'pixal3d')+ assert.equal(+ transaction.validationCapability.stateName,+ '.modly-registration-pending-pixal3d-104',+ )+ assert.ok(transaction.validationCapability.token.length >= 32)+ const capabilityStat = statSync(+ join(root, '.modly-registration-pending-pixal3d-104'),+ )+ assert.equal(capabilityStat.nlink, 1)+ if (process.platform !== 'win32') {+ assert.equal(capabilityStat.mode & 0o077, 0)+ }++ let validatorCalled = false+ await mod.validateExtensionDestinationRegistration(+ destination,+ async () => {+ validatorCalled = true+ assert.equal(existsSync(join(destination, '.modly-incomplete')), false)+ assert.equal(existsSync(join(destination, '.modly-registration-pending')), false)+ assert.equal(existsSync(join(backup, '.modly-registration-pending')), false)+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-104')),+ true,+ )+ },+ 'test-update',+ )++ assert.equal(validatorCalled, true)+ assert.deepEqual(+ await mod.cleanupValidatedExtensionBackups(root, 'pixal3d'),+ { ok: true },+ )+ assert.equal(existsSync(backup), false)+ assert.equal(existsSync(join(destination, '.modly-registration-validated')), false)+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-104')),+ false,+ )+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('Repair transaction starts before setup and keeps state outside the destination', async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-repair-validation-test-'))+ const destination = join(root, 'pixal3d')+ const backup = join(root, '.modly-backup-pixal3d-105')+ mkdirSync(destination)+ mkdirSync(backup)++ try {+ const mod = loadModule()+ const order = []+ let runtimeLoaded = true+ let setupCalled = false+ let validatorCalled = false+ await mod.runExtensionRepairTransaction({+ extensionsDir: root,+ extensionId: 'pixal3d',+ destinationDir: destination,+ suffix: '105',+ quarantine: async () => {+ order.push('quarantine')+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-105')),+ true,+ )+ runtimeLoaded = false+ },+ setup: async () => {+ order.push('setup')+ setupCalled = true+ assert.equal(runtimeLoaded, false)+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-105')),+ true,+ )+ assert.equal(existsSync(join(destination, '.modly-registration-pending')), false)+ assert.equal(existsSync(join(backup, '.modly-registration-pending')), false)+ },+ validate: async (validationCapability) => {+ order.push('validate')+ validatorCalled = true+ assert.equal(validationCapability.extensionId, 'pixal3d')+ assert.equal(+ validationCapability.stateName,+ '.modly-registration-pending-pixal3d-105',+ )+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-105')),+ true,+ )+ },+ })++ assert.equal(setupCalled, true)+ assert.equal(validatorCalled, true)+ assert.deepEqual(order, ['quarantine', 'setup', 'validate'])+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-105')),+ false,+ )+ assert.equal(existsSync(backup), false)+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('Repair setup failure retains pending quarantine and never validates runtime', async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-repair-setup-failure-test-'))+ const destination = join(root, 'pixal3d')+ mkdirSync(destination)++ try {+ const mod = loadModule()+ let runtimeLoaded = true+ let validatorCalled = false++ await assert.rejects(+ mod.runExtensionRepairTransaction({+ extensionsDir: root,+ extensionId: 'pixal3d',+ destinationDir: destination,+ suffix: '109',+ quarantine: async () => {+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-109')),+ true,+ )+ runtimeLoaded = false+ },+ setup: async () => {+ assert.equal(runtimeLoaded, false)+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-109')),+ true,+ )+ throw new Error('setup exploded')+ },+ validate: async () => {+ validatorCalled = true+ },+ }),+ /setup exploded/,+ )++ assert.equal(validatorCalled, false)+ assert.equal(runtimeLoaded, false)+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-109')),+ true,+ )+ assert.equal(existsSync(join(destination, '.modly-registration-pending')), false)+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('Repair validation failure re-evicts partially registered runtime state', async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-repair-validation-failure-test-'))+ const destination = join(root, 'pixal3d')+ mkdirSync(destination)++ try {+ const mod = loadModule()+ let runtimeLoaded = true+ let quarantineCount = 0++ await assert.rejects(+ mod.runExtensionRepairTransaction({+ extensionsDir: root,+ extensionId: 'pixal3d',+ destinationDir: destination,+ suffix: '113',+ quarantine: async () => {+ quarantineCount += 1+ runtimeLoaded = false+ },+ setup: async () => {+ assert.equal(runtimeLoaded, false)+ },+ validate: async () => {+ runtimeLoaded = true+ throw new Error('one node failed registration')+ },+ }),+ /one node failed registration/,+ )++ assert.equal(quarantineCount, 2)+ assert.equal(runtimeLoaded, false)+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-113')),+ true,+ )+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('fresh-install crash keeps a complete destination externally quarantined', async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-fresh-crash-test-'))+ const destination = join(root, 'pixal3d')+ mkdirSync(destination)+ writeFileSync(join(destination, 'version.txt'), 'unvalidated', 'utf8')++ try {+ const mod = loadModule()+ const transaction = await mod.beginExtensionRegistrationTransaction(+ root,+ 'pixal3d',+ '106',+ )+ assert.equal(transaction.ok, true)++ await mod.reconcileInterruptedExtensionInstalls(root)++ assert.equal(readFileSync(join(destination, 'version.txt'), 'utf8'), 'unvalidated')+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-106')),+ true,+ )+ assert.equal(existsSync(join(destination, '.modly-registration-pending')), false)+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('new registration capability replaces older pending attempts without a quarantine gap', async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-capability-rotation-test-'))+ const destination = join(root, 'pixal3d')+ mkdirSync(destination)++ try {+ const mod = loadModule()+ const first = await mod.beginExtensionRegistrationTransaction(+ root,+ 'pixal3d',+ '111',+ )+ const second = await mod.beginExtensionRegistrationTransaction(+ root,+ 'pixal3d',+ '112',+ )++ assert.equal(first.ok, true)+ assert.equal(second.ok, true)+ assert.notEqual(+ first.validationCapability.token,+ second.validationCapability.token,+ )+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-111')),+ false,+ )+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-112')),+ true,+ )+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('registration capability creation never overwrites a pre-existing sidecar', async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-capability-exclusive-test-'))+ const statePath = join(root, '.modly-registration-pending-pixal3d-114')+ writeFileSync(statePath, 'pre-existing', 'utf8')+ if (process.platform !== 'win32') chmodSync(statePath, 0o644)++ try {+ const mod = loadModule()+ const result = await mod.beginExtensionRegistrationTransaction(+ root,+ 'pixal3d',+ '114',+ )++ assert.equal(result.ok, false)+ assert.equal(readFileSync(statePath, 'utf8'), 'pre-existing')+ if (process.platform !== 'win32') {+ assert.equal(statSync(statePath).mode & 0o777, 0o644)+ }+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('registration capability creation rejects a hard-linked target', async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-capability-hardlink-test-'))+ const original = join(root, 'original')+ const statePath = join(root, '.modly-registration-pending-pixal3d-115')+ writeFileSync(original, 'pre-existing', 'utf8')+ linkSync(original, statePath)++ try {+ const mod = loadModule()+ const result = await mod.beginExtensionRegistrationTransaction(+ root,+ 'pixal3d',+ '115',+ )++ assert.equal(result.ok, false)+ assert.equal(readFileSync(original, 'utf8'), 'pre-existing')+ assert.equal(statSync(original).nlink, 2)+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('no-backup Repair failure preserves external quarantine state', async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-repair-failure-test-'))+ const destination = join(root, 'pixal3d')+ mkdirSync(destination)++ try {+ const mod = loadModule()+ assert.deepEqual(+ await mod.quarantineExtensionRegistrationFailure(root, 'pixal3d'),+ { ok: true },+ )++ const pendingNames = readdirSync(root).filter((name) =>+ name.startsWith('.modly-registration-pending-pixal3d-'),+ )+ assert.equal(pendingNames.length, 1)+ assert.equal(existsSync(join(destination, '.modly-registration-pending')), false)+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('failed local registration validation persists quarantine for restart', async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-local-validation-test-'))+ const destination = join(root, 'pixal3d')+ mkdirSync(destination)++ try {+ const mod = loadModule()+ let receivedCapability = null+ let runtimeLoaded = true+ let quarantineCount = 0++ await assert.rejects(+ mod.runExtensionRegistrationValidationTransaction({+ extensionsDir: root,+ extensionId: 'pixal3d',+ suffix: '110',+ quarantine: async () => {+ quarantineCount += 1+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-110')),+ true,+ )+ runtimeLoaded = false+ },+ activate: async () => {+ assert.equal(runtimeLoaded, false)+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-110')),+ true,+ )+ },+ validate: async (validationCapability) => {+ assert.equal(runtimeLoaded, false)+ receivedCapability = validationCapability+ runtimeLoaded = true+ throw new Error('venv not found')+ },+ }),+ /venv not found/,+ )++ assert.equal(receivedCapability.extensionId, 'pixal3d')+ assert.equal(runtimeLoaded, false)+ assert.equal(quarantineCount, 2)+ assert.equal(+ receivedCapability.stateName,+ '.modly-registration-pending-pixal3d-110',+ )+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-110')),+ true,+ )++ await mod.reconcileInterruptedExtensionInstalls(root)+ assert.equal(existsSync(destination), true)+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-110')),+ true,+ )+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('local link transaction creates quarantine before any destination mutation', async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-local-ordering-test-'))++ try {+ const mod = loadModule()+ const order = []+ let validatorCalled = false++ await assert.rejects(+ mod.runExtensionRegistrationValidationTransaction({+ extensionsDir: root,+ extensionId: 'pixal3d',+ suffix: '116',+ quarantine: async () => {+ order.push('quarantine')+ },+ activate: async () => {+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-116')),+ true,+ )+ order.push('mutate-link')+ throw new Error('simulated crash during link replacement')+ },+ validate: async () => {+ validatorCalled = true+ },+ }),+ /simulated crash during link replacement/,+ )++ assert.deepEqual(order, ['quarantine', 'mutate-link', 'quarantine'])+ assert.equal(validatorCalled, false)+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-116')),+ true,+ )+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('uninstall removes backups before the destination so restart cannot resurrect it', async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-uninstall-recovery-test-'))+ const destination = join(root, 'pixal3d')+ const backup = join(root, '.modly-backup-pixal3d-102')+ mkdirSync(destination)+ mkdirSync(backup)+ writeFileSync(join(destination, 'version.txt'), 'current', 'utf8')+ writeFileSync(join(backup, 'version.txt'), 'previous', 'utf8')+ writeFileSync(join(root, '.modly-registration-pending-pixal3d-102'), 'pending', 'utf8')++ try {+ const mod = loadModule()+ const result = await mod.removeExtensionWithBackups(root, 'pixal3d')++ assert.deepEqual(result, { ok: true })+ assert.equal(existsSync(destination), false)+ assert.equal(existsSync(backup), false)+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-102')),+ false,+ )++ await mod.reconcileInterruptedExtensionInstalls(root)+ assert.equal(existsSync(destination), false)+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('startup completes validated backup cleanup without replacing the destination', async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-validated-cleanup-test-'))+ const destination = join(root, 'pixal3d')+ const backup = join(root, '.modly-backup-pixal3d-103')+ mkdirSync(destination)+ mkdirSync(backup)+ writeFileSync(join(destination, 'version.txt'), 'new-working', 'utf8')+ writeFileSync(join(backup, 'version.txt'), 'old-working', 'utf8')+ writeFileSync(join(root, '.modly-registration-pending-pixal3d-103'), 'pending', 'utf8')+ writeFileSync(join(root, '.modly-registration-validated-pixal3d-104'), 'validated', 'utf8')++ try {+ const mod = loadModule()+ await mod.reconcileInterruptedExtensionInstalls(root)++ assert.equal(readFileSync(join(destination, 'version.txt'), 'utf8'), 'new-working')+ assert.equal(existsSync(backup), false)+ assert.equal(existsSync(join(destination, '.modly-registration-validated')), false)+ assert.equal(+ readdirSync(root).some((name) => name.startsWith('.modly-registration-')),+ false,+ )+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('destination validated marker cannot authorize deletion of an uncommitted backup', async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-forged-validated-test-'))+ const destination = join(root, 'pixal3d')+ const backup = join(root, '.modly-backup-pixal3d-107')+ mkdirSync(destination)+ mkdirSync(backup)+ writeFileSync(join(destination, 'version.txt'), 'unvalidated', 'utf8')+ writeFileSync(join(destination, '.modly-registration-validated'), 'packaged', 'utf8')+ writeFileSync(join(backup, 'version.txt'), 'old-working', 'utf8')++ try {+ const mod = loadModule()+ await mod.reconcileInterruptedExtensionInstalls(root)++ assert.equal(readFileSync(join(destination, 'version.txt'), 'utf8'), 'unvalidated')+ assert.equal(readFileSync(join(backup, 'version.txt'), 'utf8'), 'old-working')+ assert.equal(existsSync(join(destination, '.modly-registration-validated')), false)+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('registration transaction state never writes through a symlinked backup', {+ skip: symlinksAvailable+ ? false+ : 'symlink creation needs elevation or Developer Mode on this platform',+}, async () => {+ const root = mkdtempSync(join(tmpdir(), 'modly-symlink-state-test-'))+ const source = mkdtempSync(join(tmpdir(), 'modly-linked-source-'))+ const destination = join(root, 'pixal3d')+ const backup = join(root, '.modly-backup-pixal3d-108')+ mkdirSync(destination)+ symlinkSync(source, backup, 'dir')++ try {+ const mod = loadModule()+ const transaction = await mod.beginExtensionRegistrationTransaction(+ root,+ 'pixal3d',+ '108',+ )+ assert.equal(transaction.ok, true)++ assert.equal(existsSync(join(source, '.modly-registration-pending')), false)+ assert.equal(+ existsSync(join(root, '.modly-registration-pending-pixal3d-108')),+ true,+ )++ assert.deepEqual(+ await mod.cleanupValidatedExtensionBackups(root, 'pixal3d'),+ { ok: true },+ )+ assert.equal(existsSync(source), true)+ assert.equal(existsSync(join(source, '.modly-registration-pending')), false)+ } finally {+ rmSync(root, { recursive: true, force: true })+ rmSync(source, { recursive: true, force: true })+ }+})diff --git a/apps/forge-desktop/electron/main/extension-install-recovery.ts b/apps/forge-desktop/electron/main/extension-install-recovery.tsnew file mode 100644index 000000000..58add1bac--- /dev/null+++ b/apps/forge-desktop/electron/main/extension-install-recovery.ts@@ -0,0 +1,762 @@+import { existsSync } from 'fs'+import { open, readdir, rename, rm as rmAsync, writeFile } from 'fs/promises'+import { randomBytes } from 'crypto'+import { basename, join } from 'path'+import {+ EXT_BACKUP_PREFIX,+ EXT_INCOMPLETE_MARKER,+ EXT_REGISTRATION_PENDING_MARKER,+ EXT_STAGING_PREFIX,+ EXT_VALIDATED_MARKER,+ assertSafeExtensionId,+ isInternalExtensionDirName,+ parseExtensionBackupName,+ resolveExtensionPathWithinRoot,+ resolvePathWithinRoot,+} from './extension-path-guard'+import { incompleteInstallRecoveryAction } from './extension-install-utils'++const FS_RETRY_DELAYS_MS = [200, 500, 1500, 2500]+const REGISTRATION_PENDING_PREFIX = `${EXT_REGISTRATION_PENDING_MARKER}-`+const REGISTRATION_VALIDATED_PREFIX = `${EXT_VALIDATED_MARKER}-`++export interface InstallRecoveryLogger {+ info: (message: string) => void+ warn: (message: string) => void+}++const consoleLogger: InstallRecoveryLogger = {+ info: (message) => console.log(message),+ warn: (message) => console.warn(message),+}++function isLockedFsError(err: unknown): boolean {+ const code = (err as NodeJS.ErrnoException).code+ return code === 'EBUSY' || code === 'EPERM' || code === 'EACCES'+}++export type FsRetryResult =+ | { ok: true }+ | { ok: false; locked: boolean; error: unknown }++export type ExtensionMutationResult =+ | { ok: true }+ | {+ ok: false+ stage: 'scan' | 'backup' | 'destination' | 'marker'+ locked: boolean+ error: unknown+ }++export interface ExtensionRegistrationValidationCapability {+ extensionId: string+ destinationName: string+ stateName: string+ token: string+}++export type ExtensionRegistrationTransactionResult =+ | {+ ok: true+ validationCapability: ExtensionRegistrationValidationCapability+ }+ | Exclude<ExtensionMutationResult, { ok: true }>++async function fsWithRetry(+ op: () => Promise<void>,+ label: string,+ target: string,+ log: InstallRecoveryLogger,+): Promise<FsRetryResult> {+ for (let attempt = 0; ; attempt++) {+ try {+ await op()+ return { ok: true }+ } catch (err) {+ if (!isLockedFsError(err) || attempt === FS_RETRY_DELAYS_MS.length) {+ log.warn(`[${label}] ${target}: ${err}`)+ return { ok: false, locked: isLockedFsError(err), error: err }+ }+ await new Promise((resolve) => setTimeout(resolve, FS_RETRY_DELAYS_MS[attempt]))+ }+ }+}++export const rmWithRetry = (+ path: string,+ label: string,+ log: InstallRecoveryLogger = consoleLogger,+): Promise<FsRetryResult> =>+ fsWithRetry(() => rmAsync(path, { recursive: true, force: true }), label, path, log)++export const renameWithRetry = (+ from: string,+ to: string,+ label: string,+ log: InstallRecoveryLogger = consoleLogger,+): Promise<FsRetryResult> =>+ fsWithRetry(() => rename(from, to), label, `${from} -> ${to}`, log)++const writeMarkerWithRetry = (+ path: string,+ label: string,+ log: InstallRecoveryLogger,+ content = new Date().toISOString(),+): Promise<FsRetryResult> =>+ fsWithRetry(+ () => writeFile(path, content, { encoding: 'utf-8', mode: 0o600 }),+ label,+ path,+ log,+ )++const writeCapabilityMarkerWithRetry = (+ path: string,+ content: string,+ log: InstallRecoveryLogger,+): Promise<FsRetryResult> =>+ fsWithRetry(+ async () => {+ const handle = await open(path, 'wx', 0o600)+ try {+ if (process.platform !== 'win32') await handle.chmod(0o600)+ await handle.writeFile(content, { encoding: 'utf-8' })+ await handle.sync()+ const fileStat = await handle.stat()+ if (!fileStat.isFile() || fileStat.nlink !== 1) {+ throw new Error('Registration capability sidecar must be a single regular file')+ }+ if (+ process.platform !== 'win32'+ && (+ (fileStat.mode & 0o077) !== 0+ || (typeof process.getuid === 'function' && fileStat.uid !== process.getuid())+ )+ ) {+ throw new Error('Registration capability sidecar permissions are unsafe')+ }+ } finally {+ await handle.close()+ }+ },+ 'ext-install',+ path,+ log,+ )++function failedMutation(+ stage: Exclude<ExtensionMutationResult, { ok: true }>['stage'],+ result: Exclude<FsRetryResult, { ok: true }>,+): Exclude<ExtensionMutationResult, { ok: true }> {+ return {+ ok: false,+ stage,+ locked: result.locked,+ error: result.error,+ }+}++async function extensionBackupPaths(+ extensionsDir: string,+ extensionId: string,+): Promise<+ | { ok: true; paths: string[] }+ | { ok: false; stage: 'scan'; locked: boolean; error: unknown }+> {+ let names: string[]+ try {+ names = await readdir(extensionsDir)+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {+ return { ok: true, paths: [] }+ }+ return {+ ok: false,+ stage: 'scan',+ locked: isLockedFsError(error),+ error,+ }+ }++ return {+ ok: true,+ paths: names+ .filter((name) => parseExtensionBackupName(name)?.extensionId === extensionId)+ .sort()+ .reverse()+ .map((name) => join(extensionsDir, name)),+ }+}++function parseRegistrationStateName(+ name: string,+ prefix: string,+): { extensionId: string } | null {+ if (!name.startsWith(prefix)) return null+ const match = name.slice(prefix.length).match(/^(.+)-\d+$/)+ if (!match) return null+ try {+ return { extensionId: assertSafeExtensionId(match[1]) }+ } catch {+ return null+ }+}++export const parseExtensionRegistrationPendingName = (+ name: string,+): { extensionId: string } | null =>+ parseRegistrationStateName(name, REGISTRATION_PENDING_PREFIX)++function buildRegistrationStatePath(+ extensionsDir: string,+ extensionId: string,+ suffix: string,+ prefix: string,+): string {+ const safeId = assertSafeExtensionId(extensionId)+ if (!/^\d+$/.test(suffix)) throw new Error('Registration state suffix must be numeric')+ return resolvePathWithinRoot(extensionsDir, `${prefix}${safeId}-${suffix}`)+}++async function registrationStatePaths(+ extensionsDir: string,+ extensionId: string,+ prefix: string,+): Promise<+ | { ok: true; paths: string[] }+ | { ok: false; stage: 'scan'; locked: boolean; error: unknown }+> {+ let names: string[]+ try {+ names = await readdir(extensionsDir)+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {+ return { ok: true, paths: [] }+ }+ return {+ ok: false,+ stage: 'scan',+ locked: isLockedFsError(error),+ error,+ }+ }++ return {+ ok: true,+ paths: names+ .filter((name) => parseRegistrationStateName(name, prefix)?.extensionId === extensionId)+ .sort()+ .reverse()+ .map((name) => join(extensionsDir, name)),+ }+}++async function removeRegistrationState(+ extensionsDir: string,+ extensionId: string,+ log: InstallRecoveryLogger,+): Promise<ExtensionMutationResult> {+ for (const prefix of [REGISTRATION_PENDING_PREFIX, REGISTRATION_VALIDATED_PREFIX]) {+ const states = await registrationStatePaths(extensionsDir, extensionId, prefix)+ if (!states.ok) return states+ for (const statePath of states.paths) {+ const removed = await rmWithRetry(statePath, 'ext-cleanup', log)+ if (!removed.ok) return failedMutation('marker', removed)+ }+ }+ return { ok: true }+}++export const clearExtensionRegistrationTransaction = (+ extensionsDir: string,+ extensionId: string,+ log: InstallRecoveryLogger = consoleLogger,+): Promise<ExtensionMutationResult> =>+ removeRegistrationState(extensionsDir, extensionId, log)++export async function restoreExtensionBackup(+ destinationDir: string,+ backupDir: string,+ log: InstallRecoveryLogger = consoleLogger,+): Promise<ExtensionMutationResult> {+ const removed = await rmWithRetry(destinationDir, 'ext-restore', log)+ if (!removed.ok) return failedMutation('destination', removed)++ const restored = await renameWithRetry(backupDir, destinationDir, 'ext-restore', log)+ if (!restored.ok) return failedMutation('backup', restored)++ return { ok: true }+}++export async function beginExtensionRegistrationTransaction(+ extensionsDir: string,+ extensionId: string,+ suffix: string,+ log: InstallRecoveryLogger = consoleLogger,+): Promise<ExtensionRegistrationTransactionResult> {+ const safeExtensionId = assertSafeExtensionId(extensionId)+ const pendingPath = buildRegistrationStatePath(+ extensionsDir,+ safeExtensionId,+ suffix,+ REGISTRATION_PENDING_PREFIX,+ )+ const validationCapability: ExtensionRegistrationValidationCapability = {+ extensionId: safeExtensionId,+ destinationName: safeExtensionId,+ stateName: basename(pendingPath),+ token: randomBytes(32).toString('base64url'),+ }+ const marked = await writeCapabilityMarkerWithRetry(+ pendingPath,+ JSON.stringify({+ version: 1,+ extensionId: safeExtensionId,+ destinationName: safeExtensionId,+ token: validationCapability.token,+ consumed: false,+ }),+ log,+ )+ if (!marked.ok) return failedMutation('marker', marked)++ // The capability authorizes exactly one root sidecar. Keep the new marker in+ // place while removing older attempts so there is never an unquarantined+ // window, and a capability cannot implicitly bypass another transaction.+ const pendingStates = await registrationStatePaths(+ extensionsDir,+ safeExtensionId,+ REGISTRATION_PENDING_PREFIX,+ )+ if (!pendingStates.ok) return pendingStates+ for (const statePath of pendingStates.paths) {+ if (statePath === pendingPath) continue+ const removed = await rmWithRetry(statePath, 'ext-install', log)+ if (!removed.ok) return failedMutation('marker', removed)+ }++ return { ok: true, validationCapability }+}++export async function quarantineExtensionRegistrationFailure(+ extensionsDir: string,+ extensionId: string,+ log: InstallRecoveryLogger = consoleLogger,+): Promise<ExtensionMutationResult> {+ const pending = await registrationStatePaths(+ extensionsDir,+ extensionId,+ REGISTRATION_PENDING_PREFIX,+ )+ if (!pending.ok) return pending+ if (pending.paths.length > 0) return { ok: true }+ const started = await beginExtensionRegistrationTransaction(+ extensionsDir,+ extensionId,+ String(Date.now()),+ log,+ )+ return started.ok ? { ok: true } : started+}++export async function runExtensionRepairTransaction(+ options: {+ extensionsDir: string+ extensionId: string+ destinationDir: string+ suffix: string+ quarantine: () => Promise<void>+ setup: () => Promise<void>+ validate: (capability: ExtensionRegistrationValidationCapability) => Promise<void>+ },+ log: InstallRecoveryLogger = consoleLogger,+): Promise<void> {+ // Repair can mutate an existing environment before runtime validation. Mark+ // it pending first so a setup failure or process crash leaves the extension+ // externally quarantined for the next startup.+ const pendingRegistration = await beginExtensionRegistrationTransaction(+ options.extensionsDir,+ options.extensionId,+ options.suffix,+ log,+ )+ if (!pendingRegistration.ok) {+ throw new Error(+ `Could not preserve the extension rollback state during ${pendingRegistration.stage}: `+ + `${String(pendingRegistration.error)}`,+ )+ }++ // Evict any already-loaded generator before setup mutates its environment.+ // Failure here is also fail-closed: pending state remains for restart/UI+ // recovery, and setup never begins while stale runtime code is live.+ await options.quarantine()++ // Intentionally do not clear pending state when quarantine or setup fails. A+ // partially modified environment has not been proven safe to discover or+ // execute.+ await options.setup()++ try {+ await validateExtensionDestinationRegistration(+ options.destinationDir,+ () => options.validate(pendingRegistration.validationCapability),+ 'ext-repair',+ log,+ )+ } catch (registrationError) {+ const quarantined = await quarantineExtensionRegistrationFailure(+ options.extensionsDir,+ options.extensionId,+ log,+ )+ if (!quarantined.ok) {+ throw new Error(+ `Runtime registration failed, and Modly could not preserve quarantine `+ + `during ${quarantined.stage}: ${String(quarantined.error)}. `+ + `Original failure: ${String(registrationError)}`,+ )+ }+ try {+ await options.quarantine()+ } catch (runtimeQuarantineError) {+ throw new Error(+ `Runtime registration failed, and Modly preserved filesystem quarantine but `+ + `could not evict partially registered runtime state: `+ + `${String(runtimeQuarantineError)}. Original failure: ${String(registrationError)}`,+ )+ }+ throw registrationError+ }++ const cleaned = await cleanupValidatedExtensionBackups(+ options.extensionsDir,+ options.extensionId,+ log,+ )+ if (!cleaned.ok) {+ throw new Error(+ `Runtime registration succeeded, but Modly could not finish removing the previous `+ + `extension backup during ${cleaned.stage}: ${String(cleaned.error)}. `+ + `Restart Modly to retry the validated cleanup.`,+ )+ }+}++export async function runExtensionRegistrationValidationTransaction(+ options: {+ extensionsDir: string+ extensionId: string+ suffix: string+ quarantine: () => Promise<void>+ activate: () => Promise<void>+ validate: (capability: ExtensionRegistrationValidationCapability) => Promise<void>+ },+ log: InstallRecoveryLogger = consoleLogger,+): Promise<void> {+ const pendingRegistration = await beginExtensionRegistrationTransaction(+ options.extensionsDir,+ options.extensionId,+ options.suffix,+ log,+ )+ if (!pendingRegistration.ok) {+ throw new Error(+ `Could not preserve extension quarantine during ${pendingRegistration.stage}: `+ + `${String(pendingRegistration.error)}`,+ )+ }++ await options.quarantine()++ try {+ await options.activate()+ await options.validate(pendingRegistration.validationCapability)+ } catch (registrationError) {+ const quarantined = await quarantineExtensionRegistrationFailure(+ options.extensionsDir,+ options.extensionId,+ log,+ )+ if (!quarantined.ok) {+ throw new Error(+ `Runtime registration failed, and Modly could not preserve quarantine `+ + `during ${quarantined.stage}: ${String(quarantined.error)}. `+ + `Original failure: ${String(registrationError)}`,+ )+ }+ try {+ await options.quarantine()+ } catch (runtimeQuarantineError) {+ throw new Error(+ `Runtime registration failed, and Modly preserved filesystem quarantine but `+ + `could not evict partially registered runtime state: `+ + `${String(runtimeQuarantineError)}. Original failure: ${String(registrationError)}`,+ )+ }+ throw registrationError+ }++ const cleaned = await cleanupValidatedExtensionBackups(+ options.extensionsDir,+ options.extensionId,+ log,+ )+ if (!cleaned.ok) {+ throw new Error(+ `Runtime registration succeeded, but Modly could not finish transaction cleanup `+ + `during ${cleaned.stage}: ${String(cleaned.error)}. `+ + `Restart Modly to retry the validated cleanup.`,+ )+ }+}++export async function validateExtensionDestinationRegistration(+ destinationDir: string,+ validate: () => Promise<void>,+ label: string,+ log: InstallRecoveryLogger = consoleLogger,+): Promise<void> {+ const removed = await rmWithRetry(join(destinationDir, EXT_INCOMPLETE_MARKER), label, log)+ if (!removed.ok) {+ throw new Error(+ `Could not clear ${EXT_INCOMPLETE_MARKER} before runtime registration: `+ + `${String(removed.error)}`,+ )+ }+ await validate()+}++export async function removeExtensionWithBackups(+ extensionsDir: string,+ extensionId: string,+ log: InstallRecoveryLogger = consoleLogger,+): Promise<ExtensionMutationResult> {+ let destinationLeaf = extensionId+ try {+ destinationLeaf = assertSafeExtensionId(extensionId)+ } catch {+ // Manual/corrupted folders may not conform to extension IDs. They still+ // remain uninstallable under the root-confinement rule, but can never own+ // a valid internal backup name.+ }++ // Resolve before mutating anything. Corrupted folder names are allowed, but+ // traversal outside extensionsDir is never allowed.+ const destinationDir = resolvePathWithinRoot(extensionsDir, destinationLeaf)+ const backups = await extensionBackupPaths(extensionsDir, destinationLeaf)+ if (!backups.ok) return backups++ const stateRemoved = await removeRegistrationState(extensionsDir, destinationLeaf, log)+ if (!stateRemoved.ok) return stateRemoved++ // Backups must go first. If destination deletion later fails, the visible+ // extension remains uninstallable on retry, but startup cannot resurrect it.+ for (const backupDir of backups.paths) {+ const removed = await rmWithRetry(backupDir, 'ext-uninstall', log)+ if (!removed.ok) return failedMutation('backup', removed)+ }++ const removed = await rmWithRetry(destinationDir, 'ext-uninstall', log)+ if (!removed.ok) return failedMutation('destination', removed)+ return { ok: true }+}++export async function cleanupValidatedExtensionBackups(+ extensionsDir: string,+ extensionId: string,+ log: InstallRecoveryLogger = consoleLogger,+): Promise<ExtensionMutationResult> {+ const backups = await extensionBackupPaths(extensionsDir, extensionId)+ if (!backups.ok) return backups++ // Commit registration outside the extension tree before deleting pending+ // state or rollback copies. Repository contents and linked source trees can+ // never forge or retain this transaction marker.+ const validatedPath = buildRegistrationStatePath(+ extensionsDir,+ extensionId,+ String(Date.now()),+ REGISTRATION_VALIDATED_PREFIX,+ )+ const marked = await writeMarkerWithRetry(validatedPath, 'ext-cleanup', log)+ if (!marked.ok) return failedMutation('marker', marked)++ for (const backupDir of backups.paths) {+ const removed = await rmWithRetry(backupDir, 'ext-cleanup', log)+ if (!removed.ok) return failedMutation('backup', removed)+ }++ return removeRegistrationState(extensionsDir, extensionId, log)+}++export async function reconcileInterruptedExtensionInstalls(+ extensionsDir: string,+ log: InstallRecoveryLogger = consoleLogger,+): Promise<void> {+ if (!existsSync(extensionsDir)) return++ const entries = await readdir(extensionsDir, { withFileTypes: true })+ const names = entries.map((entry) => entry.name)++ await Promise.all(+ names+ .filter((name) => name.startsWith(EXT_STAGING_PREFIX))+ .map((name) => rmWithRetry(join(extensionsDir, name), 'ext-cleanup', log)),+ )++ // Transaction markers live beside extension folders, never inside them.+ // This keeps validation markers invisible to Python discovery and prevents a+ // linked extension from writing recovery state into a developer source tree.+ const backups = names.filter((name) => name.startsWith(EXT_BACKUP_PREFIX)).sort().reverse()+ const extensionIdsWithBackups = new Set<string>()+ const backupsByExtension = new Map<string, string[]>()+ const pendingExtensionIds = new Set<string>()+ const validatedExtensionIds = new Set<string>()++ for (const name of backups) {+ const backupPath = join(extensionsDir, name)+ const parsed = parseExtensionBackupName(name)+ if (!parsed) {+ await rmWithRetry(backupPath, 'ext-cleanup', log)+ continue+ }+ extensionIdsWithBackups.add(parsed.extensionId)+ const extensionBackups = backupsByExtension.get(parsed.extensionId) ?? []+ extensionBackups.push(backupPath)+ backupsByExtension.set(parsed.extensionId, extensionBackups)+ }++ for (const [prefix, target] of [+ [REGISTRATION_PENDING_PREFIX, pendingExtensionIds],+ [REGISTRATION_VALIDATED_PREFIX, validatedExtensionIds],+ ] as const) {+ for (const name of names.filter((candidate) => candidate.startsWith(prefix))) {+ const parsed = parseRegistrationStateName(name, prefix)+ if (!parsed) {+ await rmWithRetry(join(extensionsDir, name), 'ext-cleanup', log)+ continue+ }+ target.add(parsed.extensionId)+ }+ }++ const transactionExtensionIds = new Set([+ ...backupsByExtension.keys(),+ ...pendingExtensionIds,+ ...validatedExtensionIds,+ ])++ for (const extensionId of transactionExtensionIds) {+ const extensionBackups = backupsByExtension.get(extensionId) ?? []+ const destDir = resolveExtensionPathWithinRoot(extensionsDir, extensionId)+ const destinationExists = existsSync(destDir)+ const destinationIncomplete = existsSync(join(destDir, EXT_INCOMPLETE_MARKER))+ const destinationPending = existsSync(join(destDir, EXT_REGISTRATION_PENDING_MARKER))++ // Destination commit markers are never trusted: they may have arrived in a+ // repository or persisted from an older implementation. Only root-level,+ // transaction-scoped validated state may authorize backup deletion.+ await rmWithRetry(join(destDir, EXT_VALIDATED_MARKER), 'ext-cleanup', log)++ if (validatedExtensionIds.has(extensionId) && destinationExists) {+ const cleaned = await cleanupValidatedExtensionBackups(extensionsDir, extensionId, log)+ if (!cleaned.ok) {+ log.warn(+ `[ext-cleanup] could not finish validated backup cleanup for "${extensionId}" `+ + `during ${cleaned.stage}: ${cleaned.error}`,+ )+ }+ continue+ }+ if (+ validatedExtensionIds.has(extensionId)+ && !destinationExists+ && extensionBackups.length === 0+ ) {+ await removeRegistrationState(extensionsDir, extensionId, log)+ continue+ }++ if (pendingExtensionIds.has(extensionId)) {+ if (extensionBackups.length > 0) {+ const backupPath = extensionBackups[0]+ const restored = await restoreExtensionBackup(destDir, backupPath, log)+ if (restored.ok) {+ await removeRegistrationState(extensionsDir, extensionId, log)+ log.info(`[ext-restore] restored "${extensionId}" from ${backupPath}`)+ }+ } else if (destinationIncomplete) {+ const removed = await rmWithRetry(destDir, 'ext-cleanup', log)+ if (removed.ok) await removeRegistrationState(extensionsDir, extensionId, log)+ } else if (destinationExists) {+ // Leave the root-level pending state in place. Discovery and the+ // Extensions UI both honor it without writing into a possibly linked+ // destination tree.+ continue+ } else {+ await removeRegistrationState(extensionsDir, extensionId, log)+ }+ continue+ }++ const destinationInterrupted = (+ destinationIncomplete+ || destinationPending+ )+ const action = incompleteInstallRecoveryAction({+ destinationExists,+ destinationIncomplete: destinationInterrupted,+ backupExists: extensionBackups.length > 0,+ })+ if (action === 'restore-backup') {+ const backupPath = extensionBackups[0]+ const restored = await restoreExtensionBackup(destDir, backupPath, log)+ if (restored.ok) {+ if (validatedExtensionIds.has(extensionId)) {+ await removeRegistrationState(extensionsDir, extensionId, log)+ }+ log.info(`[ext-restore] restored "${extensionId}" from ${backupPath}`)+ }+ continue+ }++ // Complete destination + unmarked backup: preserve the rollback copy. Its+ // registration state is unknown, so deleting or restoring would both be+ // destructive guesses.+ }++ // A fresh install has no backup. If it died while marked incomplete, there+ // is no valid extension to load or restore, so remove only that orphan.+ for (const name of names) {+ if (isInternalExtensionDirName(name) || extensionIdsWithBackups.has(name)) continue+ // Corrupted/manual folders may not satisfy the extension-id pattern. They+ // are still safe to reconcile when their literal directory entry remains+ // confined to extensionsDir (same rule used by uninstall).+ const destDir = resolvePathWithinRoot(extensionsDir, name)+ const destinationExists = existsSync(destDir)+ const destinationIncomplete = existsSync(join(destDir, EXT_INCOMPLETE_MARKER))+ const destinationRegistrationPending = existsSync(+ join(destDir, EXT_REGISTRATION_PENDING_MARKER),+ )+ const action = incompleteInstallRecoveryAction({+ destinationExists,+ destinationIncomplete,+ backupExists: false,+ })+ if (action === 'remove-incomplete') {+ await rmWithRetry(destDir, 'ext-cleanup', log)+ continue+ }++ // A pending destination without a rollback copy cannot be proven valid or+ // safely discarded. Leave it quarantined for Models → Repair; both the+ // Electron list and Python registry honor this marker.+ if (destinationRegistrationPending) continue++ const staleValidatedMarker = join(destDir, EXT_VALIDATED_MARKER)+ if (existsSync(staleValidatedMarker)) {+ await rmWithRetry(staleValidatedMarker, 'ext-cleanup', log)+ }+ }+}diff --git a/apps/forge-desktop/electron/main/extension-install-utils.test.mjs b/apps/forge-desktop/electron/main/extension-install-utils.test.mjsnew file mode 100644index 000000000..ec192d713--- /dev/null+++ b/apps/forge-desktop/electron/main/extension-install-utils.test.mjs@@ -0,0 +1,509 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-ext-test-')), 'extension-install-utils.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('electron/main/extension-install-utils.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++test('validateInstallManifest accepts legacy flat model manifests', () => {+ const mod = loadModule()++ const validated = mod.validateInstallManifest(+ { id: 'legacy-model', generator_class: 'Generator' },+ {+ hasEntryFile: () => false,+ hasGeneratorFile: () => true,+ },+ 'repository',+ )++ assert.equal(validated.id, 'legacy-model')+ assert.equal(validated.isProcess, false)+ assert.equal(validated.hasNodes, false)+})++test('validateInstallManifest still rejects missing process entry files', () => {+ const mod = loadModule()++ assert.throws(+ () => mod.validateInstallManifest(+ { id: 'proc', type: 'process', entry: 'processor.py' },+ {+ hasEntryFile: () => false,+ hasGeneratorFile: () => false,+ },+ 'selected folder',+ ),+ /entry file "processor\.py" missing from selected folder/,+ )+})++test('validateInstallManifest accepts multi-source nodes and preserves legacy shapes', () => {+ const mod = loadModule()+ assert.doesNotThrow(() => mod.validateInstallManifest({+ id: 'multi-model',+ generator_class: 'Generator',+ nodes: [{+ id: 'generate',+ model_sources: [+ {+ id: 'primary', provider: 'huggingface', repo_id: 'org/main',+ destination: '.', checks: ['pipeline.json'],+ },+ {+ id: 'encoder', provider: 'huggingface', repo_id: 'org/encoder',+ destination: 'auxiliary/encoder', checks: ['model.safetensors'],+ },+ ],+ }],+ }, { hasEntryFile: () => false, hasGeneratorFile: () => true }, 'repository'))++ assert.doesNotThrow(() => mod.validateInstallManifest({+ id: 'legacy',+ generator_class: 'Generator',+ nodes: [{+ id: 'projection',+ hf_repo: 'org/legacy',+ download_check: '../generate/model.safetensors',+ hf_skip_prefixes: ['weights/**'],+ }],+ }, { hasEntryFile: () => false, hasGeneratorFile: () => true }, 'repository'))++ // Nodes that do not opt into managed sources keep the pre-existing validation path.+ assert.doesNotThrow(() => mod.validateInstallManifest({+ id: 'legacy-unmanaged',+ generator_class: 'Generator',+ nodes: [{ id: 'legacy node' }],+ }, { hasEntryFile: () => false, hasGeneratorFile: () => true }, 'repository'))+})++test('validateInstallManifest accepts scene IO without rejecting third-party artifact kinds', () => {+ const mod = loadModule()+ const files = { hasEntryFile: () => false, hasGeneratorFile: () => true }+ assert.doesNotThrow(() => mod.validateInstallManifest({+ id: 'scene-model', generator_class: 'Generator',+ nodes: [{ id: 'normalize', input: 'scene', output: 'scene' }],+ }, files, 'repository'))+ for (const input of ['capture', 'video']) {+ assert.doesNotThrow(() => mod.validateInstallManifest({+ id: 'future-model', generator_class: 'Generator',+ nodes: [{ id: 'future', input, output: 'scene' }],+ }, files, 'repository'))+ }+})++test('scene is model-only, single-input, while image-multi to scene stays valid', () => {+ const mod = loadModule()+ const modelFiles = { hasEntryFile: () => false, hasGeneratorFile: () => true }+ const processFiles = { hasEntryFile: () => true, hasGeneratorFile: () => false }+ for (const node of [+ { id: 'mixed', input: 'scene', inputs: ['scene', 'text'], output: 'mesh' },+ { id: 'duplicate', input: 'scene', inputs: ['scene', 'scene'], output: 'mesh' },+ { id: 'hidden', input: 'image', inputs: ['scene'], output: 'mesh' },+ ]) {+ assert.throws(() => mod.validateInstallManifest({ id: 'bad', generator_class: 'Generator', nodes: [node] }, modelFiles, 'repository'), /scene.*single|single.*scene/i)+ }+ for (const node of [+ { id: 'input', input: 'scene', output: 'mesh' },+ { id: 'output', input: 'image', output: 'scene' },+ ]) {+ assert.throws(() => mod.validateInstallManifest({ id: 'proc', type: 'process', entry: 'processor.js', nodes: [node] }, processFiles, 'repository'), /scene.*model|model.*scene/i)+ }+ assert.doesNotThrow(() => mod.validateInstallManifest({+ id: 'images-to-scene', generator_class: 'Generator',+ nodes: [{ id: 'prepare', input: 'image', inputs: ['image', 'image'], output: 'scene' }],+ }, modelFiles, 'repository'))+ for (const output of ['scene', 'mesh']) {+ assert.doesNotThrow(() => mod.validateInstallManifest({+ id: `scene-to-${output}`, generator_class: 'Generator',+ nodes: [{ id: 'generate', input: 'scene', output }],+ }, modelFiles, 'repository'))+ }+})++test('validateInstallManifest rejects malformed or process model_sources', () => {+ const mod = loadModule()+ const source = {+ id: 'weights', provider: 'huggingface', repo_id: 'org/model',+ destination: '../outside', checks: ['model.safetensors'],+ }+ assert.throws(() => mod.validateInstallManifest({+ id: 'unsafe', generator_class: 'Generator',+ nodes: [{ id: 'generate', model_sources: [source] }],+ }, { hasEntryFile: () => false, hasGeneratorFile: () => true }, 'repository'), /destination/i)++ assert.throws(() => mod.validateInstallManifest({+ id: 'process', type: 'process', entry: 'processor.js',+ nodes: [{ id: 'run', model_sources: [{ ...source, destination: '.' }] }],+ }, { hasEntryFile: () => true, hasGeneratorFile: () => false }, 'repository'), /only for model nodes/i)+})++test('validateInstallManifest accepts shared groups with private sources', () => {+ const mod = loadModule()+ assert.doesNotThrow(() => mod.validateInstallManifest({+ id: 'shared-model',+ generator_class: 'Generator',+ weight_groups: [{+ id: 'base',+ model_sources: [{+ id: 'base', provider: 'huggingface', repo_id: 'org/base',+ destination: '.', checks: ['base.bin'],+ }],+ }],+ nodes: [+ { id: 'base-node', weight_groups: ['base'] },+ {+ id: 'adapter-node',+ weight_groups: ['base'],+ model_sources: [{+ id: 'adapter', provider: 'huggingface', repo_id: 'org/adapter',+ destination: '.', checks: ['adapter.bin'],+ }],+ },+ ],+ }, { hasEntryFile: () => false, hasGeneratorFile: () => true }, 'repository'))+})++test('validateInstallManifest rejects unsafe shared-weight contracts', () => {+ const mod = loadModule()+ const group = {+ id: 'base',+ model_sources: [{+ id: 'base', provider: 'huggingface', repo_id: 'org/base',+ destination: '.', checks: ['base.bin'],+ }],+ }+ const files = { hasEntryFile: () => true, hasGeneratorFile: () => true }+ assert.throws(() => mod.validateInstallManifest({+ id: 'unknown', generator_class: 'Generator',+ weight_groups: [group], nodes: [{ id: 'generate', weight_groups: ['missing'] }],+ }, files, 'repository'), /unknown weight group/i)+ assert.throws(() => mod.validateInstallManifest({+ id: 'reserved', generator_class: 'Generator',+ weight_groups: [group], nodes: [{ id: '_shared', weight_groups: ['base'] }],+ }, files, 'repository'), /reserved/i)+ assert.throws(() => mod.validateInstallManifest({+ id: 'process', type: 'process', entry: 'processor.py', weight_groups: [group],+ nodes: [{ id: 'run' }],+ }, files, 'repository'), /only for model extensions/i)+})++test('python process setup failures are treated as fatal', () => {+ const mod = loadModule()++ assert.equal(mod.isSetupFailureFatal({ isProcess: true, isPythonProcess: true }), true)+ assert.equal(mod.isSetupFailureFatal({ isProcess: true, isPythonProcess: false }), false)+ assert.equal(mod.isSetupFailureFatal({ isProcess: false, isPythonProcess: false }), true)+})++test('extension updates reject model/process type changes that would leave stale registration', () => {+ const mod = loadModule()++ assert.doesNotThrow(() => mod.assertCompatibleExtensionUpdateType(+ { id: 'pixal3d' },+ { id: 'pixal3d', type: 'model' },+ ))+ assert.doesNotThrow(() => mod.assertCompatibleExtensionUpdateType(+ { id: 'mesh-tool', type: 'process' },+ { id: 'mesh-tool', type: 'process' },+ ))+ assert.throws(+ () => mod.assertCompatibleExtensionUpdateType(+ { id: 'pixal3d', type: 'model' },+ { id: 'pixal3d', type: 'process' },+ ),+ /Uninstall the existing extension first/,+ )+})++test('existing extension replacement fails closed on unreadable or invalid manifests', () => {+ const mod = loadModule()+ const nextManifest = {+ id: 'pixal3d',+ type: 'model',+ generator_class: 'Generator',+ }+ const files = {+ hasEntryFile: () => false,+ hasGeneratorFile: () => true,+ }++ assert.throws(+ () => mod.validateExistingExtensionReplacement(+ '{broken json',+ nextManifest,+ files,+ 'existing extension folder',+ ),+ /manifest\.json is unreadable or invalid.*Uninstall it first/,+ )+ assert.throws(+ () => mod.validateExistingExtensionReplacement(+ JSON.stringify({ id: 'pixal3d', type: 'model' }),+ nextManifest,+ { ...files, hasGeneratorFile: () => false },+ 'existing extension folder',+ ),+ /referenced runtime files are invalid.*Uninstall it first.*generator\.py missing/,+ )+ assert.throws(+ () => mod.validateExistingExtensionReplacement(+ JSON.stringify({+ id: 'another-extension',+ type: 'model',+ generator_class: 'Generator',+ }),+ nextManifest,+ files,+ 'existing extension folder',+ ),+ /existing manifest identifies "another-extension".*Uninstall it first/,+ )+})++test('existing extension replacement accepts a validated type-compatible manifest', () => {+ const mod = loadModule()++ assert.deepEqual(+ mod.validateExistingExtensionReplacement(+ JSON.stringify({+ id: 'pixal3d',+ type: 'model',+ generator_class: 'OldGenerator',+ }),+ {+ id: 'pixal3d',+ type: 'model',+ generator_class: 'NewGenerator',+ },+ {+ hasEntryFile: () => false,+ hasGeneratorFile: () => true,+ },+ 'existing extension folder',+ ),+ {+ id: 'pixal3d',+ isProcess: false,+ isPythonProcess: false,+ entryFile: 'processor.js',+ hasNodes: false,+ },+ )+})++test('interrupted list entries preserve safe manifest metadata while becoming corrupted', () => {+ const mod = loadModule()+ const extension = {+ type: 'process',+ id: 'mesh-tool',+ name: 'Mesh Tool',+ entry: 'processor.js',+ nodes: [{ id: 'simplify' }],+ }++ assert.deepEqual(+ mod.markExtensionInstallationInterrupted(extension, true),+ {+ ...extension,+ corrupted: true,+ manifestError: 'incomplete',+ },+ )+ assert.equal(mod.markExtensionInstallationInterrupted(extension, false), extension)+})++test('expectedModelIds derives composite IDs and preserves legacy flat IDs', () => {+ const mod = loadModule()++ assert.deepEqual(+ mod.expectedModelIds({+ id: 'pixal3d',+ type: 'model',+ nodes: [{ id: 'generate' }, { id: 'preview' }, { id: 'generate' }],+ }),+ ['pixal3d/generate', 'pixal3d/preview'],+ )+ assert.deepEqual(mod.expectedModelIds({ id: 'legacy-model' }), ['legacy-model'])+ assert.deepEqual(+ mod.expectedModelIds({ id: 'mesh-process', type: 'process', nodes: [{ id: 'run' }] }),+ [],+ )+})++test('validateExtensionReloadPayload accepts a complete compatible response', () => {+ const mod = loadModule()+ const payload = {+ reloaded: true,+ models: ['other/generate', 'pixal3d/generate'],+ errors: { 'other/broken': 'unrelated failure' },+ }++ assert.deepEqual(+ mod.validateExtensionReloadPayload(payload, 'pixal3d', ['pixal3d/generate']),+ payload,+ )+})++test('validateExtensionReloadPayload rejects missing expected model IDs', () => {+ const mod = loadModule()++ assert.throws(+ () => mod.validateExtensionReloadPayload(+ { reloaded: true, models: ['other/generate'], errors: {} },+ 'pixal3d',+ ['pixal3d/generate'],+ ),+ /missing model ID pixal3d\/generate/,+ )+})++test('validateExtensionReloadPayload rejects extension and node errors', () => {+ const mod = loadModule()++ assert.throws(+ () => mod.validateExtensionReloadPayload(+ { reloaded: true, models: [], errors: { pixal3d: 'manifest invalid' } },+ 'pixal3d',+ ['pixal3d/generate'],+ ),+ /pixal3d: manifest invalid/,+ )+ assert.throws(+ () => mod.validateExtensionReloadPayload(+ { reloaded: true, models: [], errors: { 'pixal3d/generate': 'venv not found' } },+ 'pixal3d',+ ['pixal3d/generate'],+ ),+ /pixal3d\/generate: venv not found/,+ )+})++test('validateExtensionReloadPayload rejects malformed responses', () => {+ const mod = loadModule()+ const malformed = [+ null,+ {},+ { reloaded: false, models: [], errors: {} },+ { reloaded: true, models: 'pixal3d/generate', errors: {} },+ { reloaded: true, models: [], errors: [] },+ { reloaded: true, models: [], errors: { pixal3d: 123 } },+ ]++ for (const payload of malformed) {+ assert.throws(+ () => mod.validateExtensionReloadPayload(payload, 'pixal3d', ['pixal3d/generate']),+ /malformed response/,+ )+ }+})++test('validateExtensionQuarantinePayload requires target model IDs to be absent', () => {+ const mod = loadModule()+ const quarantined = {+ reloaded: true,+ models: ['other/generate'],+ errors: { 'pixal3d/generate': 'interrupted runtime registration' },+ }++ assert.deepEqual(+ mod.validateExtensionQuarantinePayload(+ quarantined,+ 'pixal3d',+ ['pixal3d/generate'],+ ),+ quarantined,+ )+ assert.throws(+ () => mod.validateExtensionQuarantinePayload(+ {+ reloaded: true,+ models: ['pixal3d/generate'],+ errors: {},+ },+ 'pixal3d',+ ['pixal3d/generate'],+ ),+ /Runtime quarantine failed.*pixal3d\/generate/,+ )+})++test('incompleteInstallRecoveryAction chooses restore, removal, or no-op', () => {+ const mod = loadModule()++ assert.equal(mod.incompleteInstallRecoveryAction({+ destinationExists: true,+ destinationIncomplete: true,+ backupExists: true,+ }), 'restore-backup')+ assert.equal(mod.incompleteInstallRecoveryAction({+ destinationExists: true,+ destinationIncomplete: true,+ backupExists: false,+ }), 'remove-incomplete')+ assert.equal(mod.incompleteInstallRecoveryAction({+ destinationExists: false,+ destinationIncomplete: false,+ backupExists: true,+ }), 'restore-backup')+ assert.equal(mod.incompleteInstallRecoveryAction({+ destinationExists: true,+ destinationIncomplete: false,+ backupExists: true,+ }), 'none')+})++test('managed model node ids reject portable aliases before installation', () => {+ const { validateInstallManifest } = loadModule()+ const opts = { hasGeneratorFile: () => true, hasEntryFile: () => true }+ for (const ids of [['Fast', 'fast'], ['fast', 'fast']]) {+ const manifest = {+ id: 'demo', type: 'model', generator_class: 'Generator',+ weight_groups: [{ id: 'base', model_sources: [{ id: 'main', provider: 'huggingface', repo_id: 'org/base', destination: '.', checks: ['weights.bin'] }] }],+ nodes: ids.map((id) => ({ id, weight_groups: ['base'] })),+ }+ assert.throws(() => validateInstallManifest(manifest, opts, 'test'), /portable-unique/)+ }+})++test('validateInstallManifest validates weight variants and keeps them off process nodes', () => {+ const mod = loadModule()+ const files = { hasEntryFile: () => true, hasGeneratorFile: () => true }+ const weightVariants = {+ param: 'quant',+ options: [{ id: 'Q4', include_prefixes: ['dit/model_Q4.gguf'], checks: ['dit/model_Q4.gguf'] }],+ }+ const paramsSchema = [{ id: 'quant', type: 'select', options: [{ value: 'Q4' }] }]+ assert.doesNotThrow(() => mod.validateInstallManifest({+ id: 'quantized', generator_class: 'Generator', params_schema: paramsSchema,+ nodes: [{ id: 'generate', hf_repo: 'org/model', weight_variants: weightVariants }],+ }, files, 'repository'))+ assert.throws(() => mod.validateInstallManifest({+ id: 'quantized', generator_class: 'Generator',+ nodes: [{ id: 'generate', hf_repo: 'org/model', weight_variants: weightVariants }],+ }, files, 'repository'), /must name a params_schema entry/)+ assert.throws(() => mod.validateInstallManifest({+ id: 'quantized', generator_class: 'Generator', params_schema: paramsSchema,+ nodes: [{ id: 'generate', weight_variants: weightVariants }],+ }, files, 'repository'), /requires hf_repo/)+ assert.throws(() => mod.validateInstallManifest({+ id: 'proc', type: 'process', entry: 'processor.js',+ nodes: [{ id: 'run', hf_repo: 'org/model', weight_variants: weightVariants }],+ }, files, 'repository'), /weight_variants is supported only for model nodes/)+})+diff --git a/apps/forge-desktop/electron/main/extension-install-utils.ts b/apps/forge-desktop/electron/main/extension-install-utils.tsnew file mode 100644index 000000000..2677f1ec5--- /dev/null+++ b/apps/forge-desktop/electron/main/extension-install-utils.ts@@ -0,0 +1,319 @@+import {+ normalizeModelSources,+ normalizeWeightGroupReferences,+ normalizeWeightGroups,+ normalizeWeightVariants,+ validateModelNodeIds,+ safeModelSourceId,+ type ModelWeightNode,+ type WeightVariantNode,+} from './model-sources'++export interface InstallManifest {+ id?: string+ type?: 'model' | 'process'+ entry?: string+ generator_class?: string+ model_sources?: unknown+ params_schema?: unknown+ weight_groups?: unknown+ nodes?: Array<{+ id?: string+ input?: unknown+ inputs?: unknown+ output?: unknown+ hf_repo?: unknown+ model_sources?: unknown+ weight_groups?: unknown+ weight_variants?: unknown+ } & ModelWeightNode & WeightVariantNode>+}++export interface ValidatedInstallManifest {+ id: string+ isProcess: boolean+ isPythonProcess: boolean+ entryFile: string+ hasNodes: boolean+}++export interface ExtensionReloadPayload {+ reloaded: true+ models: string[]+ errors: Record<string, string>+}++export function assertSupportedSceneNodeShape(+ kind: 'model' | 'process',+ node: { id?: string; input?: unknown; inputs?: unknown; output?: unknown },+ declaredInputs: unknown[],+ output: unknown,+): void {+ const usesSceneInput = declaredInputs.includes('scene')+ if (kind === 'process' && (usesSceneInput || output === 'scene')) {+ throw new Error('manifest.json: scene input and output are supported only for model nodes')+ }+ if (kind === 'model' && usesSceneInput && (node.inputs !== undefined || node.input !== 'scene')) {+ throw new Error(`manifest.json: ${node.id ?? 'node'} must declare scene as its single input field`)+ }+}++export type IncompleteInstallRecoveryAction =+ | 'none'+ | 'remove-incomplete'+ | 'restore-backup'++export function validateInstallManifest(+ manifest: InstallManifest,+ opts: {+ hasEntryFile: (entryFile: string) => boolean+ hasGeneratorFile: () => boolean+ },+ sourceLabel: string,+): ValidatedInstallManifest {+ if (!manifest.id) throw new Error('manifest.json: required field "id" missing')++ const isProcess = manifest.type === 'process'+ const entryFile = manifest.entry ?? 'processor.js'+ const nodes = Array.isArray(manifest.nodes) ? manifest.nodes.filter((node) => node?.id) : []+ if (manifest.model_sources !== undefined) {+ throw new Error('manifest.json: model_sources must be declared on a model node')+ }+ if (isProcess && manifest.weight_groups !== undefined) {+ throw new Error('manifest.json: weight_groups is supported only for model extensions')+ }+ const weightGroups = normalizeWeightGroups(manifest)+ if (weightGroups || nodes.some((node) => node.model_sources !== undefined || node.weight_groups !== undefined)) {+ validateModelNodeIds(manifest.nodes ?? [])+ }+ for (const node of Array.isArray(manifest.nodes) ? manifest.nodes : []) {+ const declaredInputs = Array.isArray(node.inputs) ? node.inputs : [node.input ?? 'image']+ const output = node.output ?? 'mesh'+ assertSupportedSceneNodeShape(isProcess ? 'process' : 'model', node, declaredInputs, output)+ const usesSharedWeights = weightGroups !== undefined || node.weight_groups !== undefined+ if (usesSharedWeights && typeof node.id === 'string' && node.id.toLowerCase() === '_shared') {+ throw new Error('manifest.json: model node id "_shared" is reserved')+ }+ if (isProcess && node.weight_variants !== undefined) {+ throw new Error('manifest.json: weight_variants is supported only for model nodes')+ }+ if (isProcess && (node.model_sources !== undefined || node.weight_groups !== undefined)) {+ throw new Error('manifest.json: model_sources and weight_groups are supported only for model nodes')+ }+ if (!usesSharedWeights && node.model_sources === undefined && node.weight_variants === undefined) continue+ const nodeId = safeModelSourceId(node.id, 'model node id')+ if (node.model_sources !== undefined) normalizeModelSources(node)+ // Before the weight_groups/hf_repo check, so a variants + groups node gets+ // the explicit "cannot be combined" error.+ normalizeWeightVariants(node, node.params_schema ?? manifest.params_schema)+ normalizeWeightGroupReferences(node, weightGroups, `nodes[${nodeId}].weight_groups`)+ if (node.weight_groups !== undefined && node.hf_repo !== undefined) {+ throw new Error(+ `manifest.json: model node "${nodeId}" must use model_sources for private weights when weight_groups are declared`,+ )+ }+ }++ if (isProcess) {+ if (!opts.hasEntryFile(entryFile)) {+ throw new Error(`manifest.json: entry file "${entryFile}" missing from ${sourceLabel}`)+ }+ } else {+ if (!opts.hasGeneratorFile()) throw new Error(`generator.py missing from ${sourceLabel}`)+ if (!manifest.generator_class) throw new Error('manifest.json: required field "generator_class" missing')+ }++ return {+ id: manifest.id,+ isProcess,+ isPythonProcess: isProcess && entryFile.endsWith('.py'),+ entryFile,+ hasNodes: nodes.length > 0,+ }+}++export function isSetupFailureFatal(kind: {+ isProcess: boolean+ isPythonProcess: boolean+}): boolean {+ return !kind.isProcess || kind.isPythonProcess+}++export function assertCompatibleExtensionUpdateType(+ currentManifest: InstallManifest,+ nextManifest: InstallManifest,+): void {+ const currentType = currentManifest.type === 'process' ? 'process' : 'model'+ const nextType = nextManifest.type === 'process' ? 'process' : 'model'+ if (currentType !== nextType) {+ throw new Error(+ `Cannot update an extension from ${currentType} to ${nextType}. `+ + 'Uninstall the existing extension first, then install the new type.',+ )+ }+}++export function validateExistingExtensionReplacement(+ currentManifestJson: string,+ nextManifest: InstallManifest,+ opts: {+ hasEntryFile: (entryFile: string) => boolean+ hasGeneratorFile: () => boolean+ },+ sourceLabel: string,+): ValidatedInstallManifest {+ let currentManifest: unknown+ try {+ currentManifest = JSON.parse(currentManifestJson)+ } catch {+ throw new Error(+ 'Cannot safely replace the existing extension because its manifest.json '+ + 'is unreadable or invalid. Uninstall it first.',+ )+ }++ if (+ typeof currentManifest !== 'object'+ || currentManifest === null+ || Array.isArray(currentManifest)+ ) {+ throw new Error(+ 'Cannot safely replace the existing extension because its manifest.json '+ + 'is unreadable or invalid. Uninstall it first.',+ )+ }++ let validated: ValidatedInstallManifest+ try {+ validated = validateInstallManifest(+ currentManifest as InstallManifest,+ opts,+ sourceLabel,+ )+ } catch (error) {+ throw new Error(+ 'Cannot safely replace the existing extension because its manifest.json '+ + `or referenced runtime files are invalid. Uninstall it first. ${String(error)}`,+ )+ }++ if (validated.id !== nextManifest.id) {+ throw new Error(+ `Cannot safely replace extension "${nextManifest.id ?? ''}" because the existing `+ + `manifest identifies "${validated.id}". Uninstall it first.`,+ )+ }+ assertCompatibleExtensionUpdateType(currentManifest as InstallManifest, nextManifest)+ return validated+}++export function markExtensionInstallationInterrupted<T extends object>(+ extension: T,+ interrupted: boolean,+): T | (T & { corrupted: true; manifestError: 'incomplete' }) {+ if (!interrupted) return extension+ return {+ ...extension,+ corrupted: true,+ manifestError: 'incomplete',+ }+}++export function expectedModelIds(manifest: InstallManifest): string[] {+ if (manifest.type === 'process') return []+ if (typeof manifest.id !== 'string' || !manifest.id) {+ throw new Error('manifest.json: required field "id" missing')+ }++ const nodeIds = Array.isArray(manifest.nodes)+ ? manifest.nodes+ .map((node) => node?.id)+ .filter((id): id is string => typeof id === 'string' && id.length > 0)+ : []++ return nodeIds.length > 0+ ? [...new Set(nodeIds.map((nodeId) => `${manifest.id}/${nodeId}`))]+ : [manifest.id]+}++function isStringRecord(value: unknown): value is Record<string, string> {+ return typeof value === 'object'+ && value !== null+ && !Array.isArray(value)+ && Object.values(value).every((entry) => typeof entry === 'string')+}++function parseExtensionReloadPayload(payload: unknown): ExtensionReloadPayload {+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {+ throw new Error('Extension reload returned a malformed response')+ }++ const candidate = payload as Record<string, unknown>+ if (candidate.reloaded !== true+ || !Array.isArray(candidate.models)+ || !candidate.models.every((modelId) => typeof modelId === 'string')+ || !isStringRecord(candidate.errors)) {+ throw new Error('Extension reload returned a malformed response')+ }++ return {+ reloaded: true,+ models: candidate.models as string[],+ errors: candidate.errors,+ }+}++export function validateExtensionReloadPayload(+ payload: unknown,+ extensionId: string,+ expectedIds: string[],+): ExtensionReloadPayload {+ const parsed = parseExtensionReloadPayload(payload)+ const matchingErrors = Object.entries(parsed.errors).filter(([key]) =>+ key === extensionId || key.startsWith(`${extensionId}/`),+ )+ if (matchingErrors.length > 0) {+ const detail = matchingErrors.map(([key, message]) => `${key}: ${message}`).join('; ')+ throw new Error(`Runtime registration failed for extension "${extensionId}": ${detail}`)+ }++ const registered = new Set(parsed.models)+ const missing = expectedIds.filter((modelId) => !registered.has(modelId))+ if (missing.length > 0) {+ throw new Error(+ `Runtime registration failed for extension "${extensionId}": `+ + `missing model ${missing.length === 1 ? 'ID' : 'IDs'} ${missing.join(', ')}`,+ )+ }++ return parsed+}++export function validateExtensionQuarantinePayload(+ payload: unknown,+ extensionId: string,+ forbiddenIds: string[],+): ExtensionReloadPayload {+ const parsed = parseExtensionReloadPayload(payload)+ const registered = new Set(parsed.models)+ const stillRegistered = forbiddenIds.filter((modelId) => registered.has(modelId))+ if (stillRegistered.length > 0) {+ throw new Error(+ `Runtime quarantine failed for extension "${extensionId}": `+ + `model ${stillRegistered.length === 1 ? 'ID is' : 'IDs are'} still registered `+ + stillRegistered.join(', '),+ )+ }+ return parsed+}++export function incompleteInstallRecoveryAction(state: {+ destinationExists: boolean+ destinationIncomplete: boolean+ backupExists: boolean+}): IncompleteInstallRecoveryAction {+ if (!state.destinationExists || state.destinationIncomplete) {+ return state.backupExists ? 'restore-backup' : state.destinationIncomplete ? 'remove-incomplete' : 'none'+ }+ return 'none'+}diff --git a/apps/forge-desktop/electron/main/extension-path-guard.test.ts b/apps/forge-desktop/electron/main/extension-path-guard.test.tsnew file mode 100644index 000000000..58bcdafb1--- /dev/null+++ b/apps/forge-desktop/electron/main/extension-path-guard.test.ts@@ -0,0 +1,75 @@+import assert from 'node:assert/strict'+import path from 'node:path'+import test from 'node:test'++async function loadGuard() {+ return import(new URL('./extension-path-guard.ts', import.meta.url).href)+}++test('assertSafeExtensionId accepts conservative extension ids', async () => {+ const { assertSafeExtensionId } = await loadGuard()+ assert.equal(assertSafeExtensionId('mesh-process'), 'mesh-process')+ assert.equal(assertSafeExtensionId('image_model.v2'), 'image_model.v2')+ assert.equal(assertSafeExtensionId('kimodo-soma-rp'), 'kimodo-soma-rp')+})++test('assertSafeExtensionId rejects empty, traversal and absolute ids', async () => {+ const { assertSafeExtensionId } = await loadGuard()+ assert.throws(() => assertSafeExtensionId(''), /must not be empty/i)+ assert.throws(() => assertSafeExtensionId('.'), /is invalid/i)+ assert.throws(() => assertSafeExtensionId('..'), /is invalid/i)+ assert.throws(() => assertSafeExtensionId('../escape'), /path separators/i)+ assert.throws(() => assertSafeExtensionId('..\\escape'), /path separators/i)+ assert.throws(() => assertSafeExtensionId('/abs/path'), /absolute path|path separators/i)+})++test('assertSafeExtensionId rejects uppercase and unsupported characters', async () => {+ const { assertSafeExtensionId } = await loadGuard()+ assert.throws(() => assertSafeExtensionId('Mesh-Process'), /must match/i)+ assert.throws(() => assertSafeExtensionId('bad id'), /must match/i)+ assert.throws(() => assertSafeExtensionId('bad:id'), /must match/i)+})++test('resolveExtensionPathWithinRoot confines paths to root', async () => {+ const { resolveExtensionPathWithinRoot } = await loadGuard()+ const root = path.join('/tmp', 'extensions-root')+ assert.equal(resolveExtensionPathWithinRoot(root, 'mesh-process'), path.resolve(root, 'mesh-process'))+ assert.throws(() => resolveExtensionPathWithinRoot(root, '../escape'), /path separators/i)+})++test('resolvePathWithinRoot rejects canonical escapes', async () => {+ const { resolvePathWithinRoot } = await loadGuard()+ const root = path.join('/tmp', 'extensions-root')+ assert.equal(resolvePathWithinRoot(root, '.modly-backup-safe-123'), path.resolve(root, '.modly-backup-safe-123'))+ assert.throws(() => resolvePathWithinRoot(root, '../escape'), /escapes root/i)+})++test('resolvePathWithinRoot rejects leaves that resolve to the root itself', async () => {+ const { resolvePathWithinRoot } = await loadGuard()+ const root = path.join('/tmp', 'extensions-root')+ assert.throws(() => resolvePathWithinRoot(root, '.'), /escapes root/i)+ assert.throws(() => resolvePathWithinRoot(root, ''), /escapes root/i)+})++test('parseExtensionBackupName extracts ids with dashes and rejects foreign names', async () => {+ const { parseExtensionBackupName } = await loadGuard()+ assert.deepEqual(parseExtensionBackupName('.modly-backup-hunyuan3d-mini-1752580000000'), { extensionId: 'hunyuan3d-mini' })+ assert.deepEqual(parseExtensionBackupName('.modly-backup-x-1'), { extensionId: 'x' })+ assert.equal(parseExtensionBackupName('.modly-backup-noTimestamp'), null)+ assert.equal(parseExtensionBackupName('.modly-staging-x-1'), null)+ assert.equal(parseExtensionBackupName('regular-extension'), null)+})++test('buildExtensionBackupPath stays within root and rejects unsafe ids', async () => {+ const { buildExtensionBackupPath } = await loadGuard()+ const root = path.join('/tmp', 'extensions-root')+ assert.equal(buildExtensionBackupPath(root, 'mesh-process', '123'), path.resolve(root, '.modly-backup-mesh-process-123'))+ assert.throws(() => buildExtensionBackupPath(root, '../escape', '123'), /path separators/i)+})++test('buildExtensionStagingPath stays within root and rejects unsafe ids', async () => {+ const { buildExtensionStagingPath } = await loadGuard()+ const root = path.join('/tmp', 'extensions-root')+ assert.equal(buildExtensionStagingPath(root, 'mesh-process', '42'), path.resolve(root, '.modly-staging-mesh-process-42'))+ assert.throws(() => buildExtensionStagingPath(root, '../escape', '42'), /path separators/i)+})diff --git a/apps/forge-desktop/electron/main/extension-path-guard.ts b/apps/forge-desktop/electron/main/extension-path-guard.tsnew file mode 100644index 000000000..427b03e6c--- /dev/null+++ b/apps/forge-desktop/electron/main/extension-path-guard.ts@@ -0,0 +1,99 @@+import { isAbsolute, relative, resolve as resolvePath } from 'node:path'++const EXTENSION_ID_PATTERN = /^[a-z0-9][a-z0-9._-]*$/++export function assertSafeExtensionId(extensionId: unknown): string {+ if (typeof extensionId !== 'string') {+ throw new Error('Extension id must be a string')+ }++ const trimmed = extensionId.trim()+ if (!trimmed) {+ throw new Error('Extension id must not be empty')+ }++ if (trimmed === '.' || trimmed === '..') {+ throw new Error(`Extension id "${extensionId}" is invalid`)+ }++ if (isAbsolute(trimmed)) {+ throw new Error(`Extension id "${extensionId}" must not be an absolute path`)+ }++ if (trimmed.includes('/') || trimmed.includes('\\')) {+ throw new Error(`Extension id "${extensionId}" must not contain path separators`)+ }++ if (!EXTENSION_ID_PATTERN.test(trimmed)) {+ throw new Error(`Extension id "${extensionId}" must match ${EXTENSION_ID_PATTERN}`)+ }++ return trimmed+}++export function resolvePathWithinRoot(rootDir: string, unsafeLeaf: string): string {+ const resolvedRoot = resolvePath(rootDir)+ const resolvedCandidate = resolvePath(resolvedRoot, unsafeLeaf)+ const normalizedRelative = relative(resolvedRoot, resolvedCandidate).replace(/\\/g, '/')++ // An empty relative path means the leaf resolved to the root itself ('', '.')+ // — never a valid child, and catastrophic for deletion call sites.+ if (normalizedRelative === '' || normalizedRelative === '..' || normalizedRelative.startsWith('../') || isAbsolute(normalizedRelative)) {+ throw new Error(`Resolved path escapes root: ${unsafeLeaf}`)+ }++ return resolvedCandidate+}++export function resolveExtensionPathWithinRoot(rootDir: string, extensionId: unknown): string {+ return resolvePathWithinRoot(rootDir, assertSafeExtensionId(extensionId))+}++// ─── Internal (non-extension) dir names inside extensionsDir ─────────────────+// Extension ids can never start with a dot, so dot-prefixed names are reserved+// for install machinery: staging copies, backups of the previous version.+// Both the Electron and Python discovery sides must skip them.++export const EXT_BACKUP_PREFIX = '.modly-backup-'+export const EXT_STAGING_PREFIX = '.modly-staging-'+// Marker file inside an extension folder while its setup is still running —+// presence after a crash means the install never completed.+export const EXT_INCOMPLETE_MARKER = '.modly-incomplete'+// Reserved basename for registration-pending state. Active transactions append+// "-<extension-id>-<timestamp>" and live beside extension folders so linked+// source trees are never mutated.+export const EXT_REGISTRATION_PENDING_MARKER = '.modly-registration-pending'+// Reserved basename for the matching validated transaction commit marker.+export const EXT_VALIDATED_MARKER = '.modly-registration-validated'++export function isInternalExtensionDirName(name: string): boolean {+ return name.startsWith('.')+}++export function buildExtensionBackupPath(rootDir: string, extensionId: unknown, suffix: string): string {+ const safeId = assertSafeExtensionId(extensionId)+ return resolvePathWithinRoot(rootDir, `${EXT_BACKUP_PREFIX}${safeId}-${suffix}`)+}++// A backup dir is the previous version of an extension, parked during an+// install swap. Its name embeds the extension id: .modly-backup-<id>-<ts>.+// Ids may contain '-', so strip the numeric timestamp suffix, not a naive split.+export function parseExtensionBackupName(name: string): { extensionId: string } | null {+ if (!name.startsWith(EXT_BACKUP_PREFIX)) return null+ const rest = name.slice(EXT_BACKUP_PREFIX.length)+ const match = rest.match(/^(.+)-\d+$/)+ if (!match) return null+ try {+ return { extensionId: assertSafeExtensionId(match[1]) }+ } catch {+ return null+ }+}++// Staging dir lives next to the final location so activation is a same-volume+// atomic rename. Unique per attempt (suffix) so a new install can never merge+// into the leftovers of a previous one, and never races the startup purge.+export function buildExtensionStagingPath(rootDir: string, extensionId: unknown, suffix: string): string {+ const safeId = assertSafeExtensionId(extensionId)+ return resolvePathWithinRoot(rootDir, `${EXT_STAGING_PREFIX}${safeId}-${suffix}`)+}diff --git a/apps/forge-desktop/electron/main/gpu-detect.test.mjs b/apps/forge-desktop/electron/main/gpu-detect.test.mjsnew file mode 100644index 000000000..3746da5c0--- /dev/null+++ b/apps/forge-desktop/electron/main/gpu-detect.test.mjs@@ -0,0 +1,253 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-gpu-test-')), 'gpu-detect.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('electron/main/gpu-detect.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++const mod = loadModule()++// ─── KFD topology parsing ─────────────────────────────────────────────────────++test('formatGfxTarget decodes gfx_target_version across GPU generations', () => {+ // Encoding is major*10000 + minor*100 + step, minor and step read as hex+ // digits. 120000 is the value this machine's RX 9060 XT actually reports.+ assert.equal(mod.formatGfxTarget(120000), 'gfx1200') // Navi 44 / RX 9060 XT+ assert.equal(mod.formatGfxTarget(120001), 'gfx1201') // Navi 48+ assert.equal(mod.formatGfxTarget(110000), 'gfx1100') // Navi 31+ assert.equal(mod.formatGfxTarget(110002), 'gfx1102') // Navi 33+ assert.equal(mod.formatGfxTarget(100300), 'gfx1030') // Navi 21+ assert.equal(mod.formatGfxTarget(90402), 'gfx942') // MI300, hex step+ assert.equal(mod.formatGfxTarget(90010), 'gfx90a') // MI200, hex step+})++test('formatGfxTarget rejects the "no GPU" and malformed encodings', () => {+ assert.equal(mod.formatGfxTarget(0), null)+ assert.equal(mod.formatGfxTarget(-1), null)+ assert.equal(mod.formatGfxTarget(1.5), null)+})++test('parseKfdGfxTarget skips the CPU node and reads the first GPU', () => {+ // Verbatim shape of /sys/class/kfd/kfd/topology/nodes/*/properties+ const cpuNode = 'cpu_cores_count 32\nsimd_count 0\ngfx_target_version 0\n'+ const gpuNode = 'cpu_cores_count 0\nsimd_count 64\ngfx_target_version 120000\n'++ assert.equal(mod.parseKfdGfxTarget([cpuNode, gpuNode]), 'gfx1200')+})++test('parseKfdGfxTarget prefers the discrete GPU over an APU', () => {+ // Ryzen 7840 (gfx1103, 24 SIMDs) + RX 7900 XTX (gfx1100, 384 SIMDs): the APU+ // gets the lower node number, but gfx1103 has no published wheels — the card+ // with more SIMDs is the one the user bought for this.+ const cpuNode = 'cpu_cores_count 16\nsimd_count 0\ngfx_target_version 0\n'+ const apuNode = 'cpu_cores_count 0\nsimd_count 24\ngfx_target_version 110003\n'+ const dgpuNode = 'cpu_cores_count 0\nsimd_count 384\ngfx_target_version 110000\n'++ assert.equal(mod.parseKfdGfxTarget([cpuNode, apuNode, dgpuNode]), 'gfx1100')+ // Order must not matter+ assert.equal(mod.parseKfdGfxTarget([cpuNode, dgpuNode, apuNode]), 'gfx1100')+})++test('parseKfdGfxTarget returns null without a usable GPU node', () => {+ assert.equal(mod.parseKfdGfxTarget([]), null)+ assert.equal(mod.parseKfdGfxTarget(['simd_count 0\ngfx_target_version 0\n']), null)+ // A node advertising SIMDs but no compute target is not something we can target+ assert.equal(mod.parseKfdGfxTarget(['simd_count 64\ngfx_target_version 0\n']), null)+})++test('parseKfdGfxTarget does not confuse a key with its prefix', () => {+ // simd_count must not be satisfied by e.g. "max_simd_count"+ const node = 'max_simd_count 999\nsimd_count 64\ngfx_target_version 110002\n'+ assert.equal(mod.parseKfdGfxTarget([node]), 'gfx1102')+})++// ─── nvidia-smi parsing (non-regression) ──────────────────────────────────────++test('parseNvidiaSmi maps compute cap and driver version to CUDA version', () => {+ assert.deepEqual(mod.parseNvidiaSmi('8.6, 551.61\n'), { sm: 86, cudaVersion: 124 })+ assert.deepEqual(mod.parseNvidiaSmi('12.0, 572.16\n'), { sm: 120, cudaVersion: 128 })+ assert.deepEqual(mod.parseNvidiaSmi('6.1, 470.82\n'), { sm: 61, cudaVersion: 118 })+})++test('parseNvidiaSmi falls back to sm 86 on an unparseable compute cap', () => {+ assert.deepEqual(mod.parseNvidiaSmi('N/A, 551.61\n'), { sm: 86, cudaVersion: 124 })+})++test('parseNvidiaSmi returns null on empty output', () => {+ assert.equal(mod.parseNvidiaSmi(''), null)+ assert.equal(mod.parseNvidiaSmi(' \n'), null)+})++// ─── Windows adapter mapping ──────────────────────────────────────────────────++test('parseWindowsVideoControllers accepts both the object and array JSON shapes', () => {+ const single = mod.parseWindowsVideoControllers(+ '{"Name":"AMD Radeon RX 9060 XT","PNPDeviceID":"PCI\\\\VEN_1002&DEV_7590&SUBSYS_06391043&REV_C0\\\\4&1"}',+ )+ assert.deepEqual(single, [+ { name: 'AMD Radeon RX 9060 XT', pnpDeviceId: 'PCI\\VEN_1002&DEV_7590&SUBSYS_06391043&REV_C0\\4&1' },+ ])++ const many = mod.parseWindowsVideoControllers(+ '[{"Name":"A","PNPDeviceID":"PCI\\\\VEN_1002&DEV_7550"},{"Name":"B","PNPDeviceID":"PCI\\\\VEN_8086&DEV_1234"}]',+ )+ assert.equal(many.length, 2)+})++test('parseWindowsVideoControllers survives malformed PowerShell output', () => {+ assert.deepEqual(mod.parseWindowsVideoControllers('not json'), [])+ assert.deepEqual(mod.parseWindowsVideoControllers('{"Name":"No id"}'), [])+})++test('parseAmdPciDeviceId only matches AMD vendor ids', () => {+ assert.equal(mod.parseAmdPciDeviceId('PCI\\VEN_1002&DEV_7590&SUBSYS_0'), '7590')+ assert.equal(mod.parseAmdPciDeviceId('PCI\\VEN_10DE&DEV_2684'), null)+})++test('resolveWindowsGfxTarget maps device ids by silicon, not by marketing range', () => {+ const target = (deviceId) =>+ mod.resolveWindowsGfxTarget([{ name: 'x', pnpDeviceId: `PCI\\VEN_1002&DEV_${deviceId}` }]).gfxTarget++ assert.equal(target('7590'), 'gfx1200') // Navi 44+ assert.equal(target('7550'), 'gfx1201') // Navi 48+ assert.equal(target('744C'), 'gfx1100') // Navi 31, uppercase from WMI+ assert.equal(target('747e'), 'gfx1101') // Navi 32+ // 0x73f0 sells as "RX 7600M XT" but is Navi 33 — it must not land with its+ // 0x73xx RDNA2 neighbours.+ assert.equal(target('73f0'), 'gfx1102')+ assert.equal(target('73bf'), 'gfx1030') // Navi 21+})++test('resolveWindowsGfxTarget reports unmapped AMD cards instead of guessing', () => {+ const result = mod.resolveWindowsGfxTarget([+ { name: 'AMD Radeon RX 9999', pnpDeviceId: 'PCI\\VEN_1002&DEV_FFFF' },+ ])+ assert.equal(result.gfxTarget, null)+ assert.deepEqual(result.amdAdapters, ['AMD Radeon RX 9999'])+})++test('resolveWindowsGfxTarget ignores non-AMD adapters', () => {+ const result = mod.resolveWindowsGfxTarget([+ { name: 'NVIDIA RTX 4090', pnpDeviceId: 'PCI\\VEN_10DE&DEV_2684' },+ ])+ assert.equal(result.gfxTarget, null)+ assert.deepEqual(result.amdAdapters, [])+})++// ─── ROCm wheel source resolution ─────────────────────────────────────────────++test('resolveRocmTorchSpec uses the unpinned pytorch.org index on Linux', () => {+ const { indexUrl, specs } = mod.resolveRocmTorchSpec('linux', 'gfx1200', {})+ assert.equal(indexUrl, 'https://download.pytorch.org/whl/rocm7.2')+ assert.deepEqual(specs, ['torch', 'torchvision'])+})++test('resolveRocmTorchSpec uses AMD\'s index with a device extra on Windows', () => {+ // download.pytorch.org publishes no ROCm wheels for Windows at all.+ const { indexUrl, specs } = mod.resolveRocmTorchSpec('win32', 'gfx1200', {})+ assert.equal(indexUrl, 'https://repo.amd.com/rocm/whl-multi-arch/')+ assert.deepEqual(specs, [+ 'torch[device-gfx1200]==2.11.0+rocm7.14.0',+ 'torchvision[device-gfx1200]==0.26.0+rocm7.14.0',+ ])+})++test('resolveRocmTorchSpec honours MODLY_ROCM_INDEX and MODLY_ROCM_TORCH_SPEC', () => {+ const rolledBack = mod.resolveRocmTorchSpec('linux', 'gfx1200', {+ MODLY_ROCM_INDEX: 'https://download.pytorch.org/whl/rocm6.4',+ MODLY_ROCM_TORCH_SPEC: 'torch==2.8.0 torchvision==0.23.0',+ })+ assert.equal(rolledBack.indexUrl, 'https://download.pytorch.org/whl/rocm6.4')+ assert.deepEqual(rolledBack.specs, ['torch==2.8.0', 'torchvision==0.23.0'])+})++test('resolveRocmTorchSpec stays unpinned on Windows without a compute target', () => {+ // No target means no device extra to ask for; better an install that fails+ // loudly than one silently pinned to the wrong architecture.+ const { specs } = mod.resolveRocmTorchSpec('win32', null, {})+ assert.deepEqual(specs, ['torch', 'torchvision'])+})++test('torchFlavorFor maps accelerators to the setup.py argument', () => {+ assert.equal(mod.torchFlavorFor('rocm'), 'rocm')+ assert.equal(mod.torchFlavorFor('cuda'), 'cuda')+ assert.equal(mod.torchFlavorFor('cpu'), 'cpu')+ assert.equal(mod.torchFlavorFor('mps'), 'cpu')+})++// ─── Detection precedence ─────────────────────────────────────────────────────++test('detectGpuInfo keeps Apple Silicon on MPS', async () => {+ const info = await mod.detectGpuInfo({ env: {}, platform: 'darwin', arch: 'arm64' })+ assert.equal(info.accelerator, 'mps')+})++test('detectGpuInfo forced to rocm resolves wheels without probing hardware', async () => {+ const info = await mod.detectGpuInfo({+ env: { MODLY_TORCH_FLAVOR: 'rocm', MODLY_ROCM_GFX: 'gfx1201' },+ platform: 'linux',+ arch: 'x64',+ })+ assert.equal(info.accelerator, 'rocm')+ assert.equal(info.gfxTarget, 'gfx1201')+ assert.equal(info.torchIndexUrl, 'https://download.pytorch.org/whl/rocm7.2')+ // sm/cudaVersion stay at 0 so CUDA-era extensions take their most+ // conservative branch (and keep off rembg[gpu], which is CUDA-only).+ assert.equal(info.sm, 0)+ assert.equal(info.cudaVersion, 0)+})++test('detectGpuInfo forced to rocm overrides MPS on Apple Silicon', async () => {+ const info = await mod.detectGpuInfo({+ env: { MODLY_TORCH_FLAVOR: 'rocm', MODLY_ROCM_GFX: 'gfx1200' },+ platform: 'darwin',+ arch: 'arm64',+ })+ assert.equal(info.accelerator, 'rocm')+})++test('detectGpuInfo forced to cuda overrides MPS on Apple Silicon', async () => {+ // The override has to beat every probe, the darwin/arm64 default included.+ const info = await mod.detectGpuInfo({+ env: { MODLY_TORCH_FLAVOR: 'cuda' },+ platform: 'darwin',+ arch: 'arm64',+ })+ assert.equal(info.accelerator, 'cuda')+})++test('detectGpuInfo forced to cpu short-circuits everything', async () => {+ const info = await mod.detectGpuInfo({+ env: { MODLY_TORCH_FLAVOR: 'cpu', MODLY_ROCM_GFX: 'gfx1200' },+ platform: 'linux',+ arch: 'x64',+ })+ assert.deepEqual(info, { sm: 0, cudaVersion: 0, accelerator: 'cpu' })+})++test('detectGpuInfo falls back to CPU when forced to rocm on Windows with no target', async () => {+ const logs = []+ const info = await mod.detectGpuInfo({+ env: { MODLY_TORCH_FLAVOR: 'rocm' },+ platform: 'win32',+ arch: 'x64',+ onLog: (line) => logs.push(line),+ })+ assert.equal(info.accelerator, 'cpu')+ assert.ok(logs.some((l) => l.includes('MODLY_ROCM_GFX')))+})diff --git a/apps/forge-desktop/electron/main/gpu-detect.ts b/apps/forge-desktop/electron/main/gpu-detect.tsnew file mode 100644index 000000000..44ca4531d--- /dev/null+++ b/apps/forge-desktop/electron/main/gpu-detect.ts@@ -0,0 +1,407 @@+/**+ * GPU detection and PyTorch flavour resolution.+ *+ * Deliberately free of electron imports: the parsing and resolution helpers are+ * pure and get unit-tested by bundling this file directly (gpu-detect.test.mjs).+ *+ * Modly never installs PyTorch itself — each extension's setup.py does, from an+ * index it picks on its own. What we produce here is the information that lets+ * that choice land on the right wheels: the accelerator, and for AMD the ROCm+ * compute target plus the pip index/requirements the setup must end up using.+ */++import { spawn } from 'child_process'+import { existsSync, readdirSync, readFileSync } from 'fs'+import { join } from 'path'++export type Accelerator = 'cuda' | 'rocm' | 'mps' | 'cpu'+export type TorchFlavor = 'cuda' | 'rocm' | 'cpu'++export interface GpuInfo {+ sm: number+ cudaVersion: number+ accelerator: Accelerator+ /** ROCm compute target ("gfx1200"). Only set when accelerator is 'rocm'. */+ gfxTarget?: string+ /** pip --index-url the torch install has to come from (ROCm only). */+ torchIndexUrl?: string+ /** pip requirements replacing whatever torch pins an extension hardcodes. */+ torchSpecs?: string[]+}++// ─── ROCm wheel sources ───────────────────────────────────────────────────────+//+// Linux and Windows need different indexes. download.pytorch.org publishes no+// ROCm wheels for Windows at all, so Windows has to go through AMD's multi-arch+// index, where the compute target is selected by a pip extra+// (torch[device-gfx1200]) instead of by the index URL.++const ROCM_LINUX_INDEX = 'https://download.pytorch.org/whl/rocm7.2'+const ROCM_WINDOWS_INDEX = 'https://repo.amd.com/rocm/whl-multi-arch/'++// Pinned because AMD's index carries several ROCm builds side by side; this is+// the newest pair published for cp311 (Modly's embedded Python) on Windows.+const ROCM_WINDOWS_TORCH = '2.11.0+rocm7.14.0'+const ROCM_WINDOWS_TORCHVISION = '0.26.0+rocm7.14.0'++const KFD_TOPOLOGY_DIR = '/sys/class/kfd/kfd/topology/nodes'++/**+ * AMD PCI device id → ROCm compute target, for Windows where there is no KFD+ * topology to read. Keyed by silicon rather than by marketing name: 0x73f0 is+ * sold as an "RX 7600M XT" but is Navi 33, so it belongs with gfx1102, not with+ * its 0x73xx neighbours. Device ids come from the pci.ids database.+ */+const WINDOWS_PCI_GFX_TARGETS: Record<string, string> = {+ // Navi 21 (RDNA 2)+ '73a1': 'gfx1030', '73a2': 'gfx1030', '73a3': 'gfx1030', '73a5': 'gfx1030',+ '73ab': 'gfx1030', '73ae': 'gfx1030', '73af': 'gfx1030', '73bf': 'gfx1030',+ // Navi 22 (RDNA 2)+ '73c3': 'gfx1031', '73ce': 'gfx1031', '73df': 'gfx1031',+ // Navi 23 (RDNA 2)+ '73e0': 'gfx1032', '73e1': 'gfx1032', '73e3': 'gfx1032', '73ef': 'gfx1032',+ '73ff': 'gfx1032',+ // Navi 24 (RDNA 2)+ '7421': 'gfx1034', '7422': 'gfx1034', '7423': 'gfx1034', '7424': 'gfx1034',+ '743f': 'gfx1034',+ // Navi 31 (RDNA 3)+ '7448': 'gfx1100', '7449': 'gfx1100', '744a': 'gfx1100', '744b': 'gfx1100',+ '744c': 'gfx1100', '745e': 'gfx1100',+ // Navi 32 (RDNA 3)+ '7460': 'gfx1101', '7461': 'gfx1101', '7470': 'gfx1101', '747e': 'gfx1101',+ // Navi 33 (RDNA 3)+ '73f0': 'gfx1102', '7480': 'gfx1102', '7481': 'gfx1102', '7483': 'gfx1102',+ '7487': 'gfx1102', '7489': 'gfx1102', '748b': 'gfx1102', '7499': 'gfx1102',+ '749f': 'gfx1102',+ // Navi 44 / Navi 48 (RDNA 4)+ '7590': 'gfx1200',+ '7550': 'gfx1201', '7551': 'gfx1201',+}++// ─── Pure parsing helpers ─────────────────────────────────────────────────────++/**+ * Parses `nvidia-smi --query-gpu=compute_cap,driver_version --format=csv,noheader`.+ * Returns null when the output carries no usable line.+ */+export function parseNvidiaSmi(stdout: string): { sm: number; cudaVersion: number } | null {+ const line = stdout.trim().split('\n')[0]?.trim() // e.g. "8.6, 551.61"+ if (!line) return null++ const parts = line.split(',').map((s) => s.trim())+ const sm = Math.round(parseFloat(parts[0] ?? '') * 10) // → 86++ // Derive max supported CUDA version from driver version+ // Driver ≥ 520 → CUDA 11.8, ≥ 525 → 12.0, ≥ 530 → 12.1, ≥ 535 → 12.2,+ // ≥ 545 → 12.3, ≥ 550 → 12.4, ≥ 555 → 12.5, ≥ 560 → 12.6+ const driverMajor = parseInt((parts[1] ?? '').split('.')[0] ?? '0', 10)+ let cudaVersion = 118 // safe minimum+ if (driverMajor >= 570) cudaVersion = 128 // Blackwell (RTX 50xx, sm_120)+ else if (driverMajor >= 560) cudaVersion = 126+ else if (driverMajor >= 555) cudaVersion = 125+ else if (driverMajor >= 550) cudaVersion = 124+ else if (driverMajor >= 545) cudaVersion = 123+ else if (driverMajor >= 535) cudaVersion = 122+ else if (driverMajor >= 530) cudaVersion = 121+ else if (driverMajor >= 525) cudaVersion = 120+ else if (driverMajor >= 520) cudaVersion = 118++ return { sm: isNaN(sm) ? 86 : sm, cudaVersion }+}++/**+ * Decodes the KFD `gfx_target_version` integer (major*10000 + minor*100 + step,+ * with minor and step read as hex digits) into a compute target name:+ * 120000 → gfx1200, 90402 → gfx942, 90010 → gfx90a.+ */+export function formatGfxTarget(version: number): string | null {+ if (!Number.isInteger(version) || version <= 0) return null+ const major = Math.floor(version / 10000)+ const minor = Math.floor((version % 10000) / 100)+ const step = version % 100+ if (major <= 0 || minor > 15 || step > 15) return null+ return `gfx${major}${minor.toString(16)}${step.toString(16)}`+}++/**+ * Picks the compute target out of the KFD topology node `properties` files.+ * Node 0 is the CPU node (simd_count 0) and is skipped. Among GPU nodes the+ * largest simd_count wins: on an APU + dGPU machine the APU commonly gets the+ * lower node number, and its gfx target (e.g. gfx1103) often has no published+ * wheels — the discrete card is always the one with more SIMDs.+ */+export function parseKfdGfxTarget(nodeProperties: string[]): string | null {+ let best: { target: string; simdCount: number } | null = null+ for (const text of nodeProperties) {+ const simdCount = readKfdProperty(text, 'simd_count')+ if (simdCount <= 0) continue+ const target = formatGfxTarget(readKfdProperty(text, 'gfx_target_version'))+ if (!target) continue+ if (!best || simdCount > best.simdCount) best = { target, simdCount }+ }+ return best?.target ?? null+}++function readKfdProperty(text: string, key: string): number {+ const match = new RegExp(`^${key}\\s+(\\d+)\\s*$`, 'm').exec(text)+ return match ? parseInt(match[1], 10) : 0+}++export interface VideoController {+ name: string+ pnpDeviceId: string+}++/**+ * Parses the JSON emitted by `Get-CimInstance Win32_VideoController | ConvertTo-Json`.+ * PowerShell emits a bare object rather than an array when there is one adapter.+ */+export function parseWindowsVideoControllers(stdout: string): VideoController[] {+ let parsed: unknown+ try {+ parsed = JSON.parse(stdout)+ } catch {+ return []+ }+ const list = Array.isArray(parsed) ? parsed : [parsed]+ return list+ .filter((entry): entry is Record<string, unknown> => !!entry && typeof entry === 'object')+ .map((entry) => ({+ name: typeof entry['Name'] === 'string' ? entry['Name'] : '',+ pnpDeviceId: typeof entry['PNPDeviceID'] === 'string' ? entry['PNPDeviceID'] : '',+ }))+ .filter((c) => c.pnpDeviceId !== '')+}++/** Extracts the PCI device id from a PNPDeviceID, e.g. `PCI\VEN_1002&DEV_7590&…` → "7590". */+export function parseAmdPciDeviceId(pnpDeviceId: string): string | null {+ const match = /VEN_1002&DEV_([0-9A-F]{4})/i.exec(pnpDeviceId)+ return match ? match[1].toLowerCase() : null+}++/**+ * Resolves a compute target from the installed display adapters. Returns the+ * AMD adapters it saw as well, so an unmapped card can be reported by name+ * instead of silently falling back to CPU.+ */+export function resolveWindowsGfxTarget(+ controllers: VideoController[],+): { gfxTarget: string | null; amdAdapters: string[] } {+ const amdAdapters: string[] = []+ let gfxTarget: string | null = null++ for (const controller of controllers) {+ const deviceId = parseAmdPciDeviceId(controller.pnpDeviceId)+ if (!deviceId) continue+ amdAdapters.push(controller.name || `PCI 1002:${deviceId}`)+ gfxTarget ??= WINDOWS_PCI_GFX_TARGETS[deviceId] ?? null+ }++ return { gfxTarget, amdAdapters }+}++/**+ * The pip index and requirements an extension's torch install has to end up+ * using on this platform. `MODLY_ROCM_INDEX` and `MODLY_ROCM_TORCH_SPEC`+ * (space-separated requirements) override either half — the escape hatch when a+ * newer torch breaks an extension and you need to drop back to, say, rocm6.4.+ */+export function resolveRocmTorchSpec(+ platform: string,+ gfxTarget: string | null,+ env: NodeJS.ProcessEnv = process.env,+): { indexUrl: string; specs: string[] } {+ const indexOverride = env['MODLY_ROCM_INDEX']?.trim()+ const specOverride = env['MODLY_ROCM_TORCH_SPEC']?.trim()++ const isWindows = platform === 'win32'+ const indexUrl = indexOverride || (isWindows ? ROCM_WINDOWS_INDEX : ROCM_LINUX_INDEX)++ if (specOverride) return { indexUrl, specs: specOverride.split(/\s+/).filter(Boolean) }++ // AMD's multi-arch index ships one torch per compute target, selected by a+ // pip extra. The pytorch.org ROCm index bakes the targets into a single+ // wheel, so there is nothing to select and nothing to pin.+ if (isWindows && gfxTarget) {+ return {+ indexUrl,+ specs: [+ `torch[device-${gfxTarget}]==${ROCM_WINDOWS_TORCH}`,+ `torchvision[device-${gfxTarget}]==${ROCM_WINDOWS_TORCHVISION}`,+ ],+ }+ }+ return { indexUrl, specs: ['torch', 'torchvision'] }+}++/** The `torch_flavor` value extension setup.py scripts branch on. */+export function torchFlavorFor(accelerator: Accelerator): TorchFlavor {+ if (accelerator === 'rocm') return 'rocm'+ if (accelerator === 'cuda') return 'cuda'+ return 'cpu'+}++export function describeGpuInfo(info: GpuInfo): string {+ const bits = [`accelerator=${info.accelerator}`]+ if (info.accelerator === 'cuda') bits.push(`sm=${info.sm}`, `cuda=${info.cudaVersion}`)+ if (info.gfxTarget) bits.push(`gfx=${info.gfxTarget}`)+ if (info.torchIndexUrl) bits.push(`torch_index=${info.torchIndexUrl}`)+ return bits.join(' ')+}++// ─── Detection ────────────────────────────────────────────────────────────────++function cpuInfo(): GpuInfo {+ return { sm: 0, cudaVersion: 0, accelerator: 'cpu' }+}++/**+ * AMD keeps sm/cudaVersion at 0 on purpose. Extensions that predate `torch_flavor`+ * branch on those two numbers, and 0 sends them down their most conservative+ * path — which also keeps them off `rembg[gpu]`, whose onnxruntime-gpu is+ * CUDA-only. Their torch install is then corrected by the ROCm setup shim.+ */+function rocmInfo(+ gfxTarget: string | null,+ platform: string,+ env: NodeJS.ProcessEnv,+): GpuInfo {+ const { indexUrl, specs } = resolveRocmTorchSpec(platform, gfxTarget, env)+ return {+ sm: 0,+ cudaVersion: 0,+ accelerator: 'rocm',+ ...(gfxTarget ? { gfxTarget } : {}),+ torchIndexUrl: indexUrl,+ torchSpecs: specs,+ }+}++function readFlavorOverride(env: NodeJS.ProcessEnv): TorchFlavor | null {+ const raw = env['MODLY_TORCH_FLAVOR']?.trim().toLowerCase()+ return raw === 'cuda' || raw === 'rocm' || raw === 'cpu' ? raw : null+}++function queryNvidiaSmi(): Promise<{ sm: number; cudaVersion: number } | null> {+ return new Promise((resolve) => {+ // Query compute cap + driver version in one call+ const proc = spawn('nvidia-smi', ['--query-gpu=compute_cap,driver_version', '--format=csv,noheader'], {+ stdio: ['ignore', 'pipe', 'ignore'],+ })+ let out = ''+ proc.stdout?.on('data', (d: Buffer) => { out += d.toString() })+ proc.on('close', (code) => resolve(code === 0 ? parseNvidiaSmi(out) : null))+ proc.on('error', () => resolve(null))+ })+}++/**+ * Reads the compute target straight out of the kernel's KFD topology. This+ * needs no ROCm installation and no external binary — the amdgpu driver alone+ * publishes it, which is exactly the state of a machine that has only ever run+ * PyTorch ROCm wheels (they bundle their own runtime).+ */+function readKfdGfxTarget(): string | null {+ if (!existsSync('/dev/kfd')) return null+ try {+ const nodes = readdirSync(KFD_TOPOLOGY_DIR).sort((a, b) => Number(a) - Number(b))+ const properties = nodes.map((node) => {+ try {+ return readFileSync(join(KFD_TOPOLOGY_DIR, node, 'properties'), 'utf-8')+ } catch {+ return ''+ }+ })+ return parseKfdGfxTarget(properties)+ } catch {+ return null+ }+}++function queryWindowsVideoControllers(): Promise<VideoController[]> {+ return new Promise((resolve) => {+ const proc = spawn('powershell', [+ '-NoProfile', '-NonInteractive', '-Command',+ 'Get-CimInstance Win32_VideoController | Select-Object Name,PNPDeviceID | ConvertTo-Json -Compress',+ ], { stdio: ['ignore', 'pipe', 'ignore'] })+ let out = ''+ proc.stdout?.on('data', (d: Buffer) => { out += d.toString() })+ proc.on('close', (code) => resolve(code === 0 ? parseWindowsVideoControllers(out) : []))+ proc.on('error', () => resolve([]))+ })+}++export interface DetectOptions {+ env?: NodeJS.ProcessEnv+ platform?: string+ arch?: string+ onLog?: (line: string) => void+}++export async function detectGpuInfo(options: DetectOptions = {}): Promise<GpuInfo> {+ const env = options.env ?? process.env+ const platform = options.platform ?? process.platform+ const arch = options.arch ?? process.arch+ const log = options.onLog ?? (() => {})++ const forced = readFlavorOverride(env)+ if (forced) log(`[gpu-detect] MODLY_TORCH_FLAVOR=${forced} — skipping auto-detection`)++ if (forced === 'cpu') return cpuInfo()++ if (forced === 'rocm') {+ const { gfxTarget } = await resolveGfxTarget(env, platform)+ if (!gfxTarget && platform === 'win32') {+ log('[gpu-detect] ROCm forced on Windows but no compute target found — set MODLY_ROCM_GFX (e.g. gfx1200)')+ return cpuInfo()+ }+ return rocmInfo(gfxTarget, platform, env)+ }++ // A forced flavour wins over every probe, the Apple-Silicon MPS default+ // included; nvidia-smi still runs so the CUDA path learns its real+ // sm/cudaVersion instead of the conservative zeros.+ if (forced === 'cuda') {+ const nvidia = await queryNvidiaSmi()+ return nvidia ? { ...nvidia, accelerator: 'cuda' } : { sm: 0, cudaVersion: 0, accelerator: 'cuda' }+ }++ if (platform === 'darwin' && arch === 'arm64') {+ return { sm: 0, cudaVersion: 0, accelerator: 'mps' }+ }++ // NVIDIA keeps priority: on a machine with both, nothing about the existing+ // CUDA behaviour changes.+ const nvidia = await queryNvidiaSmi()+ if (nvidia) return { ...nvidia, accelerator: 'cuda' }++ const { gfxTarget, amdAdapters } = await resolveGfxTarget(env, platform)+ if (gfxTarget) {+ log(`[gpu-detect] AMD GPU detected — compute target ${gfxTarget}`)+ return rocmInfo(gfxTarget, platform, env)+ }++ if (amdAdapters.length > 0) {+ log(+ `[gpu-detect] AMD GPU found (${amdAdapters.join(', ')}) but its ROCm compute target is unknown. ` ++ 'Falling back to CPU — set MODLY_ROCM_GFX (e.g. gfx1201) to force one.',+ )+ }++ return cpuInfo()+}++/**+ * Also hands back the AMD adapters the Windows probe saw, so the caller can+ * report an unmapped card without spawning a second PowerShell round-trip.+ */+async function resolveGfxTarget(+ env: NodeJS.ProcessEnv,+ platform: string,+): Promise<{ gfxTarget: string | null; amdAdapters: string[] }> {+ const override = env['MODLY_ROCM_GFX']?.trim()+ if (override) return { gfxTarget: override, amdAdapters: [] }+ if (platform === 'linux') return { gfxTarget: readKfdGfxTarget(), amdAdapters: [] }+ if (platform === 'win32') return resolveWindowsGfxTarget(await queryWindowsVideoControllers())+ return { gfxTarget: null, amdAdapters: [] }+}diff --git a/apps/forge-desktop/electron/main/hf-token.ts b/apps/forge-desktop/electron/main/hf-token.tsnew file mode 100644index 000000000..2ea9061af--- /dev/null+++ b/apps/forge-desktop/electron/main/hf-token.ts@@ -0,0 +1,61 @@+import { getSettings, setSettings } from './settings-store'+import { encryptSecretSync, decryptSecretSync } from './secure-store'+import { logger } from './logger'++/**+ * Hugging Face token, encrypted at rest in settings.json the same way the+ * provider API keys are (see secure-store.ts). It used to sit there in plain+ * text while every other secret in the app was encrypted.+ *+ * The plaintext lives only in this module's cache: `getHfToken()` is sync+ * because the callers that need it are sync (child-process env building), while+ * encrypt/decrypt are async.+ */+let cached = ''++export function getHfToken(): string {+ return cached+}++/**+ * Decrypt the stored token into the cache, re-encrypting a legacy plaintext one.+ * Synchronous on purpose: the FastAPI bridge reads the token while building its+ * child-process env at startup, so an async init could lose a race with it.+ */+export function initHfToken(userData: string): string {+ const stored = getSettings(userData).hfToken ?? ''+ if (!stored) {+ cached = ''+ return cached+ }++ const decrypted = decryptSecretSync(stored)+ if (decrypted === null) {+ // One of our blobs, but not decryptable here (different OS user/machine).+ // Leave settings.json alone — rewriting would turn an unreadable-but-intact+ // blob into a permanently lost one — and expose no token rather than+ // handing the ciphertext out as a credential.+ cached = ''+ logger.error('[hf-token] the stored Hugging Face token could not be decrypted — re-enter it in Settings → Integrations')+ return cached+ }++ cached = decrypted+ // An unchanged value means it was never encrypted (saved before encryption+ // existed) — upgrade it in place.+ if (cached === stored) {+ try {+ setSettings(userData, { hfToken: encryptSecretSync(cached) })+ logger.info('[hf-token] migrated a plaintext token to encrypted storage')+ } catch (err) {+ logger.error(`[hf-token] could not migrate the stored token: ${err}`)+ }+ }+ return cached+}++/** Persist the token encrypted and refresh the cache. */+export function setHfToken(userData: string, token: string): void {+ cached = token+ setSettings(userData, { hfToken: token ? encryptSecretSync(token) : '' })+}diff --git a/apps/forge-desktop/electron/main/index.ts b/apps/forge-desktop/electron/main/index.tsnew file mode 100644index 000000000..2f3f5b83c--- /dev/null+++ b/apps/forge-desktop/electron/main/index.ts@@ -0,0 +1,143 @@+import { app, BrowserWindow, shell, session } from 'electron'+import { join } from 'path'+import { electronApp, optimizer, is } from '@electron-toolkit/utils'+import { setupIpcHandlers } from './ipc-handlers'+import { PythonBridge } from './python-bridge'+import { logger, archiveCurrentSession } from './logger'+import { initAutoUpdater } from './updater'+import { syncBuiltinExtensions } from './builtin-sync'+import { reconcileInterruptedExtensionInstalls } from './extension-install-recovery'+import { getSettings } from './settings-store'++let mainWindow: BrowserWindow | null = null+let pythonBridge: PythonBridge | null = null++// When the launching terminal closes, stdout/stderr become broken pipes and+// every console.* write emits an unhandled 'error' (EPIPE) that would loop+// through the uncaughtException handler forever. Swallow stream errors.+process.stdout?.on('error', () => {})+process.stderr?.on('error', () => {})++function createWindow(): void {+ mainWindow = new BrowserWindow({+ width: 1280,+ height: 800,+ minWidth: 900,+ minHeight: 600,+ show: false,+ frame: false,+ backgroundColor: '#111113',+ titleBarStyle: 'hidden',+ icon: join(__dirname, '../../resources/icons/icon.png'),+ webPreferences: {+ preload: join(__dirname, '../preload/index.js'),+ sandbox: false,+ contextIsolation: true,+ nodeIntegration: false,+ backgroundThrottling: false+ }+ })++ mainWindow.on('ready-to-show', () => {+ mainWindow?.show()+ })++ // Keep the renderer's maximize/restore icon in sync — covers the toolbar+ // button, double-clicking the title bar, and OS window-snap gestures.+ mainWindow.on('maximize', () => mainWindow?.webContents.send('window:maximizeChanged', true))+ mainWindow.on('unmaximize', () => mainWindow?.webContents.send('window:maximizeChanged', false))++ mainWindow.webContents.on('before-input-event', (event, input) => {+ const isMacQuitShortcut =+ process.platform === 'darwin' &&+ input.type === 'keyDown' &&+ input.key.toLowerCase() === 'q' &&+ input.meta &&+ !input.control &&+ !input.alt++ if (isMacQuitShortcut) {+ event.preventDefault()+ app.quit()+ }+ })++ mainWindow.webContents.setWindowOpenHandler((details) => {+ shell.openExternal(details.url)+ return { action: 'deny' }+ })++ if (is.dev && process.env['ELECTRON_RENDERER_URL']) {+ mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])+ mainWindow.webContents.openDevTools()+ } else {+ mainWindow.loadFile(join(__dirname, '../renderer/index.html'))+ }+}++app.setName('Modly')++process.on('uncaughtException', (err) => {+ if ((err as NodeJS.ErrnoException).code === 'EPIPE') return+ logger.error(`Uncaught exception: ${err.stack ?? err.message}`)+ mainWindow?.webContents.send('app:error', err.stack ?? err.message)+})++process.on('unhandledRejection', (reason) => {+ const msg = String(reason)+ logger.error(`Unhandled rejection: ${msg}`)+ mainWindow?.webContents.send('app:error', msg)+})++app.whenReady().then(async () => {+ archiveCurrentSession()+ logger.info(`App started — version ${app.getVersion()}`)+ electronApp.setAppUserModelId('com.modly.app')++ // Clear Chromium disk cache on startup to recover from any corruption+ await session.defaultSession.clearCache()++ app.on('browser-window-created', (_, window) => {+ optimizer.watchWindowShortcuts(window)+ })++ // Sync built-in extensions from app resources to userData+ syncBuiltinExtensions()++ // Finish or roll back interrupted extension swaps before the backend scans+ // the extensions directory. This must complete before PythonBridge starts.+ const extensionsDir = getSettings(app.getPath('userData')).extensionsDir+ try {+ await reconcileInterruptedExtensionInstalls(extensionsDir, logger)+ } catch (err) {+ logger.error(`[ext-recovery] Startup reconciliation failed: ${String(err)}`)+ }++ // Start Python FastAPI backend+ pythonBridge = new PythonBridge()+ pythonBridge.setWindowGetter(() => mainWindow)+ setupIpcHandlers(pythonBridge, () => mainWindow)+ initAutoUpdater(() => mainWindow)++ createWindow()++ app.on('activate', () => {+ if (BrowserWindow.getAllWindows().length === 0) createWindow()+ })+})++app.on('window-all-closed', () => {+ // Modly holds a multi-GB Python subprocess; leaving it running in the+ // Dock after the window closes (the Mac default) is the wrong behavior+ // for this app. Closing the window means quit.+ app.quit()+})++app.on('before-quit', (event) => {+ if (!pythonBridge) return+ event.preventDefault()+ pythonBridge.stop().finally(() => {+ pythonBridge = null+ app.quit()+ })+})diff --git a/apps/forge-desktop/electron/main/ipc-handlers.ts b/apps/forge-desktop/electron/main/ipc-handlers.tsnew file mode 100644index 000000000..e9cac040b--- /dev/null+++ b/apps/forge-desktop/electron/main/ipc-handlers.ts@@ -0,0 +1,2275 @@+import { ipcMain, BrowserWindow, Notification, dialog, app, shell } from 'electron'+import { buildSync } from 'esbuild'+import { autoUpdater } from 'electron-updater'+import { basename, join } from 'path'+import { rm as rmAsync, readFile, writeFile, mkdir, readdir, rename, cp, symlink, lstat, copyFile } from 'fs/promises'+import { existsSync, mkdirSync, readdirSync, statSync } from 'fs'+import axios from 'axios'+import * as tar from 'tar'+import * as os from 'os'+import { promisify } from 'util'+import { PythonBridge, API_BASE_URL } from './python-bridge'+import {+ isModelDownloaded,+ listDownloadedModels,+ downloadModelFromHF,+ downloadModelSourcesFromHF,+ type DownloadProgress,+} from './model-downloader'+import {+ legacyDownloadSteps,+ resolveInstalledExtensionSharedWeightGroups,+ resolveInstalledModelDownloadPlan,+} from './model-download-plan'+import {+ areModelSourcesDownloaded,+ areModelSourcesDownloadedAtRoot,+ areWeightGroupSourcesDownloaded,+ installedWeightVariants,+ listWeightVariantFiles,+ modelHasLocalData,+ normalizeModelSources,+ normalizeWeightGroupReferences,+ normalizeWeightGroups,+ normalizeWeightVariants,+ validateModelNodeIds,+ removePartialDownloadArtifacts,+ resolveExtensionModelRoot,+ resolveModelRoot,+ resolveWeightGroupRoot,+ resolveWeightStorageRoot,+ safeModelSourceId,+ weightStorageHasLocalData,+} from './model-sources'+import { getSettings, setSettings } from './settings-store'+import { checkSetupNeeded, markSetupDone, runFullSetup, getVenvPythonExe, ensureSslPatch } from './python-setup'+import { logger } from './logger'+import { getProcessRunner, getPythonProcessRunner, getExtPythonExe, terminateProcessRunner, terminateAllProcessRunners } from './process-runner'+import { getBuiltinExtensionsDir } from './builtin-sync'+import { spawn, execFile } from 'child_process'+import {+ EXT_INCOMPLETE_MARKER,+ EXT_REGISTRATION_PENDING_MARKER,+ EXT_VALIDATED_MARKER,+ assertSafeExtensionId,+ buildExtensionBackupPath,+ buildExtensionStagingPath,+ isInternalExtensionDirName,+ resolveExtensionPathWithinRoot,+} from './extension-path-guard'+import { detectGpuInfo, describeGpuInfo, torchFlavorFor, type GpuInfo } from './gpu-detect'+import { SETUP_LAUNCHER_SOURCE } from './setup-launcher'+import {+ assertCompatibleExtensionUpdateType,+ expectedModelIds,+ markExtensionInstallationInterrupted,+ validateExtensionQuarantinePayload,+ validateExtensionReloadPayload,+ validateExistingExtensionReplacement,+ validateInstallManifest,+ assertSupportedSceneNodeShape,+} from './extension-install-utils'+import {+ beginExtensionRegistrationTransaction,+ clearExtensionRegistrationTransaction,+ cleanupValidatedExtensionBackups,+ quarantineExtensionRegistrationFailure,+ parseExtensionRegistrationPendingName,+ removeExtensionWithBackups,+ renameWithRetry as renameExtensionWithRetry,+ restoreExtensionBackup,+ rmWithRetry as removeExtensionWithRetry,+ runExtensionRegistrationValidationTransaction,+ runExtensionRepairTransaction,+ type ExtensionRegistrationValidationCapability,+ validateExtensionDestinationRegistration,+} from './extension-install-recovery'+import { registerWorkspaceAssetLibraryIpcHandlers } from './artifact-registry-service'+import { updatesSupported } from './updater'+import { ModelWeightOperations } from './model-weight-operations'+import { readLocalFileBase64 } from './bounded-file-reader'+import { encryptSecret, decryptSecret } from './secure-store'+import { getHfToken, initHfToken, setHfToken } from './hf-token'++type WindowGetter = () => BrowserWindow | null+const pExecFile = promisify(execFile)++// ─── Run an extension's setup.py directly (no FastAPI needed) ─────────────────++function runExtensionSetup(+ extDir: string,+ gpu: GpuInfo,+ onLog?: (line: string) => void,+): Promise<void> {+ return new Promise((resolve, reject) => {+ const userData = app.getPath('userData')+ ensureSslPatch(userData)+ const pythonExe = getVenvPythonExe(userData)+ const setupPy = join(extDir, 'setup.py')++ // Shared pip wheel cache: a failed setup retried later reuses the multi-GB+ // torch wheels instead of re-downloading them (see issue #223). Extension+ // setup.py scripts that pass --no-cache-dir get it stripped by the launcher.+ const pipCacheDir = join(getSettings(userData).dependenciesDir, 'pip-cache')+ try { mkdirSync(pipCacheDir, { recursive: true }) } catch { /* pip creates it too */ }++ const torchFlavor = torchFlavorFor(gpu.accelerator)+ const args = JSON.stringify({+ python_exe: pythonExe,+ ext_dir: extDir,+ gpu_sm: gpu.sm,+ cuda_version: gpu.cudaVersion,+ accelerator: gpu.accelerator,+ // Extensions that know about AMD branch on torch_flavor (the official+ // hunyuan3d-mini one does). Those that don't get corrected by the ROCm+ // shim in setup-launcher.ts instead.+ torch_flavor: torchFlavor,+ gfx_target: gpu.gfxTarget ?? '',+ torch_index_url: gpu.torchIndexUrl ?? '',+ platform: process.platform,+ arch: process.arch,+ })+ const launcher = SETUP_LAUNCHER_SOURCE+ // The rewrite decision itself is made in gpu-detect.ts (and unit-tested+ // there); the launcher above only applies what these carry.+ const proc = spawn(pythonExe, ['-c', launcher, setupPy, args], {+ stdio: ['ignore', 'pipe', 'pipe'],+ env: {+ ...process.env,+ PIP_CACHE_DIR: pipCacheDir,+ MODLY_TORCH_FLAVOR: torchFlavor,+ MODLY_TORCH_INDEX_URL: gpu.torchIndexUrl ?? '',+ MODLY_TORCH_SPECS: JSON.stringify(gpu.torchSpecs ?? []),+ },+ })++ const handleLine = (line: string) => { if (line) onLog?.(line) }++ let stderr = ''+ proc.stdout?.on('data', (d: Buffer) => d.toString().split('\n').forEach(handleLine))+ proc.stderr?.on('data', (d: Buffer) => {+ const s = d.toString()+ stderr += s+ s.split('\n').forEach(handleLine)+ })++ proc.on('close', (code) => {+ if (code === 0) resolve()+ else reject(new Error(`setup.py exited with code ${code}\n${stderr.slice(-2000)}`))+ })+ proc.on('error', reject)+ })+}++// Extension ids with an install currently in flight. Their folder carries the+// incomplete marker during setup — extensions:list must not report it as+// corrupted while the install is legitimately running.+const activeExtensionInstalls = new Set<string>()+const rmWithRetry = (path: string, label: string) =>+ removeExtensionWithRetry(path, label, logger)+const renameWithRetry = (from: string, to: string, label: string) =>+ renameExtensionWithRetry(from, to, label, logger)++export function setupIpcHandlers(pythonBridge: PythonBridge, getWindow: WindowGetter): void {+ type ActiveDownload = {+ progress: DownloadProgress & { variantId?: string }+ done: Promise<void>+ finish: () => void+ targetRoots: string[]+ currentTargetId?: string+ stopRequested?: 'pause' | 'cancel'+ }+ const activeDownloads = new Map<string, ActiveDownload>()+ const weightOperations = new ModelWeightOperations()+ // Paused/error sessions retain their original paths even after settings change.+ const interruptedTargets = new Map<string, string[]>()+ const notifyWeightChange = () => {+ getWindow()?.webContents.send('model:weightsChanged')+ }+ // No backend listening means no Python process can hold the weight files+ // open, so deletion is safe. A backend that answers (or times out) is not.+ const backendUnreachable = (err: unknown): boolean => {+ if (!axios.isAxiosError(err) || err.response) return false+ const cause = (err as { cause?: { code?: string } }).cause+ return err.code === 'ECONNREFUSED' || cause?.code === 'ECONNREFUSED'+ }+ async function unloadForRemoval(modelIds: string[]) {+ for (const id of modelIds) {+ try {+ const response = await axios.post(+ `${API_BASE_URL}/model/unload/${encodeURIComponent(id)}`, {}, { timeout: 40_000 },+ )+ if (response.data?.unloaded !== true) throw new Error('Model unload was not confirmed; weights were preserved')+ } catch (err) {+ if (backendUnreachable(err)) return+ throw err+ }+ }+ }+ // Unload only this extension's generators, not every model in the app.+ async function unloadExtensionForRemoval(extensionId: string) {+ let modelIds: string[]+ try {+ const { data } = await axios.get<{ id: string }[]>(`${API_BASE_URL}/model/all`, { timeout: 10_000 })+ modelIds = data.map((model) => model.id).filter((id) => id.startsWith(`${extensionId}/`))+ } catch (err) {+ if (backendUnreachable(err)) return+ throw err+ }+ await unloadForRemoval(modelIds)+ }+ const resolveModelPlan = (modelId: unknown) => resolveInstalledModelDownloadPlan({+ modelId,+ userExtensionsDir: getSettings(app.getPath('userData')).extensionsDir,+ builtinExtensionsDir: getBuiltinExtensionsDir(),+ blockedExtensionIds: activeExtensionInstalls,+ })+ const LOCKED_MODEL_FILES_ERROR = 'Model files are still locked after several attempts. Close any programs using the model and try again.'+ // Logging from renderer+ ipcMain.on('log:error', (_event, message: string) => logger.error(`[Renderer] ${message}`))+ ipcMain.handle('log:getPath', () => join(app.getPath('userData'), 'logs', 'modly.log'))+ ipcMain.handle('log:readAll', async (_event, session?: string) => {+ const logsDir = join(app.getPath('userData'), 'logs')+ const dir = session ? join(logsDir, 'sessions', session) : logsDir+ const files = ['modly.log', 'errors.log', 'runtime.log']+ const result: Record<string, string> = {}+ for (const file of files) {+ try {+ const filePath = join(dir, file)+ result[file] = existsSync(filePath) ? await readFile(filePath, 'utf-8') : ''+ } catch {+ result[file] = ''+ }+ }+ return result+ })+ ipcMain.handle('log:listSessions', () => {+ const sessionsDir = join(app.getPath('userData'), 'logs', 'sessions')+ if (!existsSync(sessionsDir)) return []+ try {+ return readdirSync(sessionsDir)+ .filter(f => statSync(join(sessionsDir, f)).isDirectory())+ .sort()+ .reverse()+ } catch {+ return []+ }+ })++ // Secure storage — OS-level encryption (Keychain/DPAPI/libsecret) for secrets+ // the renderer would otherwise have to keep in plain-text localStorage (API keys).+ ipcMain.handle('secure:encrypt', (_, plainText: string) => encryptSecret(plainText))+ ipcMain.handle('secure:decrypt', (_, stored: string) => decryptSecret(stored))++ // Window controls (frameless window)+ ipcMain.on('window:minimize', () => getWindow()?.minimize())+ ipcMain.on('window:maximize', () => {+ const win = getWindow()+ if (!win) return+ win.isMaximized() ? win.restore() : win.maximize()+ })+ ipcMain.on('window:close', () => getWindow()?.close())+ ipcMain.handle('window:isMaximized', () => getWindow()?.isMaximized() ?? false)++ // Native OS notification (Windows toast / macOS Notification Center / Linux),+ // for events the user wants to know about even when the window is minimized or+ // behind other apps — e.g. a generation or workflow run finishing. Routed through+ // the main process rather than the renderer's own Notification API so it works+ // the same way regardless of focus and carries the app's own icon.+ ipcMain.handle('notifications:show', (_event, title: string, body: string) => {+ if (!Notification.isSupported()) return { success: false, error: 'Notifications not supported' }+ const notification = new Notification({+ title,+ body,+ icon: join(__dirname, '../../resources/icons/icon.png'),+ })+ notification.on('click', () => {+ const win = getWindow()+ if (!win) return+ if (win.isMinimized()) win.restore()+ win.show()+ win.focus()+ })+ notification.show()+ return { success: true }+ })++ // Setup handlers — skipped in dev (uses .venv instead of python-embed)+ ipcMain.handle('setup:check', async () => {+ const userData = app.getPath('userData')+ const defaultDataDir = join(app.getPath('documents'), 'Modly')+ return {+ needed: checkSetupNeeded(userData),+ defaultDataDir,+ platform: process.platform,+ arch: process.arch,+ }+ })++ ipcMain.handle('setup:saveDataDir', async (_event, { baseDir }: { baseDir: string }) => {+ const userData = app.getPath('userData')+ setSettings(userData, {+ modelsDir: join(baseDir, 'models'),+ workspaceDir: join(baseDir, 'workspace'),+ workflowsDir: join(baseDir, 'workflows'),+ extensionsDir: join(baseDir, 'extensions'),+ dependenciesDir: join(baseDir, 'dependencies'),+ agentDir: join(baseDir, 'agent'),+ })+ })++ ipcMain.handle('setup:run', async () => {+ const userData = app.getPath('userData')+ const win = getWindow()+ if (!win) return { success: false, error: 'No window available' }+ try {+ await runFullSetup(win, userData)+ markSetupDone(userData)+ return { success: true }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ // Python bridge+ ipcMain.handle('python:start', async () => {+ try {+ await pythonBridge.start()+ return { success: true, port: pythonBridge.getPort() }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ ipcMain.handle('python:status', () => ({+ ready: pythonBridge.isReady(),+ apiUrl: API_BASE_URL+ }))++ // File system+ ipcMain.handle('fs:selectImage', async () => {+ const win = getWindow()+ if (!win) return null++ const result = await dialog.showOpenDialog(win, {+ title: 'Select an image',+ filters: [{ name: 'Images', extensions: ['jpg', 'jpeg', 'png', 'webp'] }],+ properties: ['openFile']+ })++ return result.canceled ? null : result.filePaths[0]+ })++ ipcMain.handle('fs:selectMeshFile', async () => {+ const win = getWindow()+ if (!win) return null++ const result = await dialog.showOpenDialog(win, {+ title: 'Select a 3D mesh file',+ filters: [{ name: '3D Mesh', extensions: ['glb', 'obj', 'stl', 'ply', 'splat'] }],+ properties: ['openFile']+ })++ return result.canceled ? null : result.filePaths[0]+ })++ ipcMain.handle('fs:saveModel', async (_, defaultName: string) => {+ const win = getWindow()+ if (!win) return null++ const result = await dialog.showSaveDialog(win, {+ title: 'Save 3D Model',+ defaultPath: defaultName,+ filters: [+ { name: 'OBJ', extensions: ['obj'] },+ { name: 'GLB', extensions: ['glb'] },+ { name: 'STL', extensions: ['stl'] }+ ]+ })++ return result.canceled ? null : result.filePath+ })++ ipcMain.handle('fs:savePath', async (_, args: { filters: { name: string; extensions: string[] }[]; defaultPath?: string }) => {+ const win = getWindow()+ if (!win) return null+ const result = await dialog.showSaveDialog(win, {+ title: 'Choose output path',+ filters: args.filters,+ defaultPath: args.defaultPath,+ })+ return result.canceled ? null : result.filePath+ })++ ipcMain.handle('model:unloadAll', async (): Promise<{ success: boolean; error?: string }> => {+ try {+ await axios.post(`${API_BASE_URL}/model/unload-all`, {}, { timeout: 10_000 })+ return { success: true }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ ipcMain.handle('model:delete', async (_, modelId: string): Promise<{ success: boolean; error?: string }> => {+ if (activeDownloads.has(modelId)) {+ return { success: false, error: 'Cannot remove model weights while their download is active' }+ }+ let modelDir: string+ try {+ await resolveModelPlan(modelId)+ modelDir = resolveModelRoot(getSettings(app.getPath('userData')).modelsDir, modelId)+ } catch (err) {+ return { success: false, error: String(err) }+ }++ try {+ const removed = await weightOperations.remove(+ [modelDir], () => unloadForRemoval([modelId]), () => rmWithRetry(modelDir, 'model-delete'),+ )+ notifyWeightChange()+ return removed.ok ? { success: true } : {+ success: false, error: removed.locked ? 'Model files are still locked. Try again after closing the model.' : String(removed.error),+ }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ ipcMain.handle('model:deleteWeightVariant', async (_, modelId: string, variantId: string): Promise<{ success: boolean; error?: string }> => {+ if (activeDownloads.has(modelId)) {+ return { success: false, error: 'Cannot remove model weights while their download is active' }+ }+ try {+ const plan = await resolveModelPlan(modelId)+ const variant = plan.kind === 'legacy'+ ? plan.weightVariants?.options.find((option) => option.id === variantId)+ : undefined+ if (!variant) throw new Error(`Model node "${modelId}" has no weight variant "${String(variantId)}"`)+ const modelsDir = getSettings(app.getPath('userData')).modelsDir+ // Reserve the node root (blocks a concurrent download of any of its variants),+ // unload with confirmation, then list and remove only this variant's files.+ const removed = await weightOperations.remove(+ [resolveModelRoot(modelsDir, modelId)],+ () => unloadForRemoval([modelId]),+ async (): Promise<Awaited<ReturnType<typeof rmWithRetry>>> => {+ for (const file of await listWeightVariantFiles(modelsDir, modelId, variant)) {+ const result = await rmWithRetry(file, 'model-variant-delete')+ if (!result.ok) return result+ }+ return { ok: true }+ },+ )+ notifyWeightChange()+ if (removed.ok) return { success: true }+ return { success: false, error: removed.locked ? LOCKED_MODEL_FILES_ERROR : String(removed.error) }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ ipcMain.handle('model:showInFolder', (_, modelId: string) => {+ const modelDir = join(getSettings(app.getPath('userData')).modelsDir, modelId)+ if (existsSync(modelDir)) {+ shell.openPath(modelDir)+ }+ })++ // Read local file → base64 (bypasses file:// restrictions in the renderer)+ ipcMain.handle('fs:readFileBase64', (_, filePath: string) => readLocalFileBase64(filePath))++ ipcMain.handle('fs:readScreenshotDataUrl', async (_, filename: string) => {+ const filePath = app.isPackaged+ ? join(process.resourcesPath, 'screenshots', filename)+ : join(app.getAppPath(), 'src/assets', filename)+ const buffer = await readFile(filePath)+ return `data:image/png;base64,${buffer.toString('base64')}`+ })++ // Model management+ ipcMain.handle('model:listDownloaded', () => {+ const modelsDir = getSettings(app.getPath('userData')).modelsDir+ return listDownloadedModels(modelsDir)+ })++ ipcMain.handle('model:isDownloaded', async (_, modelId: string): Promise<boolean> => {+ const modelsDir = getSettings(app.getPath('userData')).modelsDir+ try {+ const plan = await resolveInstalledModelDownloadPlan({+ modelId,+ userExtensionsDir: getSettings(app.getPath('userData')).extensionsDir,+ builtinExtensionsDir: getBuiltinExtensionsDir(),+ blockedExtensionIds: activeExtensionInstalls,+ })+ if (plan.kind === 'multi-source') {+ const privateReady = plan.sources.length === 0+ || areModelSourcesDownloaded(modelsDir, modelId, plan.sources)+ return privateReady && plan.sharedGroups.every((group) => (+ areWeightGroupSourcesDownloaded(modelsDir, plan.extensionId, group)+ ))+ }+ return isModelDownloaded(modelsDir, modelId, plan.downloadCheck)+ && (!plan.weightVariants || installedWeightVariants(modelsDir, modelId, plan.weightVariants).length > 0)+ } catch {+ return false+ }+ })++ // null means "unknown" (unreadable plan, or a node without variants) — the renderer+ // must not read an empty array as "no variant installed".+ ipcMain.handle('model:installedWeightVariants', async (_, modelId: string): Promise<string[] | null> => {+ try {+ const plan = await resolveModelPlan(modelId)+ return plan.kind === 'legacy' && plan.weightVariants+ ? installedWeightVariants(getSettings(app.getPath('userData')).modelsDir, modelId, plan.weightVariants)+ : null+ } catch {+ return null+ }+ })++ ipcMain.handle('model:hasLocalData', async (_, modelId: string): Promise<boolean> => {+ try {+ await resolveModelPlan(modelId)+ return modelHasLocalData(getSettings(app.getPath('userData')).modelsDir, modelId)+ } catch {+ return false+ }+ })++ ipcMain.handle('model:sharedGroups', async (_, extensionId: string) => {+ try {+ const groups = await resolveInstalledExtensionSharedWeightGroups({+ extensionId,+ userExtensionsDir: getSettings(app.getPath('userData')).extensionsDir,+ builtinExtensionsDir: getBuiltinExtensionsDir(),+ blockedExtensionIds: activeExtensionInstalls,+ })+ const modelsDir = getSettings(app.getPath('userData')).modelsDir+ return groups.map((group) => ({+ id: group.id,+ targetId: group.targetId,+ dependentModelIds: group.dependentModelIds,+ downloaded: areWeightGroupSourcesDownloaded(modelsDir, extensionId, group),+ hasLocalData: weightStorageHasLocalData(modelsDir, group.targetId),+ }))+ } catch {+ return []+ }+ })++ ipcMain.handle('model:deleteSharedGroup', async (+ _,+ extensionId: string,+ groupId: string,+ ): Promise<{ success: boolean; error?: string }> => {+ try {+ const groups = await resolveInstalledExtensionSharedWeightGroups({+ extensionId,+ userExtensionsDir: getSettings(app.getPath('userData')).extensionsDir,+ builtinExtensionsDir: getBuiltinExtensionsDir(),+ blockedExtensionIds: activeExtensionInstalls,+ })+ const group = groups.find((candidate) => candidate.id === groupId)+ if (!group) return { success: false, error: `Unknown shared weight group: ${groupId}` }+ const groupRoot = resolveWeightGroupRoot(+ getSettings(app.getPath('userData')).modelsDir,+ extensionId,+ group.id,+ )+ const removed = await weightOperations.remove(+ [groupRoot],+ () => unloadForRemoval(group.dependentModelIds),+ () => rmWithRetry(groupRoot, 'shared-model-delete'),+ )+ notifyWeightChange()+ if (removed.ok) return { success: true }+ return {+ success: false,+ error: removed.locked+ ? 'Shared model files are still locked. Close any programs using them and try again.'+ : String(removed.error),+ }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ ipcMain.handle('model:deleteExtensionWeights', async (+ _,+ extensionId: string,+ ): Promise<{ success: boolean; error?: string }> => {+ try {+ const safeExtensionId = assertSafeExtensionId(extensionId)+ if ([...activeDownloads.keys()].some((modelId) => modelId.split('/', 1)[0] === safeExtensionId)) {+ return { success: false, error: 'Cannot remove extension weights while a download is active' }+ }+ const extensionRoot = resolveExtensionModelRoot(+ getSettings(app.getPath('userData')).modelsDir,+ safeExtensionId,+ )+ const removed = await weightOperations.remove(+ [extensionRoot],+ () => unloadExtensionForRemoval(safeExtensionId),+ () => rmWithRetry(extensionRoot, 'extension-model-delete'),+ )+ notifyWeightChange()+ if (removed.ok) return { success: true }+ return {+ success: false,+ error: removed.locked+ ? 'Extension model files are still locked. Close any programs using them and try again.'+ : String(removed.error),+ }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ ipcMain.handle('model:activeDownloads', () =>+ [...activeDownloads.entries()].map(([modelId, active]) => ({ modelId, ...active.progress }))+ )++ ipcMain.handle('model:download', async (+ event,+ modelId: string,+ requestedVariantId?: string | null,+ ) => {+ if (activeDownloads.has(modelId)) {+ return { success: false, error: 'Download already in progress' }+ }+ const variantId = requestedVariantId ?? undefined+ let plan: Awaited<ReturnType<typeof resolveInstalledModelDownloadPlan>>+ let legacySteps: ReturnType<typeof legacyDownloadSteps> = []+ try {+ plan = await resolveModelPlan(modelId)+ if (plan.kind === 'multi-source') {+ if (variantId !== undefined) throw new Error(`Model node "${modelId}" does not declare weight variants`)+ } else {+ // Shared files first (every variant excluded), then the requested variant.+ legacySteps = legacyDownloadSteps(plan, variantId)+ }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ if (activeDownloads.has(modelId)) {+ return { success: false, error: 'Download already in progress' }+ }++ const modelsDir = getSettings(app.getPath('userData')).modelsDir+ const allTargets = plan.kind === 'multi-source'+ ? [+ ...plan.sharedGroups.map((group) => ({+ targetId: group.targetId,+ label: `Shared · ${group.id}`,+ sources: group.sources,+ })),+ ...(plan.sources.length > 0 ? [{+ targetId: modelId,+ label: 'Node-specific',+ sources: plan.sources,+ }] : []),+ ]+ : []+ const targetRoots = plan.kind === 'multi-source'+ ? allTargets.map((target) => resolveWeightStorageRoot(modelsDir, target.targetId))+ : [resolveModelRoot(modelsDir, modelId)]+ let release: () => void+ try {+ release = weightOperations.acquire(`downloading ${modelId}`, targetRoots)+ } catch (err) {+ return { success: false, error: String(err) }+ }+ const managedTargets = allTargets.filter((target) => !areModelSourcesDownloadedAtRoot(+ resolveWeightStorageRoot(modelsDir, target.targetId), target.sources,+ ))++ let finish!: () => void+ const done = new Promise<void>((resolveDone) => { finish = resolveDone })+ const active: ActiveDownload = { progress: { percent: 0, variantId }, done, finish, targetRoots }+ activeDownloads.set(modelId, active)+ interruptedTargets.set(modelId, targetRoots)+ try {+ const onProgress = (progress: DownloadProgress) => {+ active.progress = { ...progress, variantId }+ event.sender.send('model:downloadProgress', { modelId, variantId, ...progress })+ }+ if (plan.kind === 'multi-source') {+ if (managedTargets.length === 0) {+ onProgress({ percent: 100 })+ }+ for (const [index, target] of managedTargets.entries()) {+ if (active.stopRequested) throw new Error(`Model download ${active.stopRequested === 'pause' ? 'paused' : 'cancelled'}`)+ active.currentTargetId = target.targetId+ await downloadModelSourcesFromHF(target.targetId, target.sources, (progress) => {+ const aggregatePercent = Math.min(+ 99,+ Math.round(((index + progress.percent / 100) / managedTargets.length) * 100),+ )+ onProgress({+ ...progress,+ percent: aggregatePercent,+ status: progress.status ? `${target.label} · ${progress.status}` : target.label,+ })+ })+ notifyWeightChange()+ }+ if (active.stopRequested) throw new Error(`Model download ${active.stopRequested === 'pause' ? 'paused' : 'cancelled'}`)+ if (managedTargets.length > 0) onProgress({ percent: 100, status: 'done' })+ } else {+ active.currentTargetId = modelId+ // Shared files and the variant are separate passes sharing one 0-100 bar.+ for (const [index, step] of legacySteps.entries()) {+ if (active.stopRequested) throw new Error(`Model download ${active.stopRequested === 'pause' ? 'paused' : 'cancelled'}`)+ await downloadModelFromHF(+ plan.repoId,+ modelId,+ (progress) => onProgress({ ...progress, percent: Math.round((index * 100 + progress.percent) / legacySteps.length) }),+ step.skipPrefixes,+ step.includePrefixes,+ )+ }+ }+ interruptedTargets.delete(modelId)+ return { success: true }+ } catch (err: any) {+ const message = err?.message ?? String(err)+ if (message.includes('paused')) {+ event.sender.send('model:downloadProgress', { modelId, variantId, percent: 0, status: 'paused', paused: true })+ return { success: false, paused: true }+ }+ if (message.includes('cancelled')) {+ event.sender.send('model:downloadProgress', { modelId, variantId, percent: 0, status: 'cancelled', cancelled: true })+ return { success: false, cancelled: true }+ }+ return { success: false, error: String(err) }+ } finally {+ if (activeDownloads.get(modelId) === active) activeDownloads.delete(modelId)+ release()+ active.finish()+ notifyWeightChange()+ }+ })++ ipcMain.handle('model:pauseDownload', async (_, modelId: string): Promise<{ success: boolean; error?: string }> => {+ try {+ const active = activeDownloads.get(modelId)+ const targetId = active?.currentTargetId+ if (!active || !targetId) return { success: false, error: 'No active download target' }+ active.stopRequested = 'pause'+ await axios.post(`${API_BASE_URL}/model/hf-download/pause`, null, {+ params: { model_id: targetId },+ timeout: 5000,+ })+ return { success: true }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ ipcMain.handle('model:cancelDownload', async (_, modelId: string): Promise<{ success: boolean; error?: string }> => {+ try {+ const active = activeDownloads.get(modelId)+ if (active) active.stopRequested = 'cancel'+ if (active?.currentTargetId) {+ await axios.post(`${API_BASE_URL}/model/hf-download/cancel`, null, {+ params: { model_id: active.currentTargetId },+ timeout: 5000,+ })+ }+ if (active) {+ let timer: ReturnType<typeof setTimeout> | undefined+ try {+ await Promise.race([+ active.done,+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error('Timed out waiting for the download to stop')), 30_000)+ }),+ ])+ } finally {+ clearTimeout(timer)+ }+ }+ const roots = active?.targetRoots ?? interruptedTargets.get(modelId) ?? [resolveModelRoot(+ getSettings(app.getPath('userData')).modelsDir, modelId,+ )]+ // Another sibling may have resumed these targets after our session stopped.+ const release = weightOperations.acquire(`cancelling ${modelId}`, roots)+ try {+ await Promise.all(roots.map((root) => removePartialDownloadArtifacts(root)))+ interruptedTargets.delete(modelId)+ } finally {+ release()+ notifyWeightChange()+ }+ return { success: true }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ // Export mesh to GLB / STL / OBJ+ ipcMain.handle('model:export', async (_, { outputUrl, format }: { outputUrl: string; format: string }) => {+ const win = getWindow()+ if (!win) return { success: false, error: 'No window' }++ const meshPath = outputUrl.replace(/^\/workspace\//, '')+ const baseName = meshPath.split('/').pop()?.replace(/\.\w+$/, '') ?? 'model'++ const result = await dialog.showSaveDialog(win, {+ title: 'Export 3D Model',+ defaultPath: `${baseName}.${format}`,+ filters: [{ name: format.toUpperCase(), extensions: [format] }],+ })+ if (result.canceled || !result.filePath) return { success: false }++ try {+ const response = await axios.get(+ `${API_BASE_URL}/export/${format}?path=${encodeURIComponent(meshPath)}`,+ { responseType: 'arraybuffer' }+ )+ await writeFile(result.filePath, Buffer.from(response.data as ArrayBuffer))+ return { success: true }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ // Shell+ ipcMain.handle('shell:openExternal', (_, url: string) => shell.openExternal(url))++ // Open a model in OrcaSlicer via its orcaslicer://open?file=<url> deeplink.+ //+ // The returned error only covers the shell refusing the call outright. It is+ // NOT an install check: on Windows an unregistered scheme still makes+ // ShellExecuteEx succeed — the OS shows its own "You'll need a new app to open+ // this orcaslicer link" dialog and this resolves with success. Detecting a+ // missing OrcaSlicer would take a per-platform handler probe (registry on+ // Windows), so the renderer must not promise the user that it knows.+ ipcMain.handle('slicer:open', async (_, url: string): Promise<{ success: boolean; error?: string }> => {+ if (typeof url !== 'string' || !url.startsWith('orcaslicer://')) {+ return { success: false, error: 'slicer:open requires an orcaslicer:// URL' }+ }+ try {+ await shell.openExternal(url)+ return { success: true }+ } catch (err) {+ return { success: false, error: err instanceof Error ? err.message : String(err) }+ }+ })++ // App info+ // System memory (used/available/total bytes).+ // On macOS, matches Activity Monitor's "Memory Used":+ // used = wired + active + compressed.+ ipcMain.handle('system:memory', async () => {+ const total = os.totalmem()++ if (process.platform === 'darwin') {+ try {+ const { stdout } = await pExecFile('vm_stat', [])+ const pageSizeMatch = stdout.match(/page size of (\d+) bytes/)+ const pageSize = pageSizeMatch ? parseInt(pageSizeMatch[1]!, 10) : 16384++ const pagesFor = (label: string): number => {+ const m = stdout.match(new RegExp(`${label}:\\s+(\\d+)`))+ return m ? parseInt(m[1]!, 10) : 0+ }++ const active = pagesFor('Pages active')+ const wired = pagesFor('Pages wired down')+ const compressed = pagesFor('Pages occupied by compressor')++ const used = (active + wired + compressed) * pageSize+ const available = Math.max(0, total - used)+ return { total, used, available }+ } catch {+ // Fall back to total - free outside Activity Monitor semantics.+ }+ }++ const free = os.freemem()+ return { total, used: total - free, available: free }+ })++ ipcMain.handle('app:info', () => ({+ version: app.getVersion(),+ userData: app.getPath('userData'),+ modelsDir: getSettings(app.getPath('userData')).modelsDir,+ apiUrl: API_BASE_URL,+ platform: process.platform,+ arch: process.arch,+ }))++ // Settings — decrypt the HF token (migrating a legacy plaintext one) and seed+ // it into the main-process env at startup.+ {+ const token = initHfToken(app.getPath('userData'))+ if (token) {+ process.env['HUGGING_FACE_HUB_TOKEN'] = token+ process.env['HF_TOKEN'] = token+ }+ }++ ipcMain.handle('settings:get', () => {+ // hfToken is stored encrypted — hand the renderer the usable value.+ return { ...getSettings(app.getPath('userData')), hfToken: getHfToken() }+ })++ ipcMain.handle('settings:set', async (_event, patch: { modelsDir?: string; workspaceDir?: string; extensionsDir?: string; hfToken?: string }) => {+ if (patch.modelsDir !== undefined && weightOperations.busy) {+ throw new Error('Cannot change model storage while model weights are busy')+ }+ const { hfToken, ...dirs } = patch+ setSettings(app.getPath('userData'), dirs)+ // Keep main-process env in sync so child processes spawned after token change inherit it+ if (hfToken !== undefined) {+ setHfToken(app.getPath('userData'), hfToken)+ process.env['HUGGING_FACE_HUB_TOKEN'] = hfToken+ process.env['HF_TOKEN'] = hfToken+ // Also push the token into the live FastAPI process env so extension+ // subprocesses spawned by ExtensionProcess._build_env() pick it up+ // without requiring a full app restart.+ try {+ await axios.post(`${API_BASE_URL}/settings/hf-token`, { token: hfToken }, { timeout: 3000 })+ } catch { /* FastAPI may not be running yet — ignore */ }+ }+ return { ...getSettings(app.getPath('userData')), hfToken: getHfToken() }+ })++ // Directory picker+ ipcMain.handle('fs:selectDirectory', async (_event, defaultPath?: string) => {+ const win = getWindow()+ if (!win) return null+ const result = await dialog.showOpenDialog(win, {+ properties: ['openDirectory', 'createDirectory'],+ ...(defaultPath && { defaultPath }),+ })+ return result.canceled ? null : result.filePaths[0]+ })++ // Cache clear — deletes and recreates the gen-cache folder+ // NOTE: userData/cache (lowercase) = Chromium disk cache on Windows (case-insensitive)+ // → use a dedicated subfolder to avoid collision+ ipcMain.handle('cache:clear', async () => {+ const cacheDir = join(app.getPath('userData'), 'gen-cache')+ try {+ if (existsSync(cacheDir)) {+ await rmAsync(cacheDir, { recursive: true, force: true })+ }+ await mkdir(cacheDir, { recursive: true })+ return { success: true }+ } catch (err) {+ console.error('[cache:clear] error:', err)+ return { success: false, error: String(err) }+ }+ })++ // Workspace filesystem-based persistence+ const workspacePath = (...parts: string[]) =>+ join(getSettings(app.getPath('userData')).workspaceDir, ...parts)++ registerWorkspaceAssetLibraryIpcHandlers({+ ipcMain,+ getWorkspaceDir: () => getSettings(app.getPath('userData')).workspaceDir,+ })++ ipcMain.handle('workspace:listCollections', async () => {+ const base = workspacePath()+ await mkdir(base, { recursive: true })+ const entries = await readdir(base, { withFileTypes: true })+ return entries.filter(e => e.isDirectory()).map(e => e.name)+ })++ ipcMain.handle('workspace:createCollection', async (_, name: string) => {+ await mkdir(workspacePath(name), { recursive: true })+ })++ ipcMain.handle('workspace:renameCollection', async (_, { oldName, newName }: { oldName: string; newName: string }) => {+ await rename(workspacePath(oldName), workspacePath(newName))+ })++ ipcMain.handle('workspace:deleteCollection', async (_, name: string) => {+ await rmAsync(workspacePath(name), { recursive: true, force: true })+ })++ ipcMain.handle('workspace:listJobs', async (_, collection: string) => {+ try {+ const files = await readdir(workspacePath(collection))+ const metas = files.filter(f => f.endsWith('.meta.json'))+ return Promise.all(metas.map(async f => {+ const raw = await readFile(workspacePath(collection, f), 'utf-8')+ return JSON.parse(raw)+ }))+ } catch { return [] }+ })++ ipcMain.handle('workspace:saveJobMeta', async (_, { collection, filename, meta }: { collection: string; filename: string; meta: unknown }) => {+ const metaFile = filename.replace(/\.glb$/, '.meta.json')+ await writeFile(workspacePath(collection, metaFile), JSON.stringify(meta, null, 2), 'utf-8')+ })++ ipcMain.handle('workspace:deleteJob', async (_, { collection, filename }: { collection: string; filename: string }) => {+ await rmAsync(workspacePath(collection, filename), { force: true })+ await rmAsync(workspacePath(collection, filename.replace(/\.glb$/, '.meta.json')), { force: true })+ })++ // Directory utilities for settings+ ipcMain.handle('fs:listDir', async (_, dirPath: string) => {+ try {+ const entries = await readdir(dirPath, { withFileTypes: true })+ return entries.filter(e => e.isDirectory()).map(e => e.name)+ } catch {+ return []+ }+ })++ // List files (not directories) in a folder, optionally filtered by extension.+ // `extensions` are lowercase without the dot (e.g. ['txt', 'png']).+ ipcMain.handle('fs:listFiles', async (_, dirPath: string, extensions?: string[]) => {+ try {+ const wanted = extensions?.map(e => e.toLowerCase().replace(/^\./, ''))+ const entries = await readdir(dirPath, { withFileTypes: true })+ return entries+ .filter(e => e.isFile())+ .map(e => e.name)+ .filter(name => {+ if (!wanted || wanted.length === 0) return true+ const ext = name.split('.').pop()?.toLowerCase() ?? ''+ return wanted.includes(ext)+ })+ .sort((a, b) => a.localeCompare(b, undefined, { numeric: true }))+ } catch {+ return []+ }+ })++ // Text-file picker for the standalone Load Prompt node.+ ipcMain.handle('fs:selectTextFile', async () => {+ const win = getWindow()+ if (!win) return null+ const result = await dialog.showOpenDialog(win, {+ title: 'Select a prompt text file',+ filters: [{ name: 'Text', extensions: ['txt', 'md', 'prompt'] }],+ properties: ['openFile'],+ })+ return result.canceled ? null : result.filePaths[0]+ })++ // Add a local GGUF to the agent's models folder. Picking and copying both+ // happen here, so the renderer never hands main an arbitrary path to copy.+ ipcMain.handle('agent:addModel', async (): Promise<{ success: boolean; cancelled?: boolean; fileName?: string; error?: string }> => {+ const win = getWindow()+ if (!win) return { success: false, error: 'No window available' }+ const result = await dialog.showOpenDialog(win, {+ title: 'Add a model',+ filters: [{ name: 'GGUF model', extensions: ['gguf'] }],+ properties: ['openFile'],+ })+ if (result.canceled || !result.filePaths[0]) return { success: false, cancelled: true }++ const src = result.filePaths[0]+ const fileName = basename(src)+ if (!fileName.toLowerCase().endsWith('.gguf')) return { success: false, error: 'Only .gguf files can be added.' }++ const modelsDir = join(getSettings(app.getPath('userData')).agentDir, 'models')+ const dest = join(modelsDir, fileName)+ if (existsSync(dest)) return { success: false, error: `"${fileName}" is already in your models.` }++ // Copied under a temporary name first: the API lists every *.gguf in the+ // folder, so a multi-GB copy in progress would otherwise show up as a model.+ const partial = `${dest}.part`+ try {+ await mkdir(modelsDir, { recursive: true })+ await copyFile(src, partial)+ await rename(partial, dest)+ return { success: true, fileName }+ } catch (err) {+ await rmAsync(partial, { force: true }).catch(() => {})+ return { success: false, error: String(err) }+ }+ })++ ipcMain.handle('fs:moveDirectory', async (_, { src, dest }: { src: string; dest: string }) => {+ try {+ await mkdir(dest, { recursive: true })+ await cp(src, dest, { recursive: true })+ await rmAsync(src, { recursive: true, force: true })+ return { success: true }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ ipcMain.handle('fs:deleteDirectory', async (_, dirPath: string) => {+ const userData = app.getPath('userData')+ const settings = getSettings(userData)+ const allowedRoots = [+ settings.modelsDir,+ settings.workspaceDir,+ settings.extensionsDir,+ join(userData, 'gen-cache'),+ ]+ const resolved = join(dirPath)+ const isAllowed = allowedRoots.some((root) => resolved.startsWith(root))+ if (!isAllowed) {+ return { success: false, error: 'Path is outside allowed directories' }+ }+ try {+ await rmAsync(resolved, { recursive: true, force: true })+ return { success: true }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ // Remote registry — list of trusted GitHub repo URLs+ const REGISTRY_URL = 'https://raw.githubusercontent.com/lightningpixel/modly-official-extension/main/registry.json'+ const REGISTRY_TTL = 5 * 60 * 1000 // 5 minutes++ let registryCache: { repos: Set<string>; fetchedAt: number } | null = null++ async function fetchTrustedRepos(): Promise<Set<string>> {+ const now = Date.now()+ if (registryCache && now - registryCache.fetchedAt < REGISTRY_TTL) {+ return registryCache.repos+ }+ try {+ const { net } = require('electron')+ const res = await net.fetch(REGISTRY_URL)+ if (!res.ok) throw new Error(`HTTP ${res.status}`)+ const data = await res.json() as { trusted_repos?: string[] }+ const repos = new Set(+ (data.trusted_repos ?? []).map((r: string) => r.toLowerCase().replace(/\/$/, ''))+ )+ registryCache = { repos, fetchedAt: now }+ return repos+ } catch {+ // Offline or fetch failed — keep previous cache, or empty+ return registryCache?.repos ?? new Set()+ }+ }++ function isTrustedSource(source: string | undefined, trustedRepos: Set<string>): boolean {+ if (!source) return false+ return trustedRepos.has(source.toLowerCase().replace(/\/$/, ''))+ }++ type ParsedManifest = {+ id?: string; name?: string; displayName?: string; version?: string+ description?: string; author?: string | { name?: string }+ source?: string; generator_class?: string+ // extension type+ type?: 'model' | 'process'+ entry?: string+ model_sources?: unknown+ weight_groups?: unknown+ // Optional top-level fallbacks — applied to each node if not set on the node+ params_schema?: unknown[]+ param_defaults?: Record<string, unknown>+ nodes?: {+ id: string+ name?: string+ input?: string+ inputs?: string[]+ input_labels?: string[]+ output?: string+ params_schema?: unknown[]+ param_defaults?: Record<string, unknown>+ hf_repo?: string+ download_check?: string+ hf_skip_prefixes?: string[]+ hf_include_prefixes?: string[]+ model_sources?: unknown+ weight_groups?: unknown+ weight_variants?: unknown+ }[]+ }++ function parseExtensionManifest(parsed: ParsedManifest, fallbackId: string, trustedRepos: Set<string>, builtin = false) {+ const common = {+ id: parsed.id ?? fallbackId,+ name: parsed.displayName ?? parsed.name ?? fallbackId,+ version: parsed.version,+ description: parsed.description,+ author: typeof parsed.author === 'string' ? parsed.author : parsed.author?.name,+ trusted: builtin || isTrustedSource(parsed.source, trustedRepos),+ source: parsed.source,+ builtin,+ }++ if (parsed.model_sources !== undefined) {+ throw new Error('manifest.json: model_sources must be declared on a model node')+ }+ if (parsed.type === 'process' && parsed.weight_groups !== undefined) {+ throw new Error('manifest.json: weight_groups is supported only for model extensions')+ }+ const weightGroups = normalizeWeightGroups(parsed)+ if (weightGroups || parsed.nodes?.some((node) => node.model_sources !== undefined || node.weight_groups !== undefined)) {+ validateModelNodeIds(parsed.nodes ?? [])+ }+ const nodes = (parsed.nodes ?? []).map(n => {+ const declaredInputs = Array.isArray(n.inputs) ? n.inputs : [n.input ?? 'image']+ const output = n.output ?? 'mesh'+ assertSupportedSceneNodeShape(parsed.type === 'process' ? 'process' : 'model', n, declaredInputs, output)+ const usesManagedWeights = weightGroups !== undefined+ || n.model_sources !== undefined+ || n.weight_groups !== undefined+ if (weightGroups !== undefined && typeof n.id === 'string' && n.id.toLowerCase() === '_shared') {+ throw new Error('manifest.json: model node id "_shared" is reserved')+ }+ const nodeId = usesManagedWeights ? safeModelSourceId(n.id, 'model node id') : n.id+ if (parsed.type === 'process' && (n.model_sources !== undefined || n.weight_groups !== undefined)) {+ throw new Error('manifest.json: model_sources and weight_groups are supported only for model nodes')+ }+ if (parsed.type === 'process' && n.weight_variants !== undefined) {+ throw new Error('manifest.json: weight_variants is supported only for model nodes')+ }+ const modelSources = normalizeModelSources(n)+ const weightVariants = normalizeWeightVariants(n, n.params_schema ?? parsed.params_schema)+ const groupRefs = normalizeWeightGroupReferences(+ n,+ weightGroups,+ `nodes[${n.id}].weight_groups`,+ )+ if (groupRefs && n.hf_repo !== undefined) {+ throw new Error(+ `manifest.json: model node "${nodeId}" must use model_sources for private weights when weight_groups are declared`,+ )+ }+ return {+ id: nodeId,+ name: n.name ?? n.id,+ input: n.input ?? 'image' as const,+ inputs: n.inputs,+ inputLabels: n.input_labels,+ output: n.output ?? 'mesh' as const,+ paramsSchema: n.params_schema ?? parsed.params_schema ?? [],+ paramDefaults: { ...(parsed.param_defaults ?? {}), ...(n.param_defaults ?? {}) },+ hfRepo: n.hf_repo,+ downloadCheck: n.download_check,+ hfSkipPrefixes: n.hf_skip_prefixes,+ hfIncludePrefixes: n.hf_include_prefixes,+ hasModelSources: modelSources !== undefined,+ weightGroups: groupRefs,+ weightVariants: weightVariants && {+ param: weightVariants.param,+ default: weightVariants.default,+ options: weightVariants.options.map((option) => ({+ id: option.id,+ label: option.label,+ sizeGb: option.size_gb,+ vramGb: option.vram_gb,+ })),+ },+ }+ })++ if (parsed.type === 'process') {+ return { ...common, type: 'process' as const, entry: parsed.entry ?? 'processor.js', nodes }+ }++ return {+ ...common,+ type: 'model' as const,+ nodes,+ weightGroups: (weightGroups ?? []).map((group) => ({+ id: group.id,+ dependentNodeIds: nodes+ .filter((node) => node.weightGroups?.includes(group.id))+ .map((node) => node.id),+ })),+ }+ }++ async function reloadAndValidateModelExtension(+ manifest: ParsedManifest,+ extensionId: string,+ validationCapability?: ExtensionRegistrationValidationCapability,+ ): Promise<void> {+ const expectedIds = expectedModelIds({ ...manifest, id: extensionId })+ if (expectedIds.length === 0) return++ let payload: unknown+ try {+ const response = await axios.post(+ `${API_BASE_URL}/extensions/reload`,+ validationCapability ? { validationCapability } : {},+ { timeout: 10_000 },+ )+ payload = response.data+ } catch (err) {+ throw new Error(+ `Could not validate runtime registration for extension "${extensionId}": ${String(err)}`,+ )+ }+ validateExtensionReloadPayload(payload, extensionId, expectedIds)+ }++ async function quarantineModelExtensionRuntime(+ manifest: ParsedManifest,+ extensionId: string,+ ): Promise<void> {+ const forbiddenIds = expectedModelIds({ ...manifest, id: extensionId })+ if (forbiddenIds.length === 0) return++ let payload: unknown+ try {+ const response = await axios.post(+ `${API_BASE_URL}/extensions/reload`,+ {},+ { timeout: 10_000 },+ )+ payload = response.data+ } catch (err) {+ throw new Error(+ `Could not quarantine runtime registration for extension "${extensionId}": `+ + `${String(err)}`,+ )+ }+ validateExtensionQuarantinePayload(payload, extensionId, forbiddenIds)+ }++ async function rollbackFailedExtensionUpdate(+ extensionsDir: string,+ destinationDir: string,+ backupDir: string,+ extensionId: string,+ originalFailure: unknown,+ ): Promise<never> {+ const restored = await restoreExtensionBackup(destinationDir, backupDir, logger)+ if (!restored.ok) {+ throw new Error(+ `Extension update failed, and Modly could not restore the previous version `+ + `during ${restored.stage}: ${String(restored.error)}. `+ + `Restart Modly to retry recovery. Original failure: ${String(originalFailure)}`,+ )+ }++ const stateCleared = await clearExtensionRegistrationTransaction(+ extensionsDir,+ extensionId,+ logger,+ )+ if (!stateCleared.ok) {+ throw new Error(+ `Extension update failed and the previous version was restored, but Modly `+ + `could not clear recovery state during ${stateCleared.stage}: `+ + `${String(stateCleared.error)}. Original failure: ${String(originalFailure)}`,+ )+ }++ try {+ const previousManifest = JSON.parse(+ await readFile(join(destinationDir, 'manifest.json'), 'utf-8'),+ ) as ParsedManifest+ if (previousManifest.type !== 'process') {+ await reloadAndValidateModelExtension(previousManifest, extensionId)+ }+ } catch (reloadError) {+ throw new Error(+ `Extension update failed and the previous version was restored on disk, `+ + `but Modly could not reload it: ${String(reloadError)}. `+ + `Original failure: ${String(originalFailure)}`,+ )+ }++ throw new Error(+ `Extension update failed before runtime registration could be committed, `+ + `so the previous version was restored. `+ + `${String(originalFailure)}`,+ )+ }++ async function cleanupValidatedBackupsOrThrow(+ extensionsDir: string,+ extensionId: string,+ ): Promise<void> {+ const cleaned = await cleanupValidatedExtensionBackups(extensionsDir, extensionId, logger)+ if (!cleaned.ok) {+ throw new Error(+ `Runtime registration succeeded, but Modly could not finish removing the previous `+ + `extension backup during ${cleaned.stage}: ${String(cleaned.error)}. `+ + `Restart Modly to retry the validated cleanup.`,+ )+ }+ }++ // Extensions — reads user extensions directory + built-in extensions directory+ ipcMain.handle('extensions:list', async () => {+ const userData = app.getPath('userData')+ const extensionsDir = getSettings(userData).extensionsDir+ const builtinDir = getBuiltinExtensionsDir()++ const trustedRepos = await fetchTrustedRepos()++ async function readExtensionsFromDir(dir: string, isBuiltin: boolean) {+ if (!existsSync(dir)) return []+ try {+ const entries = await readdir(dir, { withFileTypes: true })+ const pendingRegistrationIds = new Set(+ isBuiltin+ ? []+ : entries+ .map((entry) => parseExtensionRegistrationPendingName(entry.name)?.extensionId)+ .filter((extensionId): extensionId is string => Boolean(extensionId)),+ )+ // On Windows, junction points are reported by Node.js as isSymbolicLink()=true,+ // isDirectory()=false. Use statSync (which follows links) as the authoritative check.+ const dirs = entries.filter(e => {+ // Staging/backup dirs are never extensions (ids can't start with '.')+ if (isInternalExtensionDirName(e.name)) return false+ if (e.isDirectory()) return true+ if (e.isSymbolicLink()) {+ try { return statSync(join(dir, e.name)).isDirectory() } catch { return false }+ }+ return false+ })+ const results = await Promise.all(dirs.map(async (entry) => {+ const entryPath = join(dir, entry.name)+ const skeleton = { type: 'model' as const, id: entry.name, name: entry.name, trusted: isBuiltin, builtin: isBuiltin, nodes: [], corrupted: true }++ // A setup/registration marker still present means this folder is not+ // safe to expose. Hide it only while the current install owns it;+ // after a failed startup recovery, surface it as Repairable instead.+ const installInterrupted = (+ existsSync(join(entryPath, EXT_INCOMPLETE_MARKER))+ || existsSync(join(entryPath, EXT_REGISTRATION_PENDING_MARKER))+ || pendingRegistrationIds.has(entry.name)+ )+ if (installInterrupted && activeExtensionInstalls.has(entry.name)) return null++ // Detect local extensions: check for .modly-local sentinel+ let localSourcePath: string | undefined+ if (!isBuiltin) {+ const sentinelPath = join(entryPath, '.modly-local')+ if (existsSync(sentinelPath)) {+ try {+ localSourcePath = (await readFile(sentinelPath, 'utf-8')).trim()+ } catch { /* ignore */ }+ }+ }++ // 'missing' = no manifest at all (gutted folder); 'invalid' = a manifest+ // exists but doesn't parse (fixable by hand, don't push deletion only)+ let manifestError: 'missing' | 'invalid' = 'missing'+ for (const manifestFile of ['manifest.json', 'package.json']) {+ const p = join(entryPath, manifestFile)+ if (existsSync(p)) {+ try {+ const raw = await readFile(p, 'utf-8')+ const parsed = JSON.parse(raw) as ParsedManifest+ // Inject local:// source so the UI shows the Local badge+ if (localSourcePath) parsed.source = `local://${localSourcePath}`+ const extension = parseExtensionManifest(+ parsed,+ entry.name,+ trustedRepos,+ isBuiltin,+ )+ return markExtensionInstallationInterrupted(extension, installInterrupted)+ } catch { manifestError = 'invalid' }+ }+ }+ return installInterrupted+ ? markExtensionInstallationInterrupted(skeleton, true)+ : { ...skeleton, manifestError }+ }))+ return results.filter((e): e is Exclude<typeof e, null> => e !== null)+ } catch {+ return []+ }+ }++ const [userExts, builtinExts] = await Promise.all([+ readExtensionsFromDir(extensionsDir, false),+ readExtensionsFromDir(builtinDir, true),+ ])++ // Built-ins come first, then user extensions+ return [...builtinExts, ...userExts]+ })++ // Install an extension from a GitHub repo URL+ ipcMain.handle('extensions:installFromGitHub', async (event, githubUrl: string) => {+ const win = getWindow()+ const emit = (data: object) => win?.webContents.send('extensions:installProgress', data)+ const tmpDir = app.getPath('temp')++ let tarPath = ''+ let extractDir = ''+ let trackedExtensionId = ''++ try {+ // 1. Parse and validate GitHub URL+ const parsed = new URL(githubUrl.trim())+ if (parsed.hostname !== 'github.com') throw new Error('Invalid URL: must be a GitHub repository (github.com)')+ const parts = parsed.pathname.split('/').filter(Boolean)+ if (parts.length < 2) throw new Error('Invalid URL: expected format https://github.com/owner/repo')+ const [owner, repo] = parts++ emit({ step: 'downloading', percent: 0 })++ // 2. Download tarball via GitHub API+ const tarballUrl = `https://api.github.com/repos/${owner}/${repo}/tarball/HEAD`+ tarPath = join(tmpDir, `modly-ext-${Date.now()}.tar.gz`)+ extractDir = join(tmpDir, `modly-ext-extract-${Date.now()}`)++ const response = await axios.get(tarballUrl, {+ responseType: 'arraybuffer',+ headers: {+ 'Accept': 'application/vnd.github.v3+json',+ 'User-Agent': 'Modly-App',+ },+ onDownloadProgress: (evt) => {+ const pct = evt.total ? Math.round((evt.loaded / evt.total) * 80) : 40+ emit({ step: 'downloading', percent: pct })+ },+ })++ await writeFile(tarPath, Buffer.from(response.data as ArrayBuffer))++ // 3. Extract tarball (GitHub wraps contents in a top-level {owner}-{repo}-{sha}/ folder)+ emit({ step: 'extracting' })+ await mkdir(extractDir, { recursive: true })+ await tar.x({ file: tarPath, cwd: extractDir, strip: 1 })++ // 4. Validate manifest.json+ emit({ step: 'validating' })+ const manifestPath = join(extractDir, 'manifest.json')++ if (!existsSync(manifestPath)) throw new Error('manifest.json missing from repository')++ const manifestRaw = await readFile(manifestPath, 'utf-8')+ const manifest = JSON.parse(manifestRaw) as ParsedManifest++ const { id: rawManifestId, isProcess, entryFile, isPythonProcess, hasNodes } = validateInstallManifest(+ manifest,+ {+ hasEntryFile: (candidate) => existsSync(join(extractDir, candidate)),+ hasGeneratorFile: () => existsSync(join(extractDir, 'generator.py')),+ },+ 'repository',+ )+ if (!hasNodes) throw new Error('manifest.json: required field "nodes" missing or empty')+ const extensionId = assertSafeExtensionId(rawManifestId)+ manifest.id = extensionId+ trackedExtensionId = extensionId+ activeExtensionInstalls.add(extensionId)++ // Override source field with the actual GitHub URL so trust is based on origin+ manifest.source = `https://github.com/${owner}/${repo}`+ await writeFile(manifestPath, JSON.stringify(manifest, null, 2), 'utf-8')++ // 5. Stage into a fresh, unique dir next to the final location (so a new+ // attempt can never merge into leftovers of a previous one), mark it+ // incomplete, and swap it in with atomic renames BEFORE the long setup+ // phase. setup.py then runs in the final path — venvs record absolute+ // paths, so the folder must not move after setup. If anything dies+ // mid-way, the marker + backup let the startup reconciler put the+ // previous version back.+ const extensionsDir = getSettings(app.getPath('userData')).extensionsDir+ await mkdir(extensionsDir, { recursive: true })+ const installSuffix = String(Date.now())+ const destDir = resolveExtensionPathWithinRoot(extensionsDir, extensionId)+ const stagingDir = buildExtensionStagingPath(extensionsDir, extensionId, installSuffix)++ if (existsSync(destDir)) {+ const currentManifestPath = join(destDir, 'manifest.json')+ let currentManifestJson: string+ try {+ currentManifestJson = await readFile(currentManifestPath, 'utf-8')+ } catch (error) {+ throw new Error(+ `Cannot safely replace extension "${extensionId}" because its existing `+ + `manifest.json is missing or unreadable. Uninstall it first. ${String(error)}`,+ )+ }+ validateExistingExtensionReplacement(+ currentManifestJson,+ manifest,+ {+ hasEntryFile: (candidate) => existsSync(join(destDir, candidate)),+ hasGeneratorFile: () => existsSync(join(destDir, 'generator.py')),+ },+ 'existing extension folder',+ )+ }++ try {+ await cp(extractDir, stagingDir, { recursive: true })+ // Reserved recovery files are host-owned transaction state, never+ // repository content. Strip packaged/stale copies before activation.+ await rmAsync(+ join(stagingDir, EXT_REGISTRATION_PENDING_MARKER),+ { recursive: true, force: true },+ )+ await rmAsync(+ join(stagingDir, EXT_VALIDATED_MARKER),+ { recursive: true, force: true },+ )+ await writeFile(join(stagingDir, EXT_INCOMPLETE_MARKER), new Date().toISOString(), 'utf-8')++ // Compile TypeScript entry to JS at install time (once, no runtime overhead)+ if (isProcess && entryFile.endsWith('.ts')) {+ emit({ step: 'setting_up', message: 'Compiling TypeScript entry…' })+ const compiledEntry = entryFile.replace(/\.ts$/, '.js')+ buildSync({+ entryPoints: [join(stagingDir, entryFile)],+ outfile: join(stagingDir, compiledEntry),+ bundle: true,+ platform: 'node',+ format: 'cjs',+ external: ['electron'],+ })+ manifest.entry = compiledEntry+ await writeFile(join(stagingDir, 'manifest.json'), JSON.stringify(manifest, null, 2), 'utf-8')+ }+ } catch (stageErr) {+ await rmWithRetry(stagingDir, 'ext-install')+ throw stageErr+ }++ // 6. Swap into place (backup the previous version first)+ terminateProcessRunner(extensionId)+ const backupDir = existsSync(destDir)+ ? buildExtensionBackupPath(extensionsDir, extensionId, installSuffix)+ : null+ if (backupDir) {+ const parked = await renameWithRetry(destDir, backupDir, 'ext-install')+ if (!parked.ok) {+ await rmWithRetry(stagingDir, 'ext-install')+ throw new Error('The current extension folder is locked (antivirus or a running process) — close what might be using it and try again.')+ }+ }+ const activated = await renameWithRetry(stagingDir, destDir, 'ext-install')+ if (!activated.ok) {+ await rmWithRetry(stagingDir, 'ext-install')+ if (backupDir) await renameWithRetry(backupDir, destDir, 'ext-install')+ throw new Error('Could not move the staged extension into place — the folder is locked. Try again.')+ }++ // Persist transaction state beside extension folders, never inside a+ // destination or backup that may be a symlink to developer source.+ const pending = await beginExtensionRegistrationTransaction(+ extensionsDir,+ extensionId,+ installSuffix,+ logger,+ )+ if (!pending.ok) {+ if (backupDir) {+ await rollbackFailedExtensionUpdate(+ extensionsDir,+ destDir,+ backupDir,+ extensionId,+ `Could not mark the update as pending: ${String(pending.error)}`,+ )+ } else {+ await rmWithRetry(destDir, 'ext-install')+ }+ throw new Error(`Could not mark extension registration as pending: ${String(pending.error)}`)+ }++ // 7. Setup runs in the final folder; a failure restores the previous version+ try {+ if (isPythonProcess) {+ // 7a. Python process extension: run setup.py if present (same as model extensions)+ if (existsSync(join(destDir, 'setup.py'))) {+ emit({ step: 'setting_up', message: 'Setting up Python environment…' })+ const gpu = await detectGpuInfo({ onLog: (line) => logger.info(line) })+ logger.info(`[ext-setup] ${describeGpuInfo(gpu)}`)+ await runExtensionSetup(destDir, gpu, (line) => {+ logger.info(`[ext-setup] ${line}`)+ emit({ step: 'setting_up', message: line })+ })+ }+ } else if (isProcess) {+ // 7b. JS process extension: npm install if package.json present+ if (existsSync(join(destDir, 'package.json'))) {+ emit({ step: 'setting_up', message: 'Installing dependencies…' })+ await new Promise<void>((resolve, reject) => {+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'+ const child = spawn(npm, ['install', '--omit=dev', '--no-audit', '--no-fund', '--ignore-scripts=false'], {+ cwd: destDir,+ stdio: 'pipe',+ })+ let buf = ''+ const onData = (chunk: Buffer) => {+ buf += chunk.toString()+ const lines = buf.split('\n')+ buf = lines.pop() ?? ''+ for (const raw of lines) {+ const line = raw.replace(/\x1b\[[0-9;]*m/g, '').trim()+ if (line) emit({ step: 'setting_up', message: line })+ }+ }+ child.stdout?.on('data', onData)+ child.stderr?.on('data', onData)+ child.on('close', (code) => code === 0 ? resolve() : reject(new Error(`npm install failed (exit ${code})`)))+ child.on('error', reject)+ })+ }+ } else {+ // 7c. Model extension: run setup.py directly (no FastAPI required)+ if (existsSync(join(destDir, 'setup.py'))) {+ emit({ step: 'setting_up', message: 'Setting up Python environment…' })+ const gpu = await detectGpuInfo({ onLog: (line) => logger.info(line) })+ logger.info(`[ext-setup] ${describeGpuInfo(gpu)}`)+ await runExtensionSetup(destDir, gpu, (line) => {+ logger.info(`[ext-setup] ${line}`)+ emit({ step: 'setting_up', message: line })+ })+ }+ }+ } catch (setupErr) {+ // Discard the half-set-up folder and put the previous version back. If+ // the folder is locked, the marker keeps it flagged corrupted and the+ // startup reconciler restores the backup on next launch.+ if (backupDir) {+ const restored = await restoreExtensionBackup(destDir, backupDir, logger)+ if (!restored.ok) {+ throw new Error(+ `Extension setup failed, and Modly could not restore the previous version `+ + `during ${restored.stage}: ${String(restored.error)}. `+ + `Restart Modly to retry recovery. Original failure: ${String(setupErr)}`,+ )+ }+ const cleared = await clearExtensionRegistrationTransaction(+ extensionsDir,+ extensionId,+ logger,+ )+ if (!cleared.ok) {+ throw new Error(+ `Extension setup failed and the previous version was restored, but Modly `+ + `could not clear recovery state during ${cleared.stage}: ${String(cleared.error)}.`,+ )+ }+ } else {+ const removed = await rmWithRetry(destDir, 'ext-install')+ if (removed.ok) {+ const cleared = await clearExtensionRegistrationTransaction(+ extensionsDir,+ extensionId,+ logger,+ )+ if (!cleared.ok) {+ throw new Error(+ `Extension setup failed and its incomplete folder was removed, but Modly `+ + `could not clear recovery state during ${cleared.stage}: ${String(cleared.error)}.`,+ )+ }+ }+ }+ throw setupErr+ }++ // 8. Setup succeeded. Root-level transaction state remains pending while+ // the new destination is explicitly validated. A crash or failure in+ // this window restores a backup or quarantines a fresh destination.+ try {+ await validateExtensionDestinationRegistration(+ destDir,+ async () => {+ if (!isProcess) {+ await reloadAndValidateModelExtension(+ manifest,+ extensionId,+ pending.validationCapability,+ )+ }+ },+ 'ext-install',+ logger,+ )+ } catch (registrationError) {+ if (backupDir) {+ await rollbackFailedExtensionUpdate(+ extensionsDir,+ destDir,+ backupDir,+ extensionId,+ registrationError,+ )+ } else {+ const quarantined = await quarantineExtensionRegistrationFailure(+ extensionsDir,+ extensionId,+ logger,+ )+ if (!quarantined.ok) {+ throw new Error(+ `Runtime registration failed, and Modly could not quarantine the extension `+ + `during ${quarantined.stage}: ${String(quarantined.error)}. `+ + `Restart Modly to retry recovery. Original failure: ${String(registrationError)}`,+ )+ }+ if (!isProcess) {+ try {+ await quarantineModelExtensionRuntime(manifest, extensionId)+ } catch (runtimeQuarantineError) {+ throw new Error(+ `Runtime registration failed and filesystem quarantine was preserved, `+ + `but Modly could not evict partially registered model state: `+ + `${String(runtimeQuarantineError)}. `+ + `Original failure: ${String(registrationError)}`,+ )+ }+ }+ }+ throw registrationError+ }++ // Runtime validation passed. Mark cleanup as validated before deleting+ // rollback copies so startup can safely retry an interrupted deletion.+ await cleanupValidatedBackupsOrThrow(extensionsDir, extensionId)++ emit({ step: 'done', extensionId })++ const trustedRepos = await fetchTrustedRepos()+ const ext = parseExtensionManifest(manifest, extensionId, trustedRepos)+ return { success: true, extensionId, extension: ext }++ } catch (err) {+ emit({ step: 'error', message: String(err) })+ return { success: false, error: String(err) }+ } finally {+ if (trackedExtensionId) activeExtensionInstalls.delete(trackedExtensionId)+ // Cleanup temp files+ if (tarPath && existsSync(tarPath)) rmAsync(tarPath, { force: true }).catch(() => {})+ if (extractDir && existsSync(extractDir)) rmAsync(extractDir, { recursive: true, force: true }).catch(() => {})+ }+ })++ // Uninstall an extension — built-ins cannot be uninstalled+ ipcMain.handle('extensions:uninstall', async (_, extensionId: string) => {+ try {+ if ([...activeDownloads.keys()].some((modelId) => modelId.split('/', 1)[0] === extensionId)) {+ return { success: false, error: 'Cannot uninstall an extension while its model download is active' }+ }+ // Corrupted folders can carry arbitrary names (manual copies, failed+ // unzips), so only enforce root confinement for the deletion path. The+ // strict id pattern still guards the built-in check — a non-conforming+ // name can never be a built-in.+ const extensionsDir = getSettings(app.getPath('userData')).extensionsDir++ try {+ const safeExtensionId = assertSafeExtensionId(extensionId)+ if (existsSync(resolveExtensionPathWithinRoot(getBuiltinExtensionsDir(), safeExtensionId))) {+ return { success: false, error: `"${safeExtensionId}" is a built-in extension and cannot be uninstalled.` }+ }+ } catch { /* non-conforming folder name → not a built-in */ }++ // Terminate process runner if it's a process extension+ terminateProcessRunner(extensionId)++ const removed = await removeExtensionWithBackups(+ extensionsDir,+ String(extensionId),+ logger,+ )+ if (!removed.ok) {+ return {+ success: false,+ error: removed.locked+ ? `Could not delete the extension ${removed.stage === 'backup' ? 'backup' : 'folder'} `+ + '— a file inside it is locked (antivirus or a running process). '+ + 'Close what might be using it and try again.'+ : `Could not uninstall the extension during ${removed.stage}: ${String(removed.error)}`,+ }+ }+ // Hot-reload Python so it stops using the deleted model extension+ try {+ await axios.post(`${API_BASE_URL}/extensions/reload`, {}, { timeout: 10_000 })+ } catch { /* ignore if Python is not running */ }+ return { success: true }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ // Re-run setup.py for a model extension (creates the venv if missing)+ ipcMain.handle('extensions:repair', async (_, extensionId: string) => {+ try {+ const safeExtensionId = assertSafeExtensionId(extensionId)+ const extensionsDir = getSettings(app.getPath('userData')).extensionsDir+ const extDir = resolveExtensionPathWithinRoot(extensionsDir, safeExtensionId)+ if (!existsSync(join(extDir, 'setup.py'))) {+ return { success: false, error: 'setup.py is missing from the extension folder — the install looks incomplete. Uninstall the extension and install it again.' }+ }+ const manifestRaw = await readFile(join(extDir, 'manifest.json'), 'utf-8')+ const manifest = JSON.parse(manifestRaw) as ParsedManifest+ const { isProcess } = validateInstallManifest(+ manifest,+ {+ hasEntryFile: (candidate) => existsSync(join(extDir, candidate)),+ hasGeneratorFile: () => existsSync(join(extDir, 'generator.py')),+ },+ 'extension folder',+ )+ const gpu = await detectGpuInfo({ onLog: (line) => logger.info(line) })+ logger.info(`[ext-repair] ${describeGpuInfo(gpu)}`)+ await runExtensionRepairTransaction(+ {+ extensionsDir,+ extensionId: safeExtensionId,+ destinationDir: extDir,+ suffix: String(Date.now()),+ quarantine: async () => {+ terminateProcessRunner(safeExtensionId)+ if (!isProcess) {+ await quarantineModelExtensionRuntime(manifest, safeExtensionId)+ }+ },+ setup: () => runExtensionSetup(+ extDir,+ gpu,+ (line) => logger.info(`[ext-repair] ${line}`),+ ),+ validate: async (validationCapability) => {+ if (!isProcess) {+ await reloadAndValidateModelExtension(+ manifest,+ safeExtensionId,+ validationCapability,+ )+ }+ },+ },+ logger,+ )+ return { success: true }+ } catch (err: any) {+ return { success: false, error: `Repair failed: ${err?.message ?? err}` }+ }+ })++ // Install a local extension by creating a symlink/junction to a local folder+ ipcMain.handle('extensions:installFromLocal', async () => {+ const win = getWindow()+ const emit = (data: object) => win?.webContents.send('extensions:installProgress', data)++ // 1. Open folder picker+ const pickResult = await dialog.showOpenDialog(win!, {+ title: 'Select local extension folder',+ properties: ['openDirectory'],+ })+ if (pickResult.canceled || pickResult.filePaths.length === 0) {+ return { success: false, cancelled: true }+ }+ const localPath = pickResult.filePaths[0]++ try {+ emit({ step: 'validating' })++ // 2. Read and validate manifest.json+ const manifestPath = join(localPath, 'manifest.json')+ if (!existsSync(manifestPath)) {+ throw new Error('manifest.json not found in the selected folder')+ }+ const manifestRaw = await readFile(manifestPath, 'utf-8')+ const manifest = JSON.parse(manifestRaw) as ParsedManifest++ const { id: rawManifestId, isProcess } = validateInstallManifest(+ manifest,+ {+ hasEntryFile: (candidate) => existsSync(join(localPath, candidate)),+ hasGeneratorFile: () => existsSync(join(localPath, 'generator.py')),+ },+ 'local folder',+ )+ const extensionId = assertSafeExtensionId(rawManifestId)++ // 3. Create symlink / junction in extensionsDir+ const userData = app.getPath('userData')+ const extensionsDir = getSettings(userData).extensionsDir+ await mkdir(extensionsDir, { recursive: true })++ const linkPath = resolveExtensionPathWithinRoot(extensionsDir, extensionId)+ const installSuffix = String(Date.now())+ let backupDir: string | null = null++ // Inspect an existing local link without mutating it. The host-side+ // pending transaction is created before the link is ever parked or+ // replaced, so a crash cannot expose the new target as validated.+ if (existsSync(linkPath)) {+ const currentManifestPath = join(linkPath, 'manifest.json')+ if (!existsSync(currentManifestPath)) {+ throw new Error(+ `Cannot safely replace local extension "${extensionId}" because its existing `+ + 'manifest.json is missing. Uninstall it first.',+ )+ }+ const currentManifest = JSON.parse(+ await readFile(currentManifestPath, 'utf-8'),+ ) as ParsedManifest+ assertCompatibleExtensionUpdateType(currentManifest, manifest)++ const linkStat = await lstat(linkPath)+ if (!linkStat.isSymbolicLink() && !(process.platform === 'win32' && linkStat.isDirectory())) {+ throw new Error(+ `A non-symlink folder named "${extensionId}" already exists in `+ + 'extensionsDir. Remove it first.',+ )+ }+ backupDir = buildExtensionBackupPath(extensionsDir, extensionId, installSuffix)+ }++ const trustedRepos = await fetchTrustedRepos()+ // Build manifest with localPath marker so the UI can identify local extensions+ const annotatedManifest = { ...manifest, source: `local://${localPath}` }+ const ext = parseExtensionManifest(annotatedManifest, extensionId, trustedRepos)++ try {+ await runExtensionRegistrationValidationTransaction(+ {+ extensionsDir,+ extensionId,+ suffix: installSuffix,+ quarantine: async () => {+ terminateProcessRunner(extensionId)+ if (!isProcess) {+ await quarantineModelExtensionRuntime(manifest, extensionId)+ }+ },+ activate: async () => {+ emit({ step: 'setting_up', message: 'Linking local folder…' })+ if (backupDir) {+ const parked = await renameWithRetry(linkPath, backupDir, 'ext-local')+ if (!parked.ok) {+ throw new Error(+ `Could not preserve the previous local extension: `+ + `${String(parked.error)}`,+ )+ }+ }++ if (process.platform === 'win32') {+ // Windows: junction (no elevation needed, works for directories)+ await symlink(localPath, linkPath, 'junction')+ } else {+ // macOS / Linux: standard symlink+ await symlink(localPath, linkPath)+ }++ // The sentinel lives in the linked source folder. Runtime+ // registration is still pending externally until validation.+ await writeFile(join(linkPath, '.modly-local'), localPath, 'utf-8')+ },+ validate: async (validationCapability) => {+ if (!isProcess) {+ await reloadAndValidateModelExtension(+ manifest,+ extensionId,+ validationCapability,+ )+ }+ },+ },+ logger,+ )+ } catch (err) {+ if (backupDir && existsSync(backupDir)) {+ await rollbackFailedExtensionUpdate(+ extensionsDir,+ linkPath,+ backupDir,+ extensionId,+ err,+ )+ }++ // Local links intentionally do not run setup. A fresh model that+ // cannot register remains linked, externally quarantined, and visible+ // only as a Repairable entry.+ if (!isProcess && existsSync(linkPath)) {+ const error = (+ `The local extension was linked, but it is not runtime-ready. `+ + `Click 'Repair' on its extension card, then retry. ${String(err)}`+ )+ emit({ step: 'error', extensionId, message: error })+ return {+ success: false,+ needsRepair: true,+ error,+ extensionId,+ extension: markExtensionInstallationInterrupted(ext, true),+ localPath,+ }+ }+ throw err+ }++ emit({ step: 'done', extensionId })+ return { success: true, extensionId, extension: ext, localPath }++ } catch (err) {+ emit({ step: 'error', message: String(err) })+ return { success: false, error: String(err) }+ }+ })++ // Trigger Python extension reload (without touching the filesystem)+ ipcMain.handle('extensions:reload', async () => {+ terminateAllProcessRunners()+ try {+ const res = await axios.post(`${API_BASE_URL}/extensions/reload`, {}, { timeout: 10_000 })+ return { success: true, errors: (res.data as { errors?: Record<string, string> }).errors ?? {} }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ // Run a process extension in an isolated worker thread+ ipcMain.handle('extensions:runProcess', async (_, extensionId: string, input: { filePath?: string; text?: string; texts?: (string | undefined)[]; nodeId?: string }, params: Record<string, unknown>) => {+ const userData = app.getPath('userData')+ const { extensionsDir, workspaceDir } = getSettings(userData)++ // Resolve extension directory: check built-ins first, then user extensions+ const builtinExtDir = join(getBuiltinExtensionsDir(), extensionId)+ const userExtDir = join(extensionsDir, extensionId)+ const extDir = existsSync(builtinExtDir) ? builtinExtDir : userExtDir++ if (!existsSync(extDir)) return { success: false, error: `Extension "${extensionId}" not found` }++ try {+ const manifestRaw = await readFile(join(extDir, 'manifest.json'), 'utf-8')+ const manifest = JSON.parse(manifestRaw) as ParsedManifest+ if (manifest.type !== 'process') return { success: false, error: `Extension "${extensionId}" is not a process extension` }++ const entry = manifest.entry ?? 'processor.js'+ const isPythonEntry = entry.endsWith('.py')+ const userData = app.getPath('userData')++ let runner+ if (isPythonEntry) {+ const pythonExe = getExtPythonExe(extDir) ?? getVenvPythonExe(userData)+ runner = getPythonProcessRunner(extensionId, pythonExe, extDir, entry, workspaceDir, app.getPath('temp'))+ } else {+ runner = getProcessRunner(extensionId, extDir, entry, workspaceDir, app.getPath('temp'))+ }++ const result = await runner.run(input, params)+ return { success: true, result }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ // Terminate all process runners on app quit+ app.on('before-quit', () => terminateAllProcessRunners())++ // Auto-updater+ ipcMain.handle('updater:check', async () => {+ if (!app.isPackaged || !updatesSupported) return { success: false }+ try {+ await autoUpdater.checkForUpdates()+ return { success: true }+ } catch (err) {+ logger.error(`[updater:check] ${err}`)+ return { success: false }+ }+ })++ ipcMain.handle('updater:quitAndInstall', () => {+ if (!updatesSupported) return+ app.removeAllListeners('window-all-closed')+ BrowserWindow.getAllWindows().forEach(w => w.destroy())+ autoUpdater.quitAndInstall(true, true)+ })++ // Update FastAPI paths at runtime (without restarting)+ ipcMain.handle('api:updatePaths', async (_event, patch: { modelsDir?: string; workspaceDir?: string; extensionsDir?: string }) => {+ try {+ if (patch.modelsDir !== undefined && weightOperations.busy) {+ throw new Error('Cannot change model storage while model weights are busy')+ }+ await axios.post(`${API_BASE_URL}/settings/paths`, {+ models_dir: patch.modelsDir,+ workspace_dir: patch.workspaceDir,+ extensions_dir: patch.extensionsDir,+ })+ return { success: true }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ // ── Workflows ────────────────────────────────────────────────────────────++ function workflowsDir(): string {+ const dir = getSettings(app.getPath('userData')).workflowsDir+ if (!existsSync(dir)) require('fs').mkdirSync(dir, { recursive: true })+ return dir+ }++ ipcMain.handle('workflows:list', async () => {+ const dir = workflowsDir()+ const files = readdirSync(dir).filter(f => f.endsWith('.json'))+ const workflows = []+ for (const file of files) {+ try {+ const raw = await readFile(join(dir, file), 'utf-8')+ workflows.push(JSON.parse(raw))+ } catch { /* skip corrupted files */ }+ }+ return workflows.sort((a: { updatedAt?: string }, b: { updatedAt?: string }) =>+ (b.updatedAt ?? '').localeCompare(a.updatedAt ?? '')+ )+ })++ ipcMain.handle('workflows:save', async (_, workflow: { id: string; [key: string]: unknown }) => {+ try {+ const path = join(workflowsDir(), `${workflow.id}.json`)+ await writeFile(path, JSON.stringify(workflow, null, 2), 'utf-8')+ return { success: true }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ ipcMain.handle('workflows:delete', async (_, id: string) => {+ try {+ await rmAsync(join(workflowsDir(), `${id}.json`), { force: true })+ return { success: true }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ ipcMain.handle('workflows:import', async () => {+ const win = getWindow()+ const result = await dialog.showOpenDialog(win!, {+ title: 'Import Workflow',+ filters: [{ name: 'Workflow', extensions: ['json'] }],+ properties: ['openFile'],+ })+ if (result.canceled || result.filePaths.length === 0) return { success: false }+ try {+ const raw = await readFile(result.filePaths[0], 'utf-8')+ const workflow = JSON.parse(raw)+ if (!workflow.id || !workflow.nodes) return { success: false, error: 'Invalid workflow file' }+ await writeFile(join(workflowsDir(), `${workflow.id}.json`), JSON.stringify(workflow, null, 2), 'utf-8')+ return { success: true, workflow }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })++ ipcMain.handle('workflows:export', async (_, workflow: { id: string; name?: string; [key: string]: unknown }) => {+ const win = getWindow()+ const result = await dialog.showSaveDialog(win!, {+ title: 'Export Workflow',+ defaultPath: `${workflow.name ?? workflow.id}.json`,+ filters: [{ name: 'Workflow', extensions: ['json'] }],+ })+ if (result.canceled || !result.filePath) return { success: false }+ try {+ await writeFile(result.filePath, JSON.stringify(workflow, null, 2), 'utf-8')+ return { success: true }+ } catch (err) {+ return { success: false, error: String(err) }+ }+ })+}diff --git a/apps/forge-desktop/electron/main/logger.ts b/apps/forge-desktop/electron/main/logger.tsnew file mode 100644index 000000000..a85c855fc--- /dev/null+++ b/apps/forge-desktop/electron/main/logger.ts@@ -0,0 +1,69 @@+import { app } from 'electron'+import { appendFileSync, mkdirSync, existsSync, readdirSync, statSync, renameSync, rmSync } from 'fs'+import { join } from 'path'++const MAX_SESSIONS = 10+const LOG_FILES = ['modly.log', 'errors.log', 'runtime.log']++function getLogsDir(): string {+ const logsDir = join(app.getPath('userData'), 'logs')+ mkdirSync(logsDir, { recursive: true })+ return logsDir+}++function writeTo(filename: string, logLine: string): void {+ try {+ appendFileSync(join(getLogsDir(), filename), logLine, 'utf-8')+ } catch {}+}++function line(level: string, message: string): string {+ return `[${new Date().toISOString()}] [${level}] ${message}\n`+}++export function archiveCurrentSession(): void {+ const logsDir = getLogsDir()+ const hasLogs = LOG_FILES.some(f => existsSync(join(logsDir, f)))+ if (!hasLogs) return++ const timestamp = new Date().toISOString().replace(/:/g, '-').slice(0, 19)+ const sessionsDir = join(logsDir, 'sessions')+ const sessionDir = join(sessionsDir, timestamp)+ mkdirSync(sessionDir, { recursive: true })++ for (const file of LOG_FILES) {+ const src = join(logsDir, file)+ if (existsSync(src)) {+ try { renameSync(src, join(sessionDir, file)) } catch {}+ }+ }++ // Keep only last MAX_SESSIONS+ try {+ const sessions = readdirSync(sessionsDir)+ .filter(f => statSync(join(sessionsDir, f)).isDirectory())+ .sort()+ .reverse()+ for (const old of sessions.slice(MAX_SESSIONS)) {+ rmSync(join(sessionsDir, old), { recursive: true, force: true })+ }+ } catch {}+}++// Console writes throw EPIPE when the parent process' stdout/stderr pipe is+// gone (e.g. launching terminal closed). Never let logging crash the app.+function safeConsole(fn: (msg: string) => void, msg: string): void {+ try { fn(msg) } catch {}+}++export const logger = {+ info: (msg: string) => { safeConsole(console.log, msg); writeTo('modly.log', line('INFO', msg)) },+ warn: (msg: string) => { safeConsole(console.warn, msg); writeTo('modly.log', line('WARN', msg)) },+ error: (msg: string) => { safeConsole(console.error, msg); writeTo('modly.log', line('ERROR', msg)); writeTo('errors.log', line('ERROR', msg)) },+ python: (msg: string) => {+ writeTo('runtime.log', line('RUNTIME', msg))+ if (/error|exception|traceback|critical/i.test(msg)) {+ writeTo('errors.log', line('RUNTIME', msg))+ }+ },+}diff --git a/apps/forge-desktop/electron/main/model-download-plan.test.mjs b/apps/forge-desktop/electron/main/model-download-plan.test.mjsnew file mode 100644index 000000000..1a927cbcc--- /dev/null+++ b/apps/forge-desktop/electron/main/model-download-plan.test.mjs@@ -0,0 +1,235 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-model-plan-module-')), 'model-plan.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('electron/main/model-download-plan.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++function setupExtension(manifest) {+ const root = mkdtempSync(join(tmpdir(), 'modly-action-plan-'))+ const user = join(root, 'user')+ const builtin = join(root, 'builtin')+ const extension = join(user, manifest.id)+ mkdirSync(extension, { recursive: true })+ mkdirSync(builtin)+ const manifestPath = join(extension, 'manifest.json')+ writeFileSync(manifestPath, JSON.stringify(manifest))+ return { root, user, builtin, manifestPath }+}++test('re-reads the installed manifest for each action and resolves only node-owned sources', async () => {+ const { resolveInstalledModelDownloadPlan } = loadModule()+ const manifest = {+ id: 'pixal3d',+ type: 'model',+ nodes: [{+ id: 'generate',+ model_sources: [{+ id: 'primary', provider: 'huggingface', repo_id: 'org/old',+ destination: '.', checks: ['model.safetensors'],+ }],+ }],+ }+ const fixture = setupExtension(manifest)+ const args = {+ modelId: 'pixal3d/generate',+ userExtensionsDir: fixture.user,+ builtinExtensionsDir: fixture.builtin,+ }+ try {+ const first = await resolveInstalledModelDownloadPlan(args)+ assert.equal(first.kind, 'multi-source')+ assert.equal(first.sources[0].repo_id, 'org/old')++ manifest.nodes[0].model_sources[0].repo_id = 'org/new'+ writeFileSync(fixture.manifestPath, JSON.stringify(manifest))+ const second = await resolveInstalledModelDownloadPlan(args)+ assert.equal(second.sources[0].repo_id, 'org/new')+ } finally {+ rmSync(fixture.root, { recursive: true, force: true })+ }+})++test('keeps legacy sibling checks and wildcard filters unchanged', async () => {+ const { resolveInstalledModelDownloadPlan } = loadModule()+ const fixture = setupExtension({+ id: 'triposplat',+ type: 'model',+ nodes: [{+ id: 'projection',+ hf_repo: 'VAST-AI/TripoSplat',+ download_check: '../generate/diffusion_models/triposplat_fp16.safetensors',+ hf_skip_prefixes: ['weights/**', 'assets/*'],+ }],+ })+ try {+ const plan = await resolveInstalledModelDownloadPlan({+ modelId: 'triposplat/projection',+ userExtensionsDir: fixture.user,+ builtinExtensionsDir: fixture.builtin,+ })+ assert.equal(plan.kind, 'legacy')+ assert.equal(plan.downloadCheck, '../generate/diffusion_models/triposplat_fp16.safetensors')+ assert.deepEqual(plan.skipPrefixes, ['weights/**', 'assets/*'])+ } finally {+ rmSync(fixture.root, { recursive: true, force: true })+ }+})++test('composes shared base groups with private node sources and dependency metadata', async () => {+ const {+ resolveInstalledExtensionSharedWeightGroups,+ resolveInstalledModelDownloadPlan,+ } = loadModule()+ const fixture = setupExtension({+ id: 'pixal3d',+ type: 'model',+ weight_groups: [{+ id: 'base',+ model_sources: [{+ id: 'base-model', provider: 'huggingface', repo_id: 'org/base',+ destination: '.', checks: ['pipeline.json'],+ }],+ }],+ nodes: [+ { id: 'generate', weight_groups: ['base'] },+ {+ id: 'worldsculpt',+ weight_groups: ['base'],+ model_sources: [{+ id: 'adapter', provider: 'huggingface', repo_id: 'org/adapter',+ destination: '.', checks: ['adapter.bin'],+ }],+ },+ ],+ })+ try {+ const plan = await resolveInstalledModelDownloadPlan({+ modelId: 'pixal3d/worldsculpt',+ userExtensionsDir: fixture.user,+ builtinExtensionsDir: fixture.builtin,+ })+ assert.equal(plan.kind, 'multi-source')+ assert.equal(plan.sources[0].repo_id, 'org/adapter')+ assert.equal(plan.sharedGroups[0].targetId, 'pixal3d/_shared/base')+ assert.deepEqual(plan.sharedGroups[0].dependentModelIds, [+ 'pixal3d/generate',+ 'pixal3d/worldsculpt',+ ])++ const groups = await resolveInstalledExtensionSharedWeightGroups({+ extensionId: 'pixal3d',+ userExtensionsDir: fixture.user,+ builtinExtensionsDir: fixture.builtin,+ })+ assert.equal(groups.length, 1)+ assert.equal(groups[0].sources[0].repo_id, 'org/base')+ } finally {+ rmSync(fixture.root, { recursive: true, force: true })+ }+})++test('rejects unknown groups, reserved node ids, and legacy private aliases', async () => {+ const { resolveInstalledModelDownloadPlan } = loadModule()+ for (const manifest of [+ {+ id: 'unknown-group', type: 'model', nodes: [{ id: 'generate', weight_groups: ['missing'] }],+ },+ {+ id: 'reserved-node', type: 'model', nodes: [{ id: '_shared', hf_repo: 'org/model' }],+ },+ {+ id: 'legacy-private', type: 'model',+ weight_groups: [{+ id: 'base',+ model_sources: [{+ id: 'base', provider: 'huggingface', repo_id: 'org/base',+ destination: '.', checks: ['base.bin'],+ }],+ }],+ nodes: [{ id: 'generate', weight_groups: ['base'], hf_repo: 'org/private' }],+ },+ ]) {+ const fixture = setupExtension(manifest)+ const nodeId = manifest.nodes[0].id+ try {+ await assert.rejects(+ resolveInstalledModelDownloadPlan({+ modelId: `${manifest.id}/${nodeId}`,+ userExtensionsDir: fixture.user,+ builtinExtensionsDir: fixture.builtin,+ }),+ /unknown weight group|reserved|must use model_sources/i,+ )+ } finally {+ rmSync(fixture.root, { recursive: true, force: true })+ }+ }+})++test('downloads a weight-variant node as shared files first, then one variant at a time', async () => {+ const { legacyDownloadSteps, resolveInstalledModelDownloadPlan } = loadModule()+ const fixture = setupExtension({+ id: 'trellis',+ type: 'model',+ nodes: [{+ id: 'generate',+ hf_repo: 'org/model-gguf',+ download_check: 'pipeline.json',+ hf_include_prefixes: ['pipeline.json', 'dit/'],+ hf_skip_prefixes: ['README.md'],+ params_schema: [{ id: 'quant', type: 'select', options: [{ value: 'Q4' }, { value: 'Q5' }] }],+ weight_variants: {+ param: 'quant',+ default: 'Q5',+ options: ['Q4', 'Q5'].map((quant) => ({+ id: quant,+ include_prefixes: [`dit/model_${quant}.gguf`],+ checks: [`dit/model_${quant}.gguf`],+ })),+ },+ }],+ })+ try {+ const plan = await resolveInstalledModelDownloadPlan({+ modelId: 'trellis/generate',+ userExtensionsDir: fixture.user,+ builtinExtensionsDir: fixture.builtin,+ })+ assert.equal(plan.kind, 'legacy')+ assert.deepEqual(legacyDownloadSteps(plan), [+ { includePrefixes: ['pipeline.json', 'dit/'], skipPrefixes: ['README.md', 'dit/model_Q4.gguf', 'dit/model_Q5.gguf'] },+ { includePrefixes: ['dit/model_Q5.gguf'], skipPrefixes: ['README.md'] },+ ])+ // Picking one variant still fetches the shared files first, so a node installed+ // variant-first is never left without its pipeline files.+ assert.deepEqual(legacyDownloadSteps(plan, 'Q4'), [+ { includePrefixes: ['pipeline.json', 'dit/'], skipPrefixes: ['README.md', 'dit/model_Q4.gguf', 'dit/model_Q5.gguf'] },+ { includePrefixes: ['dit/model_Q4.gguf'], skipPrefixes: ['README.md'] },+ ])+ assert.throws(() => legacyDownloadSteps(plan, 'Q8'), /no weight variant "Q8"/)++ const withoutVariants = { ...plan, weightVariants: undefined }+ assert.deepEqual(legacyDownloadSteps(withoutVariants), [+ { includePrefixes: ['pipeline.json', 'dit/'], skipPrefixes: ['README.md'] },+ ])+ assert.throws(() => legacyDownloadSteps(withoutVariants, 'Q4'), /no weight variant/)+ } finally {+ rmSync(fixture.root, { recursive: true, force: true })+ }+})diff --git a/apps/forge-desktop/electron/main/model-download-plan.ts b/apps/forge-desktop/electron/main/model-download-plan.tsnew file mode 100644index 000000000..6dc78668a--- /dev/null+++ b/apps/forge-desktop/electron/main/model-download-plan.ts@@ -0,0 +1,301 @@+import { existsSync } from 'node:fs'+import { readFile, readdir } from 'node:fs/promises'+import { join } from 'node:path'++import {+ EXT_INCOMPLETE_MARKER,+ EXT_REGISTRATION_PENDING_MARKER,+ assertSafeExtensionId,+ resolveExtensionPathWithinRoot,+} from './extension-path-guard'+import {+ normalizeModelSources,+ normalizeWeightGroupReferences,+ normalizeWeightGroups,+ normalizeWeightVariants,+ validateModelNodeIds,+ safeModelSourceId,+ weightGroupTargetId,+ type ModelSource,+ type ModelWeightGroup,+ type WeightVariants,+} from './model-sources'++interface InstalledNode {+ id?: unknown+ hf_repo?: unknown+ download_check?: unknown+ hf_skip_prefixes?: unknown+ hf_include_prefixes?: unknown+ model_sources?: unknown+ weight_groups?: unknown+ weight_variants?: unknown+ params_schema?: unknown+}++interface InstalledManifest {+ id?: unknown+ type?: unknown+ model_sources?: unknown+ weight_groups?: unknown+ params_schema?: unknown+ nodes?: unknown+}++export interface InstalledSharedWeightGroup extends ModelWeightGroup {+ targetId: string+ dependentModelIds: string[]+}++export type InstalledModelDownloadPlan = {+ kind: 'legacy'+ modelId: string+ extensionId: string+ nodeId: string+ repoId: string+ downloadCheck?: string+ skipPrefixes?: string[]+ includePrefixes?: string[]+ weightVariants?: WeightVariants+} | {+ kind: 'multi-source'+ modelId: string+ extensionId: string+ nodeId: string+ sources: ModelSource[]+ sharedGroups: InstalledSharedWeightGroup[]+}++async function hasPendingRegistration(root: string, extensionId: string): Promise<boolean> {+ try {+ const prefix = `${EXT_REGISTRATION_PENDING_MARKER}-${extensionId}-`+ return (await readdir(root)).some((name) => (+ name.startsWith(prefix) && /^\d+$/.test(name.slice(prefix.length))+ ))+ } catch {+ return false+ }+}++function installedSharedGroups(+ manifest: InstalledManifest,+ extensionId: string,+ nodes: InstalledNode[],+): InstalledSharedWeightGroup[] {+ const groups = normalizeWeightGroups(manifest)+ if (groups || nodes.some((node) => node.model_sources !== undefined || node.weight_groups !== undefined)) {+ validateModelNodeIds(manifest.nodes as InstalledNode[])+ }+ if (groups === undefined) return []+ const groupDependents = new Map<string, string[]>()+ for (const candidate of nodes) {+ if (typeof candidate.id === 'string' && candidate.id.toLowerCase() === '_shared') {+ throw new Error('manifest.json: model node id "_shared" is reserved')+ }+ const candidateId = safeModelSourceId(candidate.id, 'model node id')+ const refs = normalizeWeightGroupReferences(+ candidate,+ groups,+ `nodes[${candidateId}].weight_groups`,+ ) ?? []+ for (const groupId of refs) {+ const dependents = groupDependents.get(groupId) ?? []+ dependents.push(`${extensionId}/${candidateId}`)+ groupDependents.set(groupId, dependents)+ }+ }+ return groups.map((group) => ({+ ...group,+ targetId: weightGroupTargetId(extensionId, group.id),+ dependentModelIds: groupDependents.get(group.id) ?? [],+ }))+}++function parseManifest(raw: string, extensionId: string, nodeId: string): InstalledModelDownloadPlan {+ let parsed: unknown+ try {+ parsed = JSON.parse(raw)+ } catch {+ throw new Error(`Extension "${extensionId}" has an invalid manifest.json`)+ }+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {+ throw new Error(`Extension "${extensionId}" has an invalid manifest.json`)+ }+ const manifest = parsed as InstalledManifest+ if (manifest.id !== extensionId) throw new Error(`Installed manifest id does not match extension "${extensionId}"`)+ if (manifest.type !== undefined && manifest.type !== 'model') {+ throw new Error(`Extension "${extensionId}" is not a model extension`)+ }+ if (manifest.model_sources !== undefined) {+ throw new Error('manifest.json: model_sources must be declared on a model node')+ }+ if (!Array.isArray(manifest.nodes)) throw new Error(`Extension "${extensionId}" does not declare model nodes`)++ const nodes = manifest.nodes.filter((candidate): candidate is InstalledNode => (+ typeof candidate === 'object' && candidate !== null && !Array.isArray(candidate)+ ))+ const allSharedGroups = installedSharedGroups(manifest, extensionId, nodes)++ const matches = nodes.filter((candidate) => candidate.id === nodeId)+ if (matches.length !== 1) {+ throw new Error(`Installed manifest must declare model node "${nodeId}" exactly once`)+ }++ const node = matches[0]+ const modelId = `${extensionId}/${nodeId}`+ const weightVariants = normalizeWeightVariants(node, node.params_schema ?? manifest.params_schema)+ const sources = normalizeModelSources(node)+ const refs = normalizeWeightGroupReferences(+ node,+ allSharedGroups,+ `nodes[${nodeId}].weight_groups`,+ ) ?? []+ const sharedGroups = refs.map((groupId) => (+ allSharedGroups.find((candidate) => candidate.id === groupId)!+ ))+ if (sources || sharedGroups.length > 0) {+ if (sharedGroups.length > 0 && node.hf_repo !== undefined) {+ throw new Error(`Model node "${modelId}" must use model_sources for private weights when weight_groups are declared`)+ }+ return {+ kind: 'multi-source',+ modelId,+ extensionId,+ nodeId,+ sources: sources ?? [],+ sharedGroups,+ }+ }++ if (typeof node.hf_repo !== 'string' || !node.hf_repo) {+ throw new Error(`Model node "${modelId}" has no Hugging Face download source`)+ }+ return {+ kind: 'legacy',+ modelId,+ extensionId,+ nodeId,+ repoId: node.hf_repo,+ downloadCheck: typeof node.download_check === 'string' ? node.download_check : undefined,+ skipPrefixes: node.hf_skip_prefixes as string[] | undefined,+ includePrefixes: node.hf_include_prefixes as string[] | undefined,+ ...(weightVariants ? { weightVariants } : {}),+ }+}+++export async function resolveInstalledExtensionSharedWeightGroups(args: {+ extensionId: unknown+ userExtensionsDir: string+ builtinExtensionsDir: string+ blockedExtensionIds?: ReadonlySet<string>+}): Promise<InstalledSharedWeightGroup[]> {+ const extensionId = assertSafeExtensionId(args.extensionId)+ if (args.blockedExtensionIds?.has(extensionId)) {+ throw new Error(`Extension "${extensionId}" is being installed or repaired`)+ }+ const userPath = resolveExtensionPathWithinRoot(args.userExtensionsDir, extensionId)+ const builtinPath = resolveExtensionPathWithinRoot(args.builtinExtensionsDir, extensionId)+ const extensionPath = existsSync(userPath) ? userPath : existsSync(builtinPath) ? builtinPath : undefined+ if (!extensionPath) throw new Error(`Extension "${extensionId}" is not installed`)+ const extensionRoot = extensionPath === userPath ? args.userExtensionsDir : args.builtinExtensionsDir+ if (+ existsSync(join(extensionPath, EXT_INCOMPLETE_MARKER))+ || existsSync(join(extensionPath, EXT_REGISTRATION_PENDING_MARKER))+ || await hasPendingRegistration(extensionRoot, extensionId)+ ) {+ throw new Error(`Extension "${extensionId}" has an incomplete installation`)+ }++ const manifestPath = join(extensionPath, 'manifest.json')+ if (!existsSync(manifestPath)) throw new Error(`Extension "${extensionId}" has no manifest.json`)+ let parsed: unknown+ try {+ parsed = JSON.parse(await readFile(manifestPath, 'utf-8'))+ } catch {+ throw new Error(`Extension "${extensionId}" has an invalid manifest.json`)+ }+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {+ throw new Error(`Extension "${extensionId}" has an invalid manifest.json`)+ }+ const manifest = parsed as InstalledManifest+ if (manifest.id !== extensionId) throw new Error(`Installed manifest id does not match extension "${extensionId}"`)+ if (manifest.type !== undefined && manifest.type !== 'model') {+ throw new Error(`Extension "${extensionId}" is not a model extension`)+ }+ if (!Array.isArray(manifest.nodes)) throw new Error(`Extension "${extensionId}" does not declare model nodes`)+ const nodes = manifest.nodes.filter((candidate): candidate is InstalledNode => (+ typeof candidate === 'object' && candidate !== null && !Array.isArray(candidate)+ ))+ return installedSharedGroups(manifest, extensionId, nodes)+}++export interface LegacyDownloadStep {+ includePrefixes?: string[]+ skipPrefixes?: string[]+}++/**+ * Hugging Face filter passes for one download action. A node that declares weight+ * variants always fetches its shared files first (every variant excluded), then the+ * requested variant — its default one when no variant id is given. The shared pass+ * skips files already complete on disk, so it stays cheap on a resume or a second+ * variant.+ */+export function legacyDownloadSteps(+ plan: Extract<InstalledModelDownloadPlan, { kind: 'legacy' }>,+ variantId?: unknown,+): LegacyDownloadStep[] {+ const variants = plan.weightVariants+ if (!variants) {+ if (variantId !== undefined) {+ throw new Error(`Model node "${plan.modelId}" has no weight variant "${String(variantId)}"`)+ }+ return [{ includePrefixes: plan.includePrefixes, skipPrefixes: plan.skipPrefixes }]+ }+ const selected = variantId === undefined ? variants.default : variantId+ const variant = variants.options.find((option) => option.id === selected)+ if (!variant) throw new Error(`Model node "${plan.modelId}" has no weight variant "${String(variantId)}"`)+ return [+ {+ includePrefixes: plan.includePrefixes,+ skipPrefixes: [...(plan.skipPrefixes ?? []), ...variants.options.flatMap((option) => option.include_prefixes)],+ },+ { includePrefixes: variant.include_prefixes, skipPrefixes: plan.skipPrefixes },+ ]+}++/** Re-read the installed manifest for every model action; renderer metadata is never trusted. */+export async function resolveInstalledModelDownloadPlan(args: {+ modelId: unknown+ userExtensionsDir: string+ builtinExtensionsDir: string+ blockedExtensionIds?: ReadonlySet<string>+}): Promise<InstalledModelDownloadPlan> {+ if (typeof args.modelId !== 'string') throw new Error('Model id must be a string')+ const parts = args.modelId.split('/')+ if (parts.length !== 2) throw new Error('Model id must identify one extension node')+ const extensionId = assertSafeExtensionId(parts[0])+ if (parts[1].toLowerCase() === '_shared') throw new Error('Model node id "_shared" is reserved')+ const nodeId = safeModelSourceId(parts[1], 'model node id')+ if (args.blockedExtensionIds?.has(extensionId)) {+ throw new Error(`Extension "${extensionId}" is being installed or repaired`)+ }++ const userPath = resolveExtensionPathWithinRoot(args.userExtensionsDir, extensionId)+ const builtinPath = resolveExtensionPathWithinRoot(args.builtinExtensionsDir, extensionId)+ const extensionPath = existsSync(userPath) ? userPath : existsSync(builtinPath) ? builtinPath : undefined+ if (!extensionPath) throw new Error(`Extension "${extensionId}" is not installed`)+ const extensionRoot = extensionPath === userPath ? args.userExtensionsDir : args.builtinExtensionsDir+ if (+ existsSync(join(extensionPath, EXT_INCOMPLETE_MARKER))+ || existsSync(join(extensionPath, EXT_REGISTRATION_PENDING_MARKER))+ || await hasPendingRegistration(extensionRoot, extensionId)+ ) {+ throw new Error(`Extension "${extensionId}" has an incomplete installation`)+ }++ const manifestPath = join(extensionPath, 'manifest.json')+ if (!existsSync(manifestPath)) throw new Error(`Extension "${extensionId}" has no manifest.json`)+ return parseManifest(await readFile(manifestPath, 'utf-8'), extensionId, nodeId)+}diff --git a/apps/forge-desktop/electron/main/model-download-preload.test.mjs b/apps/forge-desktop/electron/main/model-download-preload.test.mjsnew file mode 100644index 000000000..c88ebf6b3--- /dev/null+++ b/apps/forge-desktop/electron/main/model-download-preload.test.mjs@@ -0,0 +1,64 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-preload-download-')), 'electron-api.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('electron/preload/electron-api.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++test('renderer model actions keep node and shared-weight identities explicit', async () => {+ const { createElectronApi } = loadModule()+ const calls = []+ const ipc = {+ invoke: async (...args) => { calls.push(args); return { success: true } },+ send: () => {},+ on: () => {},+ removeAllListeners: () => {},+ }+ const api = createElectronApi(+ ipc,+ { setZoomFactor: () => {} },+ { getPathForFile: () => '' },+ )++ await api.model.isDownloaded('pixal3d/generate')+ await api.model.hasLocalData('pixal3d/generate')+ await api.model.sharedGroups('pixal3d')+ await api.model.download('pixal3d/generate')+ await api.model.deleteSharedGroup('pixal3d', 'base')+ await api.model.deleteExtensionWeights('pixal3d')++ assert.deepEqual(calls, [+ ['model:isDownloaded', 'pixal3d/generate'],+ ['model:hasLocalData', 'pixal3d/generate'],+ ['model:sharedGroups', 'pixal3d'],+ ['model:download', 'pixal3d/generate'],+ ['model:deleteSharedGroup', 'pixal3d', 'base'],+ ['model:deleteExtensionWeights', 'pixal3d'],+ ])+})++test('UI exposes partial-data removal and dependent-node warnings', () => {+ const page = readFileSync(resolve('src/areas/models/ModelsPage.tsx'), 'utf8')+ const drawer = readFileSync(resolve('src/areas/models/components/ExtensionDrawer.tsx'), 'utf8')++ assert.match(page, /window\.electron\.model\.hasLocalData\(fullId\)/)+ assert.match(page, /deleteExtensionWeights\(extId\)/)+ assert.match(drawer, /localDataIds\.includes\(fullId\) && state\.kind !== 'downloading'/)+ assert.match(drawer, /Remove partial model data/)+ assert.match(drawer, /following nodes will become unavailable/)+})diff --git a/apps/forge-desktop/electron/main/model-downloader.ts b/apps/forge-desktop/electron/main/model-downloader.tsnew file mode 100644index 000000000..abad7b817--- /dev/null+++ b/apps/forge-desktop/electron/main/model-downloader.ts@@ -0,0 +1,227 @@+/**+ * ModelDownloader — downloads models via the SSE endpoint of the Python backend.+ * No longer depends on the Go API catalog.+ */+import { existsSync, readdirSync, statSync, readFileSync } from 'fs'+import { join } from 'path'+import { getHfToken } from './hf-token'+import type { ModelSource } from './model-sources'++export interface DownloadProgress {+ percent: number+ file?: string+ fileIndex?: number+ totalFiles?: number+ status?: string+ bytesDownloaded?: number+ totalBytes?: number+ stalledSeconds?: number+}+export type ProgressCallback = (progress: DownloadProgress) => void++const PYTHON_API_URL = process.env['PYTHON_API_URL'] ?? 'http://127.0.0.1:8765'++// ------------------------------------------------------------------+// Public API+// ------------------------------------------------------------------++/**+ * Check if a model is already downloaded (directory exists and is non-empty).+ */+export function isModelDownloaded(modelsDir: string, modelId: string, downloadCheck?: string): boolean {+ const modelDir = join(modelsDir, modelId)+ if (!existsSync(modelDir)) return false+ if (downloadCheck && downloadCheck.trim()) {+ return existsSync(join(modelDir, downloadCheck))+ }+ try {+ return readdirSync(modelDir).length > 0+ } catch {+ return false+ }+}++/**+ * Recursively compute the total size in bytes of a directory.+ */+function dirSizeBytes(dirPath: string): number {+ let total = 0+ try {+ for (const entry of readdirSync(dirPath)) {+ const full = join(dirPath, entry)+ try {+ const s = statSync(full)+ total += s.isDirectory() ? dirSizeBytes(full) : s.size+ } catch { /* skip unreadable entries */ }+ }+ } catch { /* skip unreadable dir */ }+ return total+}++/**+ * Read HuggingFace download metadata files to get declared file sizes.+ * HF stores these at <modelDir>/.cache/huggingface/download/<filename>.metadata+ * Each file is JSON with a "size" field (bytes).+ * Used as fallback when dirSizeBytes returns near-zero (e.g. symlinks on Windows).+ */+function getModelSizeFromHFMetadata(modelDir: string): number {+ const cacheDir = join(modelDir, '.cache', 'huggingface', 'download')+ if (!existsSync(cacheDir)) return 0+ let total = 0+ try {+ for (const entry of readdirSync(cacheDir)) {+ if (!entry.endsWith('.metadata')) continue+ try {+ const data = JSON.parse(readFileSync(join(cacheDir, entry), 'utf-8'))+ if (typeof data.size === 'number' && data.size > 0) total += data.size+ } catch { /* skip malformed metadata */ }+ }+ } catch { /* skip unreadable cache dir */ }+ return total+}++/**+ * List all locally downloaded models by scanning the models directory.+ * Returns id, name and size_gb (rounded to 1 decimal).+ */+export function listDownloadedModels(modelsDir: string): { id: string; name: string; size_gb: number }[] {+ if (!existsSync(modelsDir)) return []+ try {+ return readdirSync(modelsDir)+ .filter((name) => {+ try {+ const dir = join(modelsDir, name)+ return statSync(dir).isDirectory() && readdirSync(dir).length > 0+ } catch {+ return false+ }+ })+ .map((name) => {+ const modelDir = join(modelsDir, name)+ let bytes = dirSizeBytes(modelDir)+ // Fallback: if near-zero (symlinks not followed), use HF metadata declared sizes+ if (bytes < 1_000_000) bytes = getModelSizeFromHFMetadata(modelDir)+ const size_gb = Math.round(bytes / 1e9 * 10) / 10+ return { id: name, name, size_gb }+ })+ } catch {+ return []+ }+}++/**+ * Download a model from HuggingFace Hub via the Python FastAPI SSE endpoint.+ * Reports progress (0–100) via the onProgress callback.+ */+export async function downloadModelFromHF(+ repoId: string,+ modelId: string,+ onProgress: ProgressCallback,+ skipPrefixes?: string[],+ includePrefixes?: string[],+): Promise<void> {+ const { net } = require('electron')+ let url = `${PYTHON_API_URL}/model/hf-download?repo_id=${encodeURIComponent(repoId)}&model_id=${encodeURIComponent(modelId)}`+ if (skipPrefixes && skipPrefixes.length > 0) {+ url += `&skip_prefixes=${encodeURIComponent(JSON.stringify(skipPrefixes))}`+ }+ if (includePrefixes && includePrefixes.length > 0) {+ url += `&include_prefixes=${encodeURIComponent(JSON.stringify(includePrefixes))}`+ }+ // Header, never a query param: uvicorn logs the full request line to stdout,+ // python-bridge pipes that into runtime.log, and `log:readAll` hands that file+ // to the user for bug reports. The token used to ride all the way there.+ const hfToken = getHfToken() // decrypted cache — settings.json holds the ciphertext+ const res = await net.fetch(url, hfToken ? { headers: { 'X-HF-Token': hfToken } } : undefined)+ if (!res.ok) throw new Error(`HuggingFace download failed: HTTP ${res.status}`)+ await consumeDownloadStream(res, onProgress)+}++/** Download a validated node-level source plan through one aggregate SSE stream. */+export async function downloadModelSourcesFromHF(+ modelId: string,+ sources: ModelSource[],+ onProgress: ProgressCallback,+): Promise<void> {+ const { net } = require('electron')+ const headers: Record<string, string> = { 'Content-Type': 'application/json' }+ const hfToken = getHfToken()+ if (hfToken) headers.Authorization = `Bearer ${hfToken}`+ const url = `${PYTHON_API_URL}/model/hf-download-sources?model_id=${encodeURIComponent(modelId)}`+ const res = await net.fetch(url, {+ method: 'POST',+ headers,+ body: JSON.stringify({ sources }),+ })+ if (!res.ok) throw new Error(`HuggingFace multi-source download failed: HTTP ${res.status}`)+ await consumeDownloadStream(res, onProgress)+}++async function consumeDownloadStream(+ res: Response,+ onProgress: ProgressCallback,+): Promise<void> {+ if (!res.body) throw new Error('No response body from HF download stream')++ const decoder = new TextDecoder()+ const reader = res.body.getReader()+ let buffer = ''+ const STALL_TIMEOUT_MS = 120_000++ async function readWithTimeout() {+ // The timer has to be cleared: an SSE stream emitting ~10 events/s otherwise+ // keeps every timer created in the last 120 s alive in the main process.+ let timer: NodeJS.Timeout | undefined+ try {+ return await Promise.race([+ reader.read(),+ new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error(`Model download stalled for ${Math.round(STALL_TIMEOUT_MS / 1000)}s`)),+ STALL_TIMEOUT_MS,+ )+ }),+ ])+ } finally {+ if (timer) clearTimeout(timer)+ }+ }++ while (true) {+ const { done, value } = await readWithTimeout()+ if (done) break++ buffer += decoder.decode(value, { stream: true })+ const lines = buffer.split('\n')+ buffer = lines.pop() ?? ''++ for (const line of lines) {+ if (!line.startsWith('data: ')) continue+ try {+ const data = JSON.parse(line.slice(6))+ if (typeof data.percent === 'number') onProgress({+ percent: data.percent,+ file: data.file,+ fileIndex: data.fileIndex,+ totalFiles: data.totalFiles,+ status: data.status,+ bytesDownloaded: data.bytesDownloaded,+ totalBytes: data.totalBytes,+ stalledSeconds: data.stalledSeconds,+ })+ if (data.paused) throw new Error('Model download paused')+ if (data.cancelled) throw new Error('Model download cancelled')+ if (data.error) throw new Error(`HF download error: ${data.error}`)+ } catch (e) {+ if (+ e instanceof Error &&+ (+ e.message.startsWith('HF download error:') ||+ e.message === 'Model download paused' ||+ e.message === 'Model download cancelled'+ )+ ) throw e+ }+ }+ }+}diff --git a/apps/forge-desktop/electron/main/model-sources.test.mjs b/apps/forge-desktop/electron/main/model-sources.test.mjsnew file mode 100644index 000000000..751c4f563--- /dev/null+++ b/apps/forge-desktop/electron/main/model-sources.test.mjs@@ -0,0 +1,261 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-model-sources-module-')), 'model-sources.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('electron/main/model-sources.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++const validNode = () => ({+ model_sources: [+ {+ id: 'primary',+ provider: 'huggingface',+ repo_id: 'org/main',+ destination: '.',+ checks: ['pipeline.json'],+ },+ {+ id: 'encoder',+ provider: 'huggingface',+ repo_id: 'org/encoder',+ revision: 'refs/pr/1',+ destination: 'auxiliary/encoder',+ include_prefixes: ['config.json', 'weights/'],+ skip_prefixes: ['README.md'],+ checks: ['config.json', 'model.safetensors'],+ },+ ],+})++test('validates the new model_sources contract without reinterpreting legacy fields', () => {+ const { normalizeModelSources } = loadModule()+ const sources = normalizeModelSources(validNode())+ assert.equal(sources.length, 2)+ assert.equal(sources[1].destination, 'auxiliary/encoder')++ assert.equal(normalizeModelSources({+ hf_repo: 'legacy/repo',+ download_check: '../generate/model.safetensors',+ hf_skip_prefixes: ['weights/**'],+ }), undefined)+})++test('rejects unsafe destinations, unsupported providers, and non-portable source aliases', () => {+ const { normalizeModelSources } = loadModule()+ const source = validNode().model_sources[0]+ for (const destination of ['../outside', 'aux/CON', 'aux/name.', 'C:/models']) {+ assert.throws(+ () => normalizeModelSources({ model_sources: [{ ...source, destination }] }),+ /destination|unsafe/i,+ )+ }+ assert.throws(+ () => normalizeModelSources({ model_sources: [{ ...source, provider: 'url' }] }),+ /provider.*huggingface/i,+ )+ assert.throws(+ () => normalizeModelSources({ model_sources: [source, { ...source, id: 'PRIMARY' }] }),+ /portable-unique/i,+ )+ assert.throws(+ () => normalizeModelSources({ model_sources: [{ ...source, checks: [] }] }),+ /checks.*non-empty/i,+ )+})++test('requires every declared check and rejects symlinked extension-root ancestry', (t) => {+ const { areModelSourcesDownloaded, normalizeModelSources } = loadModule()+ const root = mkdtempSync(join(tmpdir(), 'modly-model-readiness-'))+ const models = join(root, 'models')+ const modelRoot = join(models, 'pixal3d', 'generate')+ const sources = normalizeModelSources(validNode())+ mkdirSync(join(modelRoot, 'auxiliary', 'encoder'), { recursive: true })+ writeFileSync(join(modelRoot, 'pipeline.json'), '{}')+ writeFileSync(join(modelRoot, 'auxiliary', 'encoder', 'config.json'), '{}')++ try {+ assert.equal(areModelSourcesDownloaded(models, 'pixal3d/generate', sources), false)+ writeFileSync(join(modelRoot, 'auxiliary', 'encoder', 'model.safetensors'), 'x')+ assert.equal(areModelSourcesDownloaded(models, 'pixal3d/generate', sources), true)++ writeFileSync(join(modelRoot, 'auxiliary', 'encoder', 'model.safetensors'), '')+ assert.equal(areModelSourcesDownloaded(models, 'pixal3d/generate', sources), false)+ rmSync(join(modelRoot, 'auxiliary', 'encoder', 'model.safetensors'))+ mkdirSync(join(modelRoot, 'auxiliary', 'encoder', 'model.safetensors'))+ assert.equal(areModelSourcesDownloaded(models, 'pixal3d/generate', sources), false)++ rmSync(join(models, 'pixal3d'), { recursive: true, force: true })+ const outside = join(root, 'outside')+ mkdirSync(join(outside, 'generate'), { recursive: true })+ try {+ symlinkSync(outside, join(models, 'pixal3d'), 'dir')+ } catch (error) {+ t.skip(`Symlinks unavailable: ${error}`)+ return+ }+ assert.equal(areModelSourcesDownloaded(models, 'pixal3d/generate', sources), false)+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})++test('validates extension-scoped groups and canonicalizes sibling references', () => {+ const { normalizeWeightGroups, normalizeWeightGroupReferences } = loadModule()+ const groups = normalizeWeightGroups({+ weight_groups: [{+ id: 'Base-Weights',+ model_sources: validNode().model_sources,+ }],+ })+ assert.deepEqual(+ normalizeWeightGroupReferences({ weight_groups: ['base-weights'] }, groups),+ ['Base-Weights'],+ )+ assert.throws(+ () => normalizeWeightGroupReferences({ weight_groups: ['missing'] }, groups),+ /unknown weight group/i,+ )+ assert.throws(+ () => normalizeWeightGroups({+ weight_groups: [+ { id: 'base', model_sources: validNode().model_sources },+ { id: 'BASE', model_sources: validNode().model_sources },+ ],+ }),+ /portable-unique/i,+ )+})++test('stores and checks shared weights under the reserved extension root', () => {+ const {+ areWeightGroupSourcesDownloaded,+ normalizeWeightGroups,+ resolveModelRoot,+ resolveWeightGroupRoot,+ resolveWeightStorageRoot,+ } = loadModule()+ const root = mkdtempSync(join(tmpdir(), 'modly-shared-readiness-'))+ const models = join(root, 'models')+ const [group] = normalizeWeightGroups({+ weight_groups: [{+ id: 'base',+ model_sources: [{+ id: 'primary', provider: 'huggingface', repo_id: 'org/base',+ destination: '.', checks: ['model.bin'],+ }],+ }],+ })+ const groupRoot = join(models, 'demo', '_shared', 'base')+ try {+ assert.equal(resolveWeightGroupRoot(models, 'demo', 'base'), groupRoot)+ assert.equal(resolveWeightStorageRoot(models, 'demo/_shared/base'), groupRoot)+ assert.throws(() => resolveModelRoot(models, 'demo/_shared'), /reserved/i)+ assert.equal(areWeightGroupSourcesDownloaded(models, 'demo', group), false)+ mkdirSync(groupRoot, { recursive: true })+ writeFileSync(join(groupRoot, 'model.bin'), 'weights')+ assert.equal(areWeightGroupSourcesDownloaded(models, 'demo', group), true)+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})+++const quantNode = () => ({+ hf_repo: 'org/model-gguf',+ download_check: 'pipeline.json',+ params_schema: [{+ id: 'quant',+ label: 'Quantization',+ type: 'select',+ default: 'Q5',+ options: [{ value: 'Q4', label: 'Q4' }, { value: 'Q5', label: 'Q5' }],+ }],+ weight_variants: {+ param: 'quant',+ default: 'Q5',+ options: ['Q4', 'Q5'].map((quant) => ({+ id: quant,+ include_prefixes: [`dit/model_${quant}.gguf`],+ checks: [`dit/model_${quant}.gguf`],+ })),+ },+})++test('validates weight variants and rejects ambiguous or unsafe declarations', () => {+ const { normalizeWeightVariants } = loadModule()+ const variants = normalizeWeightVariants(quantNode())+ assert.equal(variants.param, 'quant')+ assert.equal(variants.default, 'Q5')+ assert.deepEqual(variants.options.map((option) => option.label), ['Q4', 'Q5'])+ assert.equal(normalizeWeightVariants({ hf_repo: 'org/model' }), undefined)++ const node = quantNode()+ const [q4, q5] = node.weight_variants.options+ const withOptions = (options, extra = {}) => ({ ...node, weight_variants: { ...node.weight_variants, options, ...extra } })+ const cases = [+ [{ ...node, hf_repo: undefined }, /requires hf_repo/],+ [{ ...node, model_sources: [] }, /cannot be combined/],+ [{ ...node, weight_groups: ['base'] }, /cannot be combined with weight_groups/],+ [{ ...node, download_check: 'dit/model_Q4.gguf' }, /download_check/],+ [withOptions([q4, q5], { default: 'Q8' }), /default/],+ [withOptions([q4, { ...q5, include_prefixes: ['dit/'] }]), /share files/],+ [withOptions([q4, { ...q5, id: 'q4' }]), /portable-unique/],+ [withOptions([{ ...q4, checks: ['other.gguf'] }]), /not covered/],+ [withOptions([{ ...q4, include_prefixes: ['../outside'] }]), /unsafe/],+ [withOptions([{ ...q4, size_gb: -1 }]), /size_gb/],+ [withOptions([{ ...q4, vram_gb: 0 }]), /vram_gb/],+ [withOptions([{ ...q4, vram_gb: '6' }]), /vram_gb/],+ [{ ...node, params_schema: undefined }, /must name a params_schema entry/],+ [{ ...node, params_schema: [{ id: 'steps', type: 'int' }] }, /must name a params_schema entry/],+ [+ { ...node, params_schema: [{ id: 'quant', type: 'select', options: [{ value: 'Q5' }] }] },+ /must offer every weight variant id \(missing: Q4\)/,+ ],+ ]+ for (const [candidate, error] of cases) assert.throws(() => normalizeWeightVariants(candidate), error)++ // A param that declares no options (or an unknown shape) is left to the node.+ assert.doesNotThrow(() => normalizeWeightVariants({ ...node, params_schema: [{ id: 'quant', type: 'string' }] }))+ assert.equal('vram_gb' in variants.options[0], false)+ assert.equal(normalizeWeightVariants(withOptions([{ ...q4, vram_gb: 6.5 }, q5])).options[0].vram_gb, 6.5)+})++test('reports installed variants and lists only the files of the variant being removed', async () => {+ const { installedWeightVariants, listWeightVariantFiles, normalizeWeightVariants } = loadModule()+ const variants = normalizeWeightVariants(quantNode())+ const root = mkdtempSync(join(tmpdir(), 'modly-weight-variants-'))+ const models = join(root, 'models')+ const nodeRoot = join(models, 'trellis', 'generate')+ mkdirSync(join(nodeRoot, 'dit'), { recursive: true })+ writeFileSync(join(nodeRoot, 'pipeline.json'), '{}')+ writeFileSync(join(nodeRoot, 'dit', 'model_Q5.gguf'), 'q5')+ writeFileSync(join(nodeRoot, 'dit', 'model_Q4.gguf'), '')+ writeFileSync(join(nodeRoot, 'dit', 'model_Q4.gguf.part'), 'partial')++ try {+ assert.deepEqual(installedWeightVariants(models, 'trellis/generate', variants), ['Q5'])+ assert.deepEqual(installedWeightVariants(models, '../escape', variants), [])+ const files = await listWeightVariantFiles(models, 'trellis/generate', variants.options[0])+ assert.deepEqual(+ files.map((file) => file.slice(nodeRoot.length + 1).replaceAll('\\', '/')).sort(),+ ['dit/model_Q4.gguf', 'dit/model_Q4.gguf.part'],+ )+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})diff --git a/apps/forge-desktop/electron/main/model-sources.ts b/apps/forge-desktop/electron/main/model-sources.tsnew file mode 100644index 000000000..194e916e2--- /dev/null+++ b/apps/forge-desktop/electron/main/model-sources.ts@@ -0,0 +1,535 @@+import { existsSync, lstatSync, readdirSync, statSync } from 'node:fs'+import { readdir, rm } from 'node:fs/promises'+import { isAbsolute, relative, resolve, sep } from 'node:path'++export interface ModelSource {+ id: string+ provider: 'huggingface'+ repo_id: string+ revision?: string+ destination: string+ include_prefixes?: string[]+ skip_prefixes?: string[]+ checks: string[]+}++export interface ModelSourceNode {+ model_sources?: unknown+}++export interface ModelWeightGroup {+ id: string+ sources: ModelSource[]+}++export interface ModelWeightManifest {+ weight_groups?: unknown+}++export interface ModelWeightNode extends ModelSourceNode {+ weight_groups?: unknown+}++/** One separately installable set of files inside a node's model directory (e.g. a quantization). */+export interface WeightVariant {+ id: string+ label: string+ size_gb?: number+ vram_gb?: number+ include_prefixes: string[]+ checks: string[]+}++export interface WeightVariants {+ /** params_schema id whose value selects the variant at generation time */+ param: string+ default: string+ options: WeightVariant[]+}++export interface WeightVariantNode {+ weight_variants?: unknown+ hf_repo?: unknown+ download_check?: unknown+ model_sources?: unknown+ weight_groups?: unknown+ params_schema?: unknown+}++const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/+const WINDOWS_DEVICE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i+const WINDOWS_UNSAFE = /[<>"|?*\u0000-\u001f]/++function portableSegment(value: string, field: string): string {+ if (+ !value+ || value === '.'+ || value === '..'+ || value.endsWith('.')+ || value.endsWith(' ')+ || value.includes(':')+ || WINDOWS_UNSAFE.test(value)+ || WINDOWS_DEVICE.test(value)+ ) {+ throw new Error(`${field} contains unsafe path segment "${value}"`)+ }+ return value+}++export function safeModelSourceId(value: unknown, field = 'model source id'): string {+ if (typeof value !== 'string' || !value || value !== value.trim() || !SAFE_ID.test(value)) {+ throw new Error(`${field} must be a safe non-empty identifier`)+ }+ return portableSegment(value, field)+}++export function safeModelRelativePath(value: unknown, field: string, allowDot = false): string {+ if (typeof value !== 'string' || !value || value !== value.trim()) {+ throw new Error(`${field} must be a non-empty relative path`)+ }+ if (allowDot && value === '.') return value+ if (value === '.' || value.startsWith('/') || value.includes('\\') || isAbsolute(value)) {+ throw new Error(`${field} must be a safe relative POSIX path`)+ }+ for (const part of value.split('/')) portableSegment(part, field)+ return value+}++function safePrefix(value: unknown, field: string): string {+ if (typeof value !== 'string') return safeModelRelativePath(value, field)+ const path = value.endsWith('/') ? value.slice(0, -1) : value+ safeModelRelativePath(path, field)+ return value+}++function optionalPrefixes(value: unknown, field: string): string[] | undefined {+ if (value === undefined) return undefined+ if (!Array.isArray(value)) throw new Error(`${field} must be an array`)+ return value.map((entry, index) => safePrefix(entry, `${field}[${index}]`))+}++function safeRepoId(value: unknown, field: string): string {+ if (typeof value !== 'string' || !value || value !== value.trim() || value.includes('\\')) {+ throw new Error(`${field} must be a non-empty Hugging Face repository id`)+ }+ const parts = value.split('/')+ if (parts.length > 2 || parts.some((part) => !SAFE_ID.test(part) || part === '.' || part === '..')) {+ throw new Error(`${field} is not a safe Hugging Face repository id`)+ }+ return value+}++function safeRevision(value: unknown, field: string): string | undefined {+ if (value === undefined) return undefined+ if (typeof value !== 'string' || !value || value !== value.trim() || value.startsWith('/') || value.includes('\\') || value.includes('\0')) {+ throw new Error(`${field} must be a safe non-empty revision`)+ }+ if (value.split('/').some((part) => !part || part === '.' || part === '..')) {+ throw new Error(`${field} must be a safe revision`)+ }+ return value+}++export function normalizeModelSources(+ node: ModelSourceNode,+ fieldName = 'model_sources',+): ModelSource[] | undefined {+ if (!Object.prototype.hasOwnProperty.call(node, 'model_sources')) return undefined+ if (!Array.isArray(node.model_sources) || node.model_sources.length === 0) {+ throw new Error(`${fieldName} must be a non-empty array`)+ }++ const seen = new Map<string, string>()+ return node.model_sources.map((raw, index) => {+ const field = `${fieldName}[${index}]`+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {+ throw new Error(`${field} must be an object`)+ }+ const value = raw as Record<string, unknown>+ const id = safeModelSourceId(value.id, `${field}.id`)+ const alias = id.normalize('NFC').toLowerCase()+ const previous = seen.get(alias)+ if (previous) throw new Error(`model source ids "${previous}" and "${id}" are not portable-unique`)+ seen.set(alias, id)+ if (value.provider !== 'huggingface') throw new Error(`${field}.provider must be "huggingface"`)+ if (!Array.isArray(value.checks) || value.checks.length === 0) {+ throw new Error(`${field}.checks must be a non-empty array`)+ }++ const source: ModelSource = {+ id,+ provider: 'huggingface',+ repo_id: safeRepoId(value.repo_id, `${field}.repo_id`),+ destination: safeModelRelativePath(value.destination, `${field}.destination`, true),+ checks: value.checks.map((check, checkIndex) => (+ safeModelRelativePath(check, `${field}.checks[${checkIndex}]`)+ )),+ }+ const revision = safeRevision(value.revision, `${field}.revision`)+ const include = optionalPrefixes(value.include_prefixes, `${field}.include_prefixes`)+ const skip = optionalPrefixes(value.skip_prefixes, `${field}.skip_prefixes`)+ if (revision !== undefined) source.revision = revision+ if (include !== undefined) source.include_prefixes = include+ if (skip !== undefined) source.skip_prefixes = skip+ return source+ })+}++export function validateModelNodeIds(nodes: Array<{ id?: unknown }>): void {+ const seen = new Set<string>()+ for (const node of nodes) {+ if (typeof node?.id === 'string' && node.id.toLowerCase() === '_shared') {+ throw new Error('model node id "_shared" is reserved')+ }+ const id = safeModelSourceId(node?.id, 'model node id')+ const alias = id.toLowerCase()+ if (seen.has(alias)) throw new Error(`model node id "${id}" is not portable-unique`)+ seen.add(alias)+ }+}++export function normalizeWeightGroups(manifest: ModelWeightManifest): ModelWeightGroup[] | undefined {+ if (!Object.prototype.hasOwnProperty.call(manifest, 'weight_groups')) return undefined+ if (!Array.isArray(manifest.weight_groups) || manifest.weight_groups.length === 0) {+ throw new Error('weight_groups must be a non-empty array')+ }++ const seen = new Map<string, string>()+ return manifest.weight_groups.map((raw, index) => {+ const field = `weight_groups[${index}]`+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {+ throw new Error(`${field} must be an object`)+ }+ const value = raw as Record<string, unknown>+ if (typeof value.id === 'string' && value.id.toLowerCase() === '_shared') {+ throw new Error(`${field}.id uses the reserved identifier "_shared"`)+ }+ const id = safeModelSourceId(value.id, `${field}.id`)+ const alias = id.normalize('NFC').toLowerCase()+ const previous = seen.get(alias)+ if (previous) throw new Error(`weight group ids "${previous}" and "${id}" are not portable-unique`)+ seen.set(alias, id)+ const sources = normalizeModelSources(+ { model_sources: value.model_sources },+ `${field}.model_sources`,+ )+ return { id, sources: sources! }+ })+}++export function normalizeWeightGroupReferences(+ node: ModelWeightNode,+ groups: ModelWeightGroup[] | undefined,+ fieldName = 'weight_groups',+): string[] | undefined {+ if (!Object.prototype.hasOwnProperty.call(node, 'weight_groups')) return undefined+ if (!Array.isArray(node.weight_groups) || node.weight_groups.length === 0) {+ throw new Error(`${fieldName} must be a non-empty array of weight group ids`)+ }+ const available = new Map((groups ?? []).map((group) => [group.id.normalize('NFC').toLowerCase(), group.id]))+ const seen = new Map<string, string>()+ return node.weight_groups.map((raw, index) => {+ const id = safeModelSourceId(raw, `${fieldName}[${index}]`)+ const alias = id.normalize('NFC').toLowerCase()+ const previous = seen.get(alias)+ if (previous) throw new Error(`weight group references "${previous}" and "${id}" are not portable-unique`)+ seen.set(alias, id)+ const canonical = available.get(alias)+ if (!canonical) throw new Error(`${fieldName}[${index}] references unknown weight group "${id}"`)+ return canonical+ })+}++function prefixesOverlap(left: string[], right: string[]): boolean {+ return left.some((a) => right.some((b) => {+ const lowerA = a.toLowerCase()+ const lowerB = b.toLowerCase()+ return lowerA.startsWith(lowerB) || lowerB.startsWith(lowerA)+ }))+}++/** Variant ids must be selectable, so the param they key has to exist and offer them. */+function assertParamOffersVariants(param: string, paramsSchema: unknown, ids: string[]): void {+ const entry = Array.isArray(paramsSchema)+ ? paramsSchema.find((p) => typeof p === 'object' && p !== null && (p as { id?: unknown }).id === param)+ : undefined+ if (!entry) throw new Error(`weight_variants.param must name a params_schema entry ("${param}")`)+ const options = (entry as { options?: unknown }).options+ if (!Array.isArray(options)) return+ const values = new Set(options.map((option) =>+ typeof option === 'object' && option !== null ? String((option as { value?: unknown }).value) : String(option)))+ const missing = ids.filter((id) => !values.has(id))+ if (missing.length > 0) {+ throw new Error(`the "${param}" param must offer every weight variant id (missing: ${missing.join(', ')})`)+ }+}++export function normalizeWeightVariants(+ node: WeightVariantNode,+ paramsSchema?: unknown,+): WeightVariants | undefined {+ if (!Object.prototype.hasOwnProperty.call(node, 'weight_variants')) return undefined+ if (Object.prototype.hasOwnProperty.call(node, 'model_sources')) {+ throw new Error('weight_variants cannot be combined with model_sources')+ }+ if (Object.prototype.hasOwnProperty.call(node, 'weight_groups')) {+ throw new Error('weight_variants cannot be combined with weight_groups')+ }+ if (typeof node.hf_repo !== 'string' || !node.hf_repo) {+ throw new Error('weight_variants requires hf_repo on the same node')+ }+ const raw = node.weight_variants+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {+ throw new Error('weight_variants must be an object')+ }+ const value = raw as Record<string, unknown>+ const param = safeModelSourceId(value.param, 'weight_variants.param')+ if (!Array.isArray(value.options) || value.options.length === 0) {+ throw new Error('weight_variants.options must be a non-empty array')+ }++ const seen = new Map<string, string>()+ const options = value.options.map((rawOption, index): WeightVariant => {+ const field = `weight_variants.options[${index}]`+ if (typeof rawOption !== 'object' || rawOption === null || Array.isArray(rawOption)) {+ throw new Error(`${field} must be an object`)+ }+ const option = rawOption as Record<string, unknown>+ const id = safeModelSourceId(option.id, `${field}.id`)+ const alias = id.normalize('NFC').toLowerCase()+ const previous = seen.get(alias)+ if (previous) throw new Error(`weight variant ids "${previous}" and "${id}" are not portable-unique`)+ seen.set(alias, id)+ const label = option.label ?? id+ if (typeof label !== 'string' || !label.trim()) throw new Error(`${field}.label must be a non-empty string`)+ const sizeGb = option.size_gb+ if (sizeGb !== undefined && (typeof sizeGb !== 'number' || !Number.isFinite(sizeGb) || sizeGb <= 0)) {+ throw new Error(`${field}.size_gb must be a positive number`)+ }+ const vramGb = option.vram_gb+ if (vramGb !== undefined && (typeof vramGb !== 'number' || !Number.isFinite(vramGb) || vramGb <= 0)) {+ throw new Error(`${field}.vram_gb must be a positive number`)+ }+ const include = optionalPrefixes(option.include_prefixes, `${field}.include_prefixes`)+ if (!include?.length) throw new Error(`${field}.include_prefixes must be a non-empty array`)+ if (!Array.isArray(option.checks) || option.checks.length === 0) {+ throw new Error(`${field}.checks must be a non-empty array`)+ }+ const checks = option.checks.map((check, checkIndex) => {+ const path = safeModelRelativePath(check, `${field}.checks[${checkIndex}]`)+ if (!include.some((prefix) => path.startsWith(prefix))) {+ throw new Error(`${field}.checks[${checkIndex}] is not covered by its include_prefixes`)+ }+ return path+ })+ return {+ id,+ label,+ ...(sizeGb === undefined ? {} : { size_gb: sizeGb }),+ ...(vramGb === undefined ? {} : { vram_gb: vramGb }),+ include_prefixes: include,+ checks,+ }+ })++ options.forEach((variant, index) => {+ for (const other of options.slice(index + 1)) {+ if (prefixesOverlap(variant.include_prefixes, other.include_prefixes)) {+ throw new Error(`weight variants "${variant.id}" and "${other.id}" share files`)+ }+ }+ })+ const downloadCheck = node.download_check+ if (typeof downloadCheck === 'string' && options.some((variant) => prefixesOverlap([downloadCheck], variant.include_prefixes))) {+ throw new Error('download_check must name a file outside every weight variant')+ }+ const defaultId = value.default ?? options[0].id+ if (!options.some((variant) => variant.id === defaultId)) {+ throw new Error('weight_variants.default must name one of its options')+ }+ assertParamOffersVariants(param, paramsSchema ?? node.params_schema, options.map((variant) => variant.id))+ return { param, default: defaultId as string, options }+}++function pathHasSymlink(root: string, candidate: string): boolean {+ const rootPath = resolve(root)+ const rel = relative(rootPath, resolve(candidate))+ if (rel === '..' || rel.startsWith('../') || rel.startsWith('..\\') || isAbsolute(rel)) return true+ let current = rootPath+ try {+ if (existsSync(current) && lstatSync(current).isSymbolicLink()) return true+ for (const part of rel.split(/[/\\]/).filter(Boolean)) {+ current = resolve(current, part)+ if (existsSync(current) && lstatSync(current).isSymbolicLink()) return true+ }+ } catch {+ return true+ }+ return false+}++export function resolveModelRoot(modelsDir: string, modelId: string): string {+ if (typeof modelId !== 'string') throw new Error('Model id must be a string')+ const parts = modelId.split('/')+ if (parts.length !== 2) throw new Error('Model id must identify one extension node')+ const extensionId = safeModelSourceId(parts[0], 'extension id')+ if (parts[1].toLowerCase() === '_shared') throw new Error('Model node id "_shared" is reserved')+ const nodeId = safeModelSourceId(parts[1], 'model node id')+ const root = resolve(modelsDir)+ const extensionRoot = resolveExtensionModelRoot(modelsDir, extensionId)+ const modelRoot = resolve(extensionRoot, nodeId)+ if (pathHasSymlink(root, modelRoot)) throw new Error('Model path resolves through a symlink')+ return modelRoot+}++export function resolveExtensionModelRoot(modelsDir: string, extensionId: string): string {+ const safeExtensionId = safeModelSourceId(extensionId, 'extension id')+ const root = resolve(modelsDir)+ const extensionRoot = resolve(root, safeExtensionId)+ if (pathHasSymlink(root, extensionRoot)) throw new Error('Extension model path resolves through a symlink')+ return extensionRoot+}++export function resolveWeightGroupRoot(modelsDir: string, extensionId: string, groupId: string): string {+ const safeExtensionId = safeModelSourceId(extensionId, 'extension id')+ if (typeof groupId === 'string' && groupId.toLowerCase() === '_shared') {+ throw new Error('Weight group id "_shared" is reserved')+ }+ const safeGroupId = safeModelSourceId(groupId, 'weight group id')+ const root = resolve(modelsDir)+ const extensionRoot = resolveExtensionModelRoot(modelsDir, safeExtensionId)+ const groupRoot = resolve(extensionRoot, '_shared', safeGroupId)+ if (pathHasSymlink(root, groupRoot)) throw new Error('Weight group path resolves through a symlink')+ return groupRoot+}++export function weightGroupTargetId(extensionId: string, groupId: string): string {+ const safeExtensionId = safeModelSourceId(extensionId, 'extension id')+ const safeGroupId = safeModelSourceId(groupId, 'weight group id')+ return `${safeExtensionId}/_shared/${safeGroupId}`+}++export function resolveWeightStorageRoot(modelsDir: string, targetId: string): string {+ if (typeof targetId !== 'string') throw new Error('Weight target id must be a string')+ const parts = targetId.split('/')+ if (parts.length === 2) return resolveModelRoot(modelsDir, targetId)+ if (parts.length === 3 && parts[1] === '_shared') {+ return resolveWeightGroupRoot(modelsDir, parts[0], parts[2])+ }+ throw new Error('Weight target id must identify one model node or extension weight group')+}++export function areModelSourcesDownloadedAtRoot(modelRoot: string, sources: ModelSource[]): boolean {+ try {+ if (!existsSync(modelRoot) || pathHasSymlink(modelRoot, modelRoot)) return false+ return sources.every((source) => {+ const destination = source.destination === '.'+ ? modelRoot+ : resolve(modelRoot, ...source.destination.split('/'))+ if (!existsSync(destination) || pathHasSymlink(modelRoot, destination)) return false+ return source.checks.every((check) => {+ const candidate = resolve(destination, ...check.split('/'))+ if (!existsSync(candidate) || pathHasSymlink(modelRoot, candidate)) return false+ try {+ const stat = statSync(candidate)+ return stat.isFile() && stat.size > 0+ } catch {+ return false+ }+ })+ })+ } catch {+ return false+ }+}++export function areModelSourcesDownloaded(modelsDir: string, modelId: string, sources: ModelSource[]): boolean {+ try {+ const modelRoot = resolveModelRoot(modelsDir, modelId)+ return areModelSourcesDownloadedAtRoot(modelRoot, sources)+ } catch {+ return false+ }+}++export function areWeightGroupSourcesDownloaded(+ modelsDir: string,+ extensionId: string,+ group: ModelWeightGroup,+): boolean {+ try {+ return areModelSourcesDownloadedAtRoot(+ resolveWeightGroupRoot(modelsDir, extensionId, group.id),+ group.sources,+ )+ } catch {+ return false+ }+}++export function modelHasLocalData(modelsDir: string, modelId: string): boolean {+ try {+ const modelRoot = resolveModelRoot(modelsDir, modelId)+ return existsSync(modelRoot) && readdirSync(modelRoot).length > 0+ } catch {+ return false+ }+}++export function weightStorageHasLocalData(modelsDir: string, targetId: string): boolean {+ try {+ const root = resolveWeightStorageRoot(modelsDir, targetId)+ return existsSync(root) && readdirSync(root).length > 0+ } catch {+ return false+ }+}++function isDownloadedFile(root: string, relativePath: string): boolean {+ const candidate = resolve(root, ...relativePath.split('/'))+ if (!existsSync(candidate) || pathHasSymlink(root, candidate)) return false+ try {+ const stat = statSync(candidate)+ return stat.isFile() && stat.size > 0+ } catch {+ return false+ }+}++export function installedWeightVariants(modelsDir: string, modelId: string, variants: WeightVariants): string[] {+ try {+ const modelRoot = resolveModelRoot(modelsDir, modelId)+ return variants.options+ .filter((variant) => variant.checks.every((check) => isDownloadedFile(modelRoot, check)))+ .map((variant) => variant.id)+ } catch {+ return []+ }+}++/** Files of one variant on disk (in-progress `.part` files included), never through a symlink. */+export async function listWeightVariantFiles(modelsDir: string, modelId: string, variant: WeightVariant): Promise<string[]> {+ const modelRoot = resolveModelRoot(modelsDir, modelId)+ if (!existsSync(modelRoot)) return []+ const entries = await readdir(modelRoot, { recursive: true, withFileTypes: true })+ return entries+ .filter((entry) => entry.isFile())+ .map((entry) => resolve(entry.parentPath ?? modelRoot, entry.name))+ .filter((path) => {+ const relativePath = relative(modelRoot, path).split(sep).join('/')+ return variant.include_prefixes.some((prefix) => relativePath.startsWith(prefix))+ && !pathHasSymlink(modelRoot, path)+ })+}++// Mirrors the backend's cancel cleanup (api/routers/model.py): only the in-progress+// `.part` files are removed, so completed sources already on disk survive a cancel.+export async function removePartialDownloadArtifacts(modelRoot: string): Promise<void> {+ if (!existsSync(modelRoot)) return+ const entries = await readdir(modelRoot, { recursive: true, withFileTypes: true })+ await Promise.all(+ entries+ .filter((entry) => entry.isFile() && entry.name.endsWith('.part'))+ .map((entry) => rm(resolve(entry.parentPath ?? modelRoot, entry.name), { force: true })),+ )+}diff --git a/apps/forge-desktop/electron/main/model-weight-ipc.test.mjs b/apps/forge-desktop/electron/main/model-weight-ipc.test.mjsnew file mode 100644index 000000000..b77d75bcc--- /dev/null+++ b/apps/forge-desktop/electron/main/model-weight-ipc.test.mjs@@ -0,0 +1,218 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync, transformSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'+import vm from 'node:vm'++const require = createRequire(import.meta.url)+function moduleFromCode(code, dependencies = require) {+ const module = { exports: {} }+ vm.runInNewContext(code, { module, exports: module.exports, require: dependencies, process, console, Buffer, setTimeout, clearTimeout })+ return module.exports+}+function loadModule(path) {+ return moduleFromCode(buildSync({ entryPoints: [resolve(path)], bundle: true, platform: 'node', format: 'cjs', write: false }).outputFiles[0].text)+}+const realSources = loadModule('electron/main/model-sources.ts')+const realPlan = loadModule('electron/main/model-download-plan.ts')+const realGuard = loadModule('electron/main/extension-path-guard.ts')+const realOperations = loadModule('electron/main/model-weight-operations.ts')+const ipcCode = transformSync(readFileSync('electron/main/ipc-handlers.ts', 'utf8'), { loader: 'ts', format: 'cjs' }).code+const source = { id: 'weights', provider: 'huggingface', repo_id: 'org/base', destination: '.', checks: ['weights.bin'] }+function deferred() {+ let resolve+ const promise = new Promise((r) => { resolve = r })+ return { promise, resolve }+}+function fixture(t) {+ const root = mkdtempSync(join(tmpdir(), 'modly-weight-ipc-'))+ t.after(() => rmSync(root, { recursive: true, force: true }))+ const settings = { modelsDir: join(root, 'models'), extensionsDir: join(root, 'extensions') }+ const extension = join(settings.extensionsDir, 'demo')+ mkdirSync(extension, { recursive: true })+ writeFileSync(join(extension, 'manifest.json'), JSON.stringify({+ id: 'demo', type: 'model', weight_groups: [{ id: 'base', model_sources: [source] }],+ nodes: [{ id: 'a', weight_groups: ['base'] }, { id: 'b', weight_groups: ['base'], model_sources: [{ ...source, repo_id: 'org/adapter' }] }],+ }))+ const handlers = new Map(), events = [], removed = [], calls = []+ const hooks = {+ unload: async () => ({ data: { unloaded: true } }),+ listModels: async () => ({ data: [{ id: 'demo/a' }, { id: 'demo/b' }, { id: 'other/generate' }] }),+ download: async (id) => {+ const dir = realSources.resolveWeightStorageRoot(settings.modelsDir, id)+ mkdirSync(dir, { recursive: true })+ writeFileSync(join(dir, 'weights.bin'), 'complete')+ },+ }+ const stub = new Proxy({}, { get: () => () => {} })+ const deps = (name) => {+ if (name === 'electron') return { ipcMain: { handle: (id, fn) => handlers.set(id, fn), on: () => {} }, app: { getPath: () => root, on: () => {} } }+ if (name === 'axios') return {+ post: (...args) => hooks.unload(...args),+ get: (...args) => hooks.listModels(...args),+ isAxiosError: (err) => Boolean(err?.isAxiosError),+ }+ if (name === './model-sources') return realSources+ if (name === './model-download-plan') return realPlan+ if (name === './extension-path-guard') return realGuard+ if (name === './model-weight-operations') return realOperations+ if (name === './settings-store') return { getSettings: () => settings, setSettings: (_, patch) => Object.assign(settings, patch) }+ if (name === './builtin-sync') return { getBuiltinExtensionsDir: () => join(root, 'builtin') }+ if (name === './python-bridge') return { API_BASE_URL: 'http://test' }+ if (name === './model-downloader') return {+ downloadModelSourcesFromHF: async (...args) => { calls.push(args[0]); await hooks.download(...args) },+ }+ if (name === './extension-install-recovery') return { rmWithRetry: async (dir) => { removed.push(dir); rmSync(dir, { recursive: true, force: true }); return { ok: true } } }+ if (name.startsWith('./') || name === 'electron-updater') return stub+ return require(name)+ }+ moduleFromCode(ipcCode, deps).setupIpcHandlers({}, () => ({ webContents: { send: (...event) => events.push(event) } }))+ const event = { sender: { send: (...args) => events.push(args) } }+ const invoke = (name, ...args) => handlers.get(`model:${name}`)(event, ...args)+ return { settings, hooks, invoke, removed, events, calls, handlers, root }+}++for (const action of ['deleteSharedGroup', 'deleteExtensionWeights']) {+ test(`${action} reserves its root before awaiting unload and releases it afterwards`, async (t) => {+ const f = fixture(t), entered = deferred(), finish = deferred()+ f.hooks.unload = async () => { entered.resolve(); await finish.promise; return { data: { unloaded: true } } }+ const deleting = f.invoke(action, 'demo', 'base')+ await entered.promise+ const blocked = await f.invoke('download', 'demo/a')+ assert.equal(blocked.success, false)+ assert.match(blocked.error, /busy/)+ assert.equal(f.calls.length, 0)+ finish.resolve()+ assert.equal((await deleting).success, true)+ assert.equal((await f.invoke('download', 'demo/a')).success, true)+ })+ test(`${action} preserves files when unload fails or is not confirmed`, async (t) => {+ const f = fixture(t)+ for (const unload of [async () => { throw new Error('timeout') }, async () => ({ data: {} })]) {+ f.hooks.unload = unload+ assert.equal((await f.invoke(action, 'demo', 'base')).success, false)+ assert.equal(f.removed.length, 0)+ }+ // Failure must release the lease as well.+ assert.equal((await f.invoke('download', 'demo/a')).success, true)+ })+}++function connectionRefused() {+ return Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:8765'), { isAxiosError: true, code: 'ECONNREFUSED' })+}++for (const action of ['deleteSharedGroup', 'deleteExtensionWeights']) {+ test(`${action} still removes weights when the backend is not running`, async (t) => {+ // No backend means no Python process can hold the files open.+ const f = fixture(t)+ await f.invoke('download', 'demo/a')+ f.hooks.unload = async () => { throw connectionRefused() }+ f.hooks.listModels = async () => { throw connectionRefused() }+ assert.equal((await f.invoke(action, 'demo', 'base')).success, true)+ assert.equal(f.removed.length, 1)+ })+}++test('deleteExtensionWeights unloads only that extension models', async (t) => {+ const f = fixture(t), unloaded = []+ f.hooks.unload = async (url) => { unloaded.push(url); return { data: { unloaded: true } } }+ assert.equal((await f.invoke('deleteExtensionWeights', 'demo')).success, true)+ assert.deepEqual(unloaded, ['http://test/model/unload/demo%2Fa', 'http://test/model/unload/demo%2Fb'])+})++test('active download blocks deletion, including a complete base needed by a private adapter', async (t) => {+ const f = fixture(t)+ await f.invoke('download', 'demo/a')+ const entered = deferred(), finish = deferred()+ f.hooks.download = async () => { entered.resolve(); await finish.promise }+ const downloading = f.invoke('download', 'demo/b')+ await entered.promise+ assert.equal((await f.invoke('deleteSharedGroup', 'demo', 'base')).success, false)+ assert.equal(f.removed.length, 0)+ finish.resolve()+ await downloading+})++test('paused shared cancellation cleans the original target and preserves completed files', async (t) => {+ const f = fixture(t)+ const groupDir = join(f.settings.modelsDir, 'demo', '_shared', 'base')+ f.hooks.download = async () => {+ mkdirSync(groupDir, { recursive: true })+ writeFileSync(join(groupDir, 'weights.bin.part'), 'partial')+ writeFileSync(join(groupDir, 'finished.bin'), 'complete')+ throw new Error('Model download paused')+ }+ assert.equal((await f.invoke('download', 'demo/a')).paused, true)+ f.settings.modelsDir = join(f.root, 'new-models')+ assert.equal((await f.invoke('cancelDownload', 'demo/a')).success, true)+ assert.equal(existsSync(join(groupDir, 'weights.bin.part')), false)+ assert.equal(existsSync(join(groupDir, 'finished.bin')), true)+})++test('paused cleanup cannot delete a sibling download partials', async (t) => {+ const f = fixture(t)+ f.hooks.download = async () => { throw new Error('Model download paused') }+ await f.invoke('download', 'demo/a')+ const entered = deferred(), finish = deferred()+ f.hooks.download = async () => { entered.resolve(); await finish.promise }+ const sibling = f.invoke('download', 'demo/b')+ await entered.promise+ const result = await f.invoke('cancelDownload', 'demo/a')+ assert.equal(result.success, false)+ assert.match(result.error, /busy/)+ finish.resolve()+ await sibling+})++test('private failure notifies readiness changes and preserves the usable shared base', async (t) => {+ const f = fixture(t), normalDownload = f.hooks.download+ f.hooks.download = async (id) => {+ if (id === 'demo/b') throw new Error('adapter failed')+ await normalDownload(id)+ }+ const result = await f.invoke('download', 'demo/b')+ assert.equal(result.success, false)+ assert.equal(await f.invoke('isDownloaded', 'demo/a'), true)+ assert.equal(await f.invoke('isDownloaded', 'demo/b'), false)+ assert.ok(f.events.filter(([name]) => name === 'model:weightsChanged').length >= 2)+})++test('physical locks reject case aliases and parent roots without blocking unrelated roots', () => {+ const locks = new realOperations.ModelWeightOperations()+ const release = locks.acquire('node', [resolve('Models/Demo/Fast')])+ assert.throws(() => locks.acquire('alias', [resolve('models/demo/fast')]), /busy/)+ assert.throws(() => locks.acquire('extension', [resolve('models/demo')]), /busy/)+ locks.acquire('sibling', [resolve('models/demo/other')])()+ release()+ assert.equal(locks.busy, false)+})++for (const action of ['pauseDownload', 'cancelDownload']) {+ test(`${action} at a target boundary does not start the private source`, async (t) => {+ const f = fixture(t), entered = deferred(), finish = deferred()+ f.hooks.download = async () => { entered.resolve(); await finish.promise }+ const downloading = f.invoke('download', 'demo/b')+ await entered.promise+ const stopping = f.invoke(action, 'demo/b')+ finish.resolve()+ assert.equal((await stopping).success, true)+ const result = await downloading+ assert.equal(result[action === 'pauseDownload' ? 'paused' : 'cancelled'], true)+ assert.deepEqual(f.calls, ['demo/_shared/base'])+ })+}++test('model path changes are rejected while weights are reserved', async (t) => {+ const f = fixture(t), entered = deferred(), finish = deferred()+ f.hooks.download = async () => { entered.resolve(); await finish.promise }+ const downloading = f.invoke('download', 'demo/a')+ await entered.promise+ await assert.rejects(f.handlers.get('settings:set')(null, { modelsDir: join(f.root, 'new') }), /busy/)+ assert.equal((await f.handlers.get('api:updatePaths')(null, { modelsDir: join(f.root, 'new') })).success, false)+ finish.resolve()+ await downloading+})diff --git a/apps/forge-desktop/electron/main/model-weight-operations.ts b/apps/forge-desktop/electron/main/model-weight-operations.tsnew file mode 100644index 000000000..7ec921817--- /dev/null+++ b/apps/forge-desktop/electron/main/model-weight-operations.ts@@ -0,0 +1,35 @@+import { resolve, sep } from 'node:path'++/** Atomic in-process reservations, including ancestor/descendant conflicts.+ * Fold case conservatively so Windows aliases cannot obtain separate leases.+ */+export class ModelWeightOperations {+ private leases = new Map<symbol, { owner: string; roots: string[] }>()++ get busy(): boolean { return this.leases.size > 0 }++ acquire(owner: string, roots: string[]): () => void {+ const canonical = roots.map((root) => resolve(root).normalize('NFC').toLowerCase())+ const contains = (parent: string, child: string) => (+ child === parent || child.startsWith(parent.endsWith(sep) ? parent : parent + sep)+ )+ for (const lease of this.leases.values()) {+ if (canonical.some((root) => lease.roots.some((other) => contains(root, other) || contains(other, root)))) {+ throw new Error(`Model weights are busy: ${lease.owner}`)+ }+ }+ const token = Symbol(owner)+ this.leases.set(token, { owner, roots: canonical })+ return () => { this.leases.delete(token) }+ }++ async remove<T>(roots: string[], unload: () => Promise<void>, remove: () => Promise<T>): Promise<T> {+ const release = this.acquire('removing model weights', roots)+ try {+ await unload()+ return await remove()+ } finally {+ release()+ }+ }+}diff --git a/apps/forge-desktop/electron/main/process-runner-worker-exit.test.mjs b/apps/forge-desktop/electron/main/process-runner-worker-exit.test.mjsnew file mode 100644index 000000000..de1a11f1a--- /dev/null+++ b/apps/forge-desktop/electron/main/process-runner-worker-exit.test.mjs@@ -0,0 +1,106 @@+/**+ * A JS process extension runs in a worker thread that is kept warm between+ * runs. If that worker dies mid-run -- an uncaught error outside the awaited+ * processor call, running out of memory on a large mesh, process.exit() -- it+ * never posts 'done' or 'error'. The run must settle with an error instead of+ * leaving the workflow waiting forever, and the next run must get a fresh+ * worker rather than posting into the dead one -- including when the worker+ * died while idle, between two runs.+ */+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'+import vm from 'node:vm'++function loadModule() {+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('electron/main/process-runner.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ external: ['electron'],+ })+ // process-runner imports electron's `app` (only the Python runner uses it);+ // the real package cannot load outside Electron, so hand it a stub.+ const module = { exports: {} }+ const dependencies = (name) => (name === 'electron' ? { app: {} } : require(name))+ vm.runInNewContext(result.outputFiles[0].text, {+ module, exports: module.exports, require: dependencies, process, console, Buffer, setTimeout, clearTimeout,+ })+ return module.exports+}++// Behaves according to params.mode; `runs` counts runs served by this worker,+// so a fresh worker starts again from 1.+function makeRunner() {+ const { ProcessRunner } = loadModule()+ const root = mkdtempSync(join(tmpdir(), 'modly-worker-exit-'))+ const extDir = join(root, 'ext')+ mkdirSync(extDir, { recursive: true })+ writeFileSync(join(extDir, 'processor.js'), [+ 'let runs = 0',+ 'module.exports = async (input, params) => {',+ ' runs += 1',+ " if (params.mode === 'throw') throw new Error('bad input')",+ " if (params.mode === 'crash') {",+ " setTimeout(() => { throw new Error('worker blew up') }, 0)",+ ' return new Promise(() => {})',+ ' }',+ " if (params.mode === 'exit') process.exit(3)",+ // Returns normally, then a timer it left behind kills the idle worker.+ " if (params.mode === 'late-crash') setTimeout(() => { throw new Error('late failure') }, 10)",+ ' return { text: String(runs) }',+ '}',+ '',+ ].join('\n'))+ return new ProcessRunner(extDir, 'processor.js', join(root, 'workspace'), root)+}++test('a run whose worker crashes rejects instead of hanging', { timeout: 5000 }, async () => {+ const runner = makeRunner()+ try {+ await assert.rejects(runner.run({}, { mode: 'crash' }), /worker blew up/)+ } finally {+ runner.terminate()+ }+})++test('after its worker exits, the runner starts a fresh one for the next run', { timeout: 5000 }, async () => {+ const runner = makeRunner()+ try {+ await assert.rejects(runner.run({}, { mode: 'exit' }), /exited with code 3/)+ assert.deepEqual(await runner.run({}, { mode: 'ok' }), { text: '1' })+ } finally {+ runner.terminate()+ }+})++test('an error thrown by the processor still rejects with its message and keeps the warm worker', { timeout: 5000 }, async () => {+ const runner = makeRunner()+ try {+ await assert.rejects(runner.run({}, { mode: 'throw' }), { message: 'Error: bad input' })+ // Same worker thread: its run counter carried over instead of restarting.+ assert.deepEqual(await runner.run({}, { mode: 'ok' }), { text: '2' })+ } finally {+ runner.terminate()+ }+})++test('a worker that dies between runs is replaced for the next run', { timeout: 5000 }, async () => {+ const runner = makeRunner()+ try {+ // The run itself succeeds; the timer it leaves behind kills the idle worker.+ assert.deepEqual(await runner.run({}, { mode: 'late-crash' }), { text: '1' })+ await new Promise((settle) => setTimeout(settle, 200))+ // A fresh worker serves the next run (counter restarts) instead of hanging.+ assert.deepEqual(await runner.run({}, { mode: 'ok' }), { text: '1' })+ } finally {+ runner.terminate()+ }+})diff --git a/apps/forge-desktop/electron/main/process-runner.test.mjs b/apps/forge-desktop/electron/main/process-runner.test.mjsnew file mode 100644index 000000000..1d72b8660--- /dev/null+++ b/apps/forge-desktop/electron/main/process-runner.test.mjs@@ -0,0 +1,122 @@+/**+ * Process-extension runners are cached per extension id and reused across+ * workflow runs. The cache must not hand back a runner that was built for+ * different arguments: the workspace folder is baked into each runner, so after+ * the user moves the workspace in Settings (which updates the backend at+ * runtime, without a restart) a stale runner keeps writing node output into the+ * old folder, where the viewer can no longer find it.+ */+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'+import vm from 'node:vm'++function loadModule() {+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('electron/main/process-runner.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ external: ['electron'],+ })+ // process-runner imports electron's `app` (the Python runner reads it when it+ // spawns); the real package cannot load outside Electron, so hand it a stub.+ const app = { isPackaged: false, getAppPath: () => process.cwd() }+ const module = { exports: {} }+ const dependencies = (name) => (name === 'electron' ? { app } : require(name))+ vm.runInNewContext(result.outputFiles[0].text, {+ module, exports: module.exports, require: dependencies, process, console, Buffer, setTimeout, clearTimeout,+ })+ return module.exports+}++// A JS process extension that reports the workspace it was given, plus how many+// runs this worker has served (module state survives only while it is reused).+function makeJsExtension(root) {+ const extDir = join(root, 'js-ext')+ mkdirSync(extDir, { recursive: true })+ writeFileSync(join(extDir, 'processor.js'), [+ 'let runs = 0',+ 'module.exports = async (input, params, context) => {',+ ' runs += 1',+ ' return { filePath: context.workspaceDir, text: String(runs) }',+ '}',+ '',+ ].join('\n'))+ return extDir+}++// A "Python" process extension driven through the same stdin/stdout protocol.+// Node stands in for the interpreter so the test needs no Python install.+function makeStdioExtension(root) {+ const extDir = join(root, 'py-ext')+ mkdirSync(extDir, { recursive: true })+ writeFileSync(join(extDir, 'processor.cjs'), [+ "let raw = ''",+ "process.stdin.on('data', (chunk) => { raw += chunk })",+ "process.stdin.on('end', () => {",+ ' const data = JSON.parse(raw)',+ " process.stdout.write(JSON.stringify({ type: 'done', result: { filePath: data.workspaceDir } }) + '\\n')",+ '})',+ '',+ ].join('\n'))+ return extDir+}++test('a JS process runner follows the workspace after it moves', async () => {+ const { getProcessRunner, terminateAllProcessRunners } = loadModule()+ const root = mkdtempSync(join(tmpdir(), 'modly-runner-js-'))+ const extDir = makeJsExtension(root)+ const oldWorkspace = join(root, 'workspace-old')+ const newWorkspace = join(root, 'workspace-new')+ try {+ const before = await getProcessRunner('js-ext', extDir, 'processor.js', oldWorkspace, root).run({}, {})+ assert.equal(before.filePath, oldWorkspace)++ const after = await getProcessRunner('js-ext', extDir, 'processor.js', newWorkspace, root).run({}, {})+ assert.equal(after.filePath, newWorkspace)+ } finally {+ terminateAllProcessRunners()+ }+})++test('a Python process runner follows the workspace after it moves', async () => {+ const { getPythonProcessRunner, terminateAllProcessRunners } = loadModule()+ const root = mkdtempSync(join(tmpdir(), 'modly-runner-py-'))+ const extDir = makeStdioExtension(root)+ const oldWorkspace = join(root, 'workspace-old')+ const newWorkspace = join(root, 'workspace-new')+ try {+ const before = await getPythonProcessRunner('py-ext', process.execPath, extDir, 'processor.cjs', oldWorkspace, root).run({}, {})+ assert.equal(before.filePath, oldWorkspace)++ const after = await getPythonProcessRunner('py-ext', process.execPath, extDir, 'processor.cjs', newWorkspace, root).run({}, {})+ assert.equal(after.filePath, newWorkspace)+ } finally {+ terminateAllProcessRunners()+ }+})++test('unchanged arguments keep reusing the same warm runner', async () => {+ const { getProcessRunner, terminateAllProcessRunners } = loadModule()+ const root = mkdtempSync(join(tmpdir(), 'modly-runner-reuse-'))+ const extDir = makeJsExtension(root)+ const workspace = join(root, 'workspace')+ try {+ const first = getProcessRunner('js-ext', extDir, 'processor.js', workspace, root)+ assert.equal((await first.run({}, {})).text, '1')++ const second = getProcessRunner('js-ext', extDir, 'processor.js', workspace, root)+ assert.equal(second, first)+ // Same worker thread: its module state carried over instead of reloading.+ assert.equal((await second.run({}, {})).text, '2')+ } finally {+ terminateAllProcessRunners()+ }+})diff --git a/apps/forge-desktop/electron/main/process-runner.ts b/apps/forge-desktop/electron/main/process-runner.tsnew file mode 100644index 000000000..8b012c824--- /dev/null+++ b/apps/forge-desktop/electron/main/process-runner.ts@@ -0,0 +1,370 @@+import { Worker } from 'worker_threads'+import { spawn } from 'child_process'+import { existsSync } from 'fs'+import { join } from 'path'+import { app } from 'electron'++// ─── Worker code for JS process extensions ────────────────────────────────────++const WORKER_CODE = /* js */ `+const { workerData, parentPort } = require('worker_threads')+const path = require('path')+const Module = require('module')++// Resolve modules from the extension's own node_modules+const require_ext = Module.createRequire(path.join(workerData.extDir, '_'))++let processor+try {+ processor = require_ext(path.join(workerData.extDir, workerData.entry))+ if (typeof processor !== 'function') {+ throw new Error('processor.js must export a function as module.exports')+ }+} catch (err) {+ parentPort.postMessage({ type: 'error', message: 'Failed to load processor: ' + String(err) })+ process.exit(1)+}++parentPort.postMessage({ type: 'ready' })++parentPort.on('message', async (msg) => {+ if (msg.action !== 'run') return+ try {+ const context = {+ workspaceDir: workerData.workspaceDir,+ tempDir: workerData.tempDir,+ nodeId: msg.input?.nodeId ?? '',+ log: (m) => parentPort.postMessage({ type: 'log', message: String(m) }),+ progress: (pct, label) => parentPort.postMessage({ type: 'progress', percent: pct, label }),+ }+ const result = await processor(msg.input, msg.params, context)+ parentPort.postMessage({ type: 'done', result })+ } catch (err) {+ parentPort.postMessage({ type: 'error', message: String(err) })+ }+})+`++// ─── Types ────────────────────────────────────────────────────────────────────++export interface ProcessInput {+ filePath?: string+ text?: string+ /** Per-slot texts for multi-text-input nodes (index = target handle slot). */+ texts?: (string | undefined)[]+ nodeId?: string+}++export interface ProcessResult {+ filePath?: string+ text?: string+}++export interface IProcessRunner {+ run(+ input: ProcessInput,+ params: Record<string, unknown>,+ onProgress?: (percent: number, label: string) => void,+ onLog?: (message: string) => void,+ ): Promise<ProcessResult>+ terminate(): void+}++// ─── JS ProcessRunner (Worker thread) ────────────────────────────────────────++export class ProcessRunner implements IProcessRunner {+ private worker: Worker | null = null+ private ready: boolean = false+ private extDir: string+ private entry: string+ private workspaceDir: string+ private tempDir: string++ constructor(extDir: string, entry: string, workspaceDir: string, tempDir: string) {+ this.extDir = extDir+ this.entry = entry+ this.workspaceDir = workspaceDir+ this.tempDir = tempDir+ }++ private async ensureReady(): Promise<void> {+ if (this.ready && this.worker) return++ return new Promise((resolve, reject) => {+ const worker = new Worker(WORKER_CODE, {+ eval: true,+ workerData: {+ extDir: this.extDir,+ entry: this.entry,+ workspaceDir: this.workspaceDir,+ tempDir: this.tempDir,+ },+ })++ worker.once('message', (msg) => {+ if (msg.type === 'ready') {+ this.worker = worker+ this.ready = true+ resolve()+ } else if (msg.type === 'error') {+ worker.terminate()+ reject(new Error(msg.message))+ }+ })++ worker.once('error', (err) => {+ reject(err)+ })++ // A worker can also die between runs (e.g. a timer the processor left+ // behind throws after it returned). Forget it whenever it exits, so the+ // next run starts a fresh one instead of posting into a dead thread.+ worker.once('exit', () => this.discardWorker(worker))+ })+ }++ async run(+ input: ProcessInput,+ params: Record<string, unknown>,+ onProgress?: (percent: number, label: string) => void,+ onLog?: (message: string) => void,+ ): Promise<ProcessResult> {+ await this.ensureReady()+ const worker = this.worker!++ return new Promise((resolve, reject) => {+ const settle = () => {+ worker.off('message', handler)+ worker.off('error', onError)+ worker.off('exit', onExit)+ }+ const handler = (msg: { type: string; result?: ProcessResult; message?: string; percent?: number; label?: string }) => {+ if (msg.type === 'progress') {+ onProgress?.(msg.percent ?? 0, msg.label ?? '')+ } else if (msg.type === 'log') {+ onLog?.(msg.message ?? '')+ } else if (msg.type === 'done') {+ settle()+ resolve(msg.result ?? {})+ } else if (msg.type === 'error') {+ settle()+ reject(new Error(msg.message))+ }+ }+ // A worker that dies mid-run (an uncaught error, out of memory,+ // process.exit) never posts 'done' or 'error'. Settle the run instead of+ // waiting forever, and drop the dead worker so the next run starts a+ // fresh one rather than posting into it.+ const onError = (err: Error) => {+ settle()+ this.discardWorker(worker)+ reject(err)+ }+ const onExit = (code: number) => {+ settle()+ this.discardWorker(worker)+ reject(new Error(`Process extension worker exited with code ${code}`))+ }++ worker.on('message', handler)+ worker.on('error', onError)+ worker.on('exit', onExit)+ worker.postMessage({ action: 'run', input, params })+ })+ }++ private discardWorker(worker: Worker): void {+ if (this.worker !== worker) return+ this.worker = null+ this.ready = false+ }++ terminate(): void {+ this.worker?.terminate()+ this.worker = null+ this.ready = false+ }+}++// ─── Python ProcessRunner (subprocess, one process per run) ───────────────────+//+// Protocol — stdin: one JSON line { input, params, workspaceDir, tempDir }+// Protocol — stdout: JSON lines { type: 'progress'|'log'|'done'|'error', ... }++export class PythonProcessRunner implements IProcessRunner {+ private pythonExe: string+ private extDir: string+ private scriptPath: string+ private workspaceDir: string+ private tempDir: string++ constructor(pythonExe: string, extDir: string, entry: string, workspaceDir: string, tempDir: string) {+ this.pythonExe = pythonExe+ this.extDir = extDir+ this.scriptPath = join(extDir, entry)+ this.workspaceDir = workspaceDir+ this.tempDir = tempDir+ }++ async run(+ input: ProcessInput,+ params: Record<string, unknown>,+ onProgress?: (percent: number, label: string) => void,+ onLog?: (message: string) => void,+ ): Promise<ProcessResult> {+ return new Promise((resolve, reject) => {+ const proc = spawn(this.pythonExe, [this.scriptPath], {+ stdio: ['pipe', 'pipe', 'pipe'],+ env: {+ ...process.env,+ // Force UTF-8 stdio so Unicode prints from process extensions do not+ // crash under legacy Windows codepages (cp1252/cp932).+ PYTHONUTF8: '1',+ // Built-in process nodes may import shared services from the backend.+ MODLY_API_DIR: app.isPackaged+ ? join(process.resourcesPath, 'api')+ : join(app.getAppPath(), 'api'),+ // Electron is also the packaged Node runtime. meshopt_runner.cjs uses+ // ELECTRON_RUN_AS_NODE when it launches this executable.+ MODLY_NODE_EXECUTABLE: process.execPath,+ EXTENSION_DIR: this.extDir,+ WORKSPACE_DIR: this.workspaceDir,+ TEMP_DIR: this.tempDir,+ },+ })++ // Send input as a single JSON line on stdin+ proc.stdin.write(JSON.stringify({+ input,+ params,+ nodeId: input.nodeId ?? '',+ workspaceDir: this.workspaceDir,+ tempDir: this.tempDir,+ }) + '\n')+ proc.stdin.end()++ let stdoutBuf = ''+ let resolved = false++ proc.stdout.on('data', (chunk: Buffer) => {+ stdoutBuf += chunk.toString()+ const lines = stdoutBuf.split('\n')+ stdoutBuf = lines.pop() ?? ''++ for (const line of lines) {+ const trimmed = line.trim()+ if (!trimmed) continue+ try {+ const msg = JSON.parse(trimmed) as { type: string; percent?: number; label?: string; message?: string; result?: ProcessResult }+ if (msg.type === 'progress') {+ onProgress?.(msg.percent ?? 0, msg.label ?? '')+ } else if (msg.type === 'log') {+ onLog?.(msg.message ?? '')+ } else if (msg.type === 'done') {+ resolved = true+ resolve(msg.result ?? {})+ } else if (msg.type === 'error') {+ resolved = true+ reject(new Error(msg.message ?? 'Unknown error'))+ }+ } catch {+ // Non-JSON stdout line — treat as a log message+ onLog?.(trimmed)+ }+ }+ })++ let stderrBuf = ''+ proc.stderr.on('data', (chunk: Buffer) => {+ stderrBuf += chunk.toString()+ })++ proc.on('close', (code) => {+ if (!resolved) {+ if (code === 0) {+ resolve({})+ } else {+ reject(new Error(stderrBuf.trim() || `Python process exited with code ${code}`))+ }+ }+ })++ proc.on('error', (err) => {+ if (!resolved) {+ resolved = true+ reject(err)+ }+ })+ })+ }++ // Python processes are spawned per run — nothing persistent to terminate+ terminate(): void {}+}++// ─── Helper: find Python executable for an extension ─────────────────────────++export function getExtPythonExe(extDir: string): string | null {+ const candidates = process.platform === 'win32'+ ? [join(extDir, 'venv', 'Scripts', 'python.exe')]+ : [join(extDir, 'venv', 'bin', 'python'), join(extDir, 'venv', 'bin', 'python3')]++ for (const p of candidates) {+ if (existsSync(p)) return p+ }+ return null+}++// ─── Registry (one runner per extension id, reused across calls) ──────────────++const registry = new Map<string, IProcessRunner>()+// The arguments each cached runner was built with. A runner bakes them in at+// construction, so a call with different ones — e.g. after the workspace is+// moved in Settings, which updates paths without a restart — must not get the+// old runner back, or node output keeps landing in the previous folder.+const registryArgs = new Map<string, string>()++function canReuseRunner(extensionId: string, args: string[]): boolean {+ const key = JSON.stringify(args)+ if (registry.has(extensionId) && registryArgs.get(extensionId) === key) return true+ terminateProcessRunner(extensionId)+ registryArgs.set(extensionId, key)+ return false+}++export function getProcessRunner(+ extensionId: string,+ extDir: string,+ entry: string,+ workspaceDir: string,+ tempDir: string,+): ProcessRunner {+ if (!canReuseRunner(extensionId, [extDir, entry, workspaceDir, tempDir])) {+ registry.set(extensionId, new ProcessRunner(extDir, entry, workspaceDir, tempDir))+ }+ return registry.get(extensionId)! as ProcessRunner+}++export function getPythonProcessRunner(+ extensionId: string,+ pythonExe: string,+ extDir: string,+ entry: string,+ workspaceDir: string,+ tempDir: string,+): PythonProcessRunner {+ if (!canReuseRunner(extensionId, [pythonExe, extDir, entry, workspaceDir, tempDir])) {+ registry.set(extensionId, new PythonProcessRunner(pythonExe, extDir, entry, workspaceDir, tempDir))+ }+ return registry.get(extensionId)! as PythonProcessRunner+}++export function terminateProcessRunner(extensionId: string): void {+ registry.get(extensionId)?.terminate()+ registry.delete(extensionId)+}++export function terminateAllProcessRunners(): void {+ for (const runner of registry.values()) runner.terminate()+ registry.clear()+}diff --git a/apps/forge-desktop/electron/main/python-bridge.ts b/apps/forge-desktop/electron/main/python-bridge.tsnew file mode 100644index 000000000..87aa2b6b5--- /dev/null+++ b/apps/forge-desktop/electron/main/python-bridge.ts@@ -0,0 +1,258 @@+import { ChildProcess, spawn } from 'child_process'+import { join } from 'path'+import { app, BrowserWindow } from 'electron'+import { existsSync, mkdirSync } from 'fs'+import axios from 'axios'+import { ensureAgentDir, getSettings } from './settings-store'+import { getHfToken } from './hf-token'+import { logger } from './logger'+import { cleanPythonEnv, getVenvPythonExe } from './python-setup'++const API_PORT = 8765+const API_HOST = '127.0.0.1'+export const API_BASE_URL = `http://${API_HOST}:${API_PORT}`++export class PythonBridge {+ private process: ChildProcess | null = null+ private ready = false+ private startPromise: Promise<void> | null = null+ private getWindow: (() => BrowserWindow | null) | null = null+ private intentionalStop = false++ setWindowGetter(fn: () => BrowserWindow | null): void {+ this.getWindow = fn+ }++ async start(): Promise<void> {+ if (this.ready) return+ if (this.startPromise) return this.startPromise+ this.startPromise = this._start()+ try {+ await this.startPromise+ } finally {+ this.startPromise = null+ }+ }++ private async _start(): Promise<void> {+ if (this.process) {+ await this.waitUntilReady()+ return+ }++ const pythonExecutable = this.resolvePythonExecutable()+ const apiDir = this.resolveApiDir()++ console.log('[PythonBridge] Starting FastAPI at', apiDir)+ console.log('[PythonBridge] Python executable:', pythonExecutable)++ await this.killProcessOnPort()++ this.process = spawn(pythonExecutable, ['-m', 'uvicorn', 'main:app', '--host', API_HOST, '--port', String(API_PORT)], {+ cwd: apiDir,+ env: {+ ...cleanPythonEnv(),+ PYTHONUNBUFFERED: '1',+ // mesh_ops uses Electron in Node mode for the existing meshoptimizer+ // backend, so packaged builds do not depend on a system Node install.+ MODLY_NODE_EXECUTABLE: process.execPath,+ // We decode both pipes as UTF-8 below (Buffer.toString() default), and+ // the API forwards extension output — tqdm bars included — through its+ // own stderr. Without this the API would encode them with the Windows+ // locale codec and the HUD log pane would show █ escapes.+ PYTHONIOENCODING: 'utf-8',+ // No PYTHONPATH needed - the venv's Python has its own isolated site-packages+ MODELS_DIR: this.resolveModelsDir(),+ WORKSPACE_DIR: this.resolveWorkspaceDir(),+ EXTENSIONS_DIR: this.resolveExtensionsDir(),+ // llm_server.py keeps everything of the local LLM here: engine, GGUF models, logs, config.+ MODLY_LLM_DIR: this.resolveAgentDir(),+ SELECTED_MODEL_ID: process.env['SELECTED_MODEL_ID'] ?? '',+ HUGGING_FACE_HUB_TOKEN: this.resolveHfToken(),+ HF_TOKEN: this.resolveHfToken(),+ },+ // On Unix, put the bridge in its own process group so every subprocess+ // it spawns (extension runners, etc.) inherits that group. On shutdown+ // we SIGKILL the whole group (negative PID) to take them all out+ // together — otherwise children get reparented to launchd and keep+ // holding MPS-wired memory until the user kills them manually.+ detached: process.platform !== 'win32',+ })++ this.process.stdout?.on('data', (data) => {+ const msg = data.toString().trim()+ console.log('[FastAPI]', msg)+ logger.python(msg)+ this.emitTqdmLog(msg)+ })++ this.process.stderr?.on('data', (data) => {+ const msg = data.toString().trim()+ console.error('[FastAPI]', msg)+ logger.python(`[stderr] ${msg}`)+ this.emitTqdmLog(msg)+ })++ this.process.on('exit', (code) => {+ const wasReady = this.ready+ console.log('[PythonBridge] Process exited with code', code)+ this.ready = false+ this.process = null+ if (wasReady && !this.intentionalStop) {+ const getWindow = this.getWindow+ if (!getWindow) return+ const win = getWindow()+ const contents = win?.webContents+ if (contents && !contents.isDestroyed()) {+ contents.send('python:crashed', { code })+ }+ }+ })++ await this.waitUntilReady()+ }++ async stop(): Promise<void> {+ if (!this.process) return+ const proc = this.process+ this.process = null+ this.ready = false+ if (process.platform === 'win32') {+ const { execSync } = require('child_process')+ try { execSync(`taskkill /PID ${proc.pid} /T /F`) } catch {}+ } else if (proc.pid) {+ // Kill the entire process group (negative PID) so extension subprocesses+ // die with the bridge instead of being orphaned to launchd. SIGKILL+ // rather than SIGTERM: on app quit we want immediate release of Metal+ // wired memory, not a polite request the subprocess might ignore while+ // it finishes an operation.+ try {+ process.kill(-proc.pid, 'SIGKILL')+ } catch {+ try { proc.kill('SIGKILL') } catch {}+ }+ }+ console.log('[PythonBridge] Stopped')+ }++ async restart(): Promise<void> {+ console.log('[PythonBridge] Restarting to free memory…')+ this.intentionalStop = true+ await this.stop()+ this.intentionalStop = false+ await this.start()+ }++ private emitTqdmLog(raw: string): void {+ if (/INFO/.test(raw)) return+ if (!raw.trim()) return+ const getWindow = this.getWindow+ if (!getWindow) return+ const win = getWindow()+ const contents = win?.webContents+ if (contents && !contents.isDestroyed()) {+ contents.send('python:log', raw.trim())+ }+ }++ isReady(): boolean { return this.ready }+ getPort(): number { return API_PORT }++ private async killProcessOnPort(): Promise<void> {+ const { execSync } = require('child_process')++ if (process.platform !== 'win32') {+ try { execSync(`lsof -ti tcp:${API_PORT} | xargs kill -9 2>/dev/null || true`, { shell: true }) } catch {}+ return+ }++ for (let attempt = 0; attempt < 3; attempt++) {+ let output = ''+ try {+ output = execSync(`netstat -ano | findstr ":${API_PORT} "`, { encoding: 'utf8', shell: true }) as string+ } catch { break }++ const pids = new Set<string>()+ for (const line of output.split('\n')) {+ const match = line.trim().match(/\s+(\d+)$/)+ if (match && match[1] !== '0') pids.add(match[1])+ }+ if (pids.size === 0) break++ for (const pid of pids) {+ try { execSync(`taskkill /PID ${pid} /T /F`, { shell: true }) } catch {}+ }+ await new Promise((r) => setTimeout(r, 300))+ }+ }++ private async waitUntilReady(maxRetries = 180, delayMs = 500): Promise<void> {+ for (let i = 0; i < maxRetries; i++) {+ if (!this.process) throw new Error('FastAPI process exited unexpectedly during startup')+ try {+ await axios.get(`${API_BASE_URL}/health`, { timeout: 2000 })+ this.ready = true+ console.log('[PythonBridge] FastAPI is ready')+ return+ } catch {+ await new Promise((r) => setTimeout(r, delayMs))+ }+ }+ throw new Error('FastAPI did not start in time')+ }++ private resolvePythonExecutable(): string {+ const userData = app.getPath('userData')+ const apiDir = this.resolveApiDir()++ // Primary: venv created during setup (bundled Python → isolated venv)+ const venvPython = getVenvPythonExe(userData)+ if (existsSync(venvPython)) return venvPython++ // Dev fallback: local .venv in the api directory+ const devCandidates = [+ join(apiDir, '.venv', 'Scripts', 'python.exe'),+ join(apiDir, '.venv', 'bin', 'python'),+ ]+ for (const c of devCandidates) {+ if (existsSync(c)) return c+ }++ // Never fall back to bare 'python' on Windows — it would be the user's system Python+ if (process.platform === 'win32') {+ throw new Error('Python venv not found. Please restart the application to re-run setup.')+ }+ return 'python3'+ }++ private resolveApiDir(): string {+ if (app.isPackaged) return join(process.resourcesPath, 'api')+ return join(app.getAppPath(), 'api')+ }++ private resolveModelsDir(): string {+ const s = getSettings(app.getPath('userData'))+ mkdirSync(s.modelsDir, { recursive: true })+ return s.modelsDir+ }++ private resolveWorkspaceDir(): string {+ const s = getSettings(app.getPath('userData'))+ mkdirSync(s.workspaceDir, { recursive: true })+ return s.workspaceDir+ }++ private resolveExtensionsDir(): string {+ const s = getSettings(app.getPath('userData'))+ mkdirSync(s.extensionsDir, { recursive: true })+ return s.extensionsDir+ }++ private resolveAgentDir(): string {+ return ensureAgentDir(app.getPath('userData'))+ }++ private resolveHfToken(): string {+ return getHfToken() // decrypted cache — settings.json holds the ciphertext+ }+}diff --git a/apps/forge-desktop/electron/main/python-setup.ts b/apps/forge-desktop/electron/main/python-setup.tsnew file mode 100644index 000000000..13e86a251--- /dev/null+++ b/apps/forge-desktop/electron/main/python-setup.ts@@ -0,0 +1,337 @@+import { BrowserWindow, app } from 'electron'+import { existsSync, readFileSync, writeFileSync } from 'fs'+import { rm, mkdir } from 'fs/promises'+import { join } from 'path'+import { spawn, execSync } from 'child_process'+import { createHash } from 'crypto'+import { getSettings } from './settings-store'+import { copyRuntimeTree } from './copy-runtime'++const SETUP_VERSION = 3++interface SetupJson {+ version: number+ requirementsHash?: string+}++function getRequirementsPath(): string {+ return app.isPackaged+ ? join(process.resourcesPath, 'api', 'requirements.txt')+ : join(app.getAppPath(), 'api', 'requirements.txt')+}++function hashRequirements(): string {+ try {+ const content = readFileSync(getRequirementsPath(), 'utf-8')+ return createHash('sha256').update(content).digest('hex')+ } catch {+ return ''+ }+}++// ─── Environment ─────────────────────────────────────────────────────────────++/**+ * Clean environment for spawning Python/pip.+ * Strips vars that could redirect imports or installs to the user's system Python.+ */+export function cleanPythonEnv(): NodeJS.ProcessEnv {+ const {+ PYTHONHOME, PYTHONPATH, PYTHONSTARTUP, PYTHONUSERBASE,+ PIP_USER, PIP_TARGET, PIP_PREFIX, PIP_REQUIRE_VIRTUALENV,+ VIRTUAL_ENV, CONDA_PREFIX,+ ...rest+ } = process.env+ void PYTHONHOME; void PYTHONPATH; void PYTHONSTARTUP; void PYTHONUSERBASE+ void PIP_USER; void PIP_TARGET; void PIP_PREFIX; void PIP_REQUIRE_VIRTUALENV+ void VIRTUAL_ENV; void CONDA_PREFIX+ return rest+}++// ─── Path helpers ─────────────────────────────────────────────────────────────++export function getEmbeddedPythonDir(): string {+ if (app.isPackaged) return join(process.resourcesPath, 'python-embed')+ return join(app.getAppPath(), 'resources', 'python-embed')+}++export function getEmbeddedPythonExe(): string {+ const dir = getEmbeddedPythonDir()+ return process.platform === 'win32' ? join(dir, 'python.exe') : join(dir, 'bin', 'python3')+}++/** Venv lives inside dependenciesDir on Windows (user-configurable drive), userData on Linux. */+export function getVenvDir(userData: string): string {+ if (process.platform === 'win32') {+ return join(getSettings(userData).dependenciesDir, 'venv')+ }+ return join(userData, 'venv')+}++export function getVenvPythonExe(userData: string): string {+ const venvDir = getVenvDir(userData)+ return process.platform === 'win32'+ ? join(venvDir, 'Scripts', 'python.exe')+ : join(venvDir, 'bin', 'python')+}++// ─── Setup state ──────────────────────────────────────────────────────────────++export function checkSetupNeeded(userData: string): boolean {+ const jsonPath = join(userData, 'python_setup.json')+ if (!existsSync(jsonPath)) return true+ try {+ const data = JSON.parse(readFileSync(jsonPath, 'utf-8')) as SetupJson+ if (data.version < SETUP_VERSION) return true+ if (data.requirementsHash !== hashRequirements()) return true+ } catch {+ return true+ }+ if (!existsSync(getVenvPythonExe(userData))) return true+ return false+}++/**+ * Write a sitecustomize.py into the venv that silently skips malformed certs+ * in the Windows certificate store (ssl.SSLError: [ASN1] nested asn1 error).+ * Python imports sitecustomize automatically on every startup.+ * No-op on non-Windows or if the patch already exists.+ */+/**+ * Returns the path to certifi's cacert.pem inside the venv, or undefined if not found.+ * Used to set SSL_CERT_FILE / REQUESTS_CA_BUNDLE for python-embed subprocesses,+ * which ship without a CA bundle on Windows.+ */+export function getCertifiBundle(userData: string): string | undefined {+ const venvDir = getVenvDir(userData)+ // Windows venv layout: Lib/site-packages/certifi/cacert.pem+ const winPath = join(venvDir, 'Lib', 'site-packages', 'certifi', 'cacert.pem')+ if (existsSync(winPath)) return winPath+ // Linux/macOS venv layout: lib/pythonX.Y/site-packages/certifi/cacert.pem+ const libDir = join(venvDir, 'lib')+ if (existsSync(libDir)) {+ try {+ const { readdirSync } = require('fs') as typeof import('fs')+ for (const entry of readdirSync(libDir)) {+ const candidate = join(libDir, entry, 'site-packages', 'certifi', 'cacert.pem')+ if (existsSync(candidate)) return candidate+ }+ } catch { /* ignore */ }+ }+ return undefined+}++export function ensureSslPatch(userData: string): void {+ if (process.platform !== 'win32') return+ const venvDir = getVenvDir(userData)+ const sitePkg = join(venvDir, 'Lib', 'site-packages')+ const target = join(sitePkg, 'sitecustomize.py')+ if (!existsSync(sitePkg)) return+ if (existsSync(target)) return+ writeFileSync(target, [+ 'try:',+ ' import ssl as _ssl',+ ' _orig = _ssl.SSLContext._load_windows_store_certs',+ ' def _safe(self, storename, purpose):',+ ' try:',+ ' _orig(self, storename, purpose)',+ ' except _ssl.SSLError:',+ ' pass',+ ' _ssl.SSLContext._load_windows_store_certs = _safe',+ 'except Exception:',+ ' pass',+ '',+ ].join('\n'), 'utf-8')+}++export function markSetupDone(userData: string): void {+ writeFileSync(+ join(userData, 'python_setup.json'),+ JSON.stringify({ version: SETUP_VERSION, requirementsHash: hashRequirements() }),+ 'utf-8'+ )+}++// ─── AppImage: stable Python runtime ─────────────────────────────────────────++/**+ * On Linux AppImage, process.resourcesPath resolves to an ephemeral mount point+ * (/tmp/.mount_Modly-XXXXXX/) that changes every launch, which breaks venv symlinks.+ * This copies the bundled Python runtime to a stable userData path once per app version.+ */+async function ensureStableEmbeddedPython(userData: string, win: BrowserWindow): Promise<string> {+ const stableDir = join(userData, 'python-embed')+ const stableExe = join(stableDir, 'bin', 'python3')+ const versionFile = join(stableDir, '.app-version')+ const currentVersion = app.getVersion()++ const alreadyCopied =+ existsSync(stableExe) &&+ existsSync(versionFile) &&+ readFileSync(versionFile, 'utf-8').trim() === currentVersion++ if (!alreadyCopied) {+ win.webContents.send('setup:progress', { step: 'venv', percent: 2 })+ console.log('[PythonSetup] Extracting Python runtime to stable path:', stableDir)+ if (existsSync(stableDir)) {+ await rm(stableDir, { recursive: true, force: true })+ }+ await mkdir(stableDir, { recursive: true })+ await copyRuntimeTree(getEmbeddedPythonDir(), stableDir)+ writeFileSync(versionFile, currentVersion, 'utf-8')+ console.log('[PythonSetup] Python runtime ready at:', stableDir)+ }++ return stableExe+}++// ─── Setup steps ─────────────────────────────────────────────────────────────++function createVenv(pythonExe: string, venvDir: string, win: BrowserWindow): Promise<void> {+ return new Promise((resolve, reject) => {+ win.webContents.send('setup:progress', { step: 'venv', percent: 5 })+ console.log('[PythonSetup] Creating venv at', venvDir)+ const proc = spawn(pythonExe, ['-m', 'venv', '--clear', venvDir], {+ stdio: ['ignore', 'pipe', 'pipe'],+ env: cleanPythonEnv(),+ })+ let stderrOut = ''+ proc.stdout?.on('data', (d: Buffer) => console.log('[venv]', d.toString().trim()))+ proc.stderr?.on('data', (d: Buffer) => {+ const text = d.toString().trim()+ if (text) { console.error('[venv]', text); stderrOut += text + '\n' }+ })+ proc.on('close', (code) => {+ if (code === 0) {+ win.webContents.send('setup:progress', { step: 'venv', percent: 20 })+ resolve()+ } else {+ let msg = `python -m venv exited with code ${code}`+ if (stderrOut) msg += `\n\n${stderrOut.trim()}`+ if (process.platform === 'win32') {+ msg +=+ '\n\nYour antivirus may be blocking the Python runtime.' ++ `\nTry adding an exclusion for:\n ${pythonExe}` ++ '\nOr temporarily pause real-time protection, then click Retry.'+ }+ reject(new Error(msg))+ }+ })+ })+}++function installRequirements(+ pythonExe: string,+ requirementsPath: string,+ win: BrowserWindow+): Promise<void> {+ const TOTAL_PACKAGES = 20+ return new Promise((resolve, reject) => {+ console.log('[PythonSetup] Installing requirements with', pythonExe)+ const proc = spawn(+ pythonExe,+ ['-m', 'pip', 'install', '-r', requirementsPath, '--no-warn-script-location', '--progress-bar', 'off'],+ { stdio: ['ignore', 'pipe', 'pipe'], env: cleanPythonEnv() }+ )+ let packagesInstalled = 0+ const onLine = (line: string) => {+ console.log('[pip]', line)+ let currentPackage: string | undefined+ const collectMatch = line.match(/^Collecting (.+?)(?:\s|$)/)+ if (collectMatch) { packagesInstalled++; currentPackage = collectMatch[1] }+ const downloadMatch = line.match(/^Downloading (.+?)(?:\s|$)/)+ if (downloadMatch) currentPackage = `Downloading ${downloadMatch[1]}…`+ const percent = Math.round(20 + (packagesInstalled / TOTAL_PACKAGES) * 79)+ win.webContents.send('setup:progress', {+ step: 'packages',+ percent: Math.min(percent, 99),+ currentPackage,+ })+ }+ let buffer = ''+ proc.stdout?.on('data', (d: Buffer) => {+ buffer += d.toString()+ const lines = buffer.split('\n')+ buffer = lines.pop() ?? ''+ lines.forEach((l) => onLine(l.trim()))+ })+ proc.stderr?.on('data', (d: Buffer) => {+ const text = d.toString().trim()+ if (text) console.error('[pip]', text)+ })+ proc.on('close', (code) => {+ if (code === 0) {+ win.webContents.send('setup:progress', { step: 'packages', percent: 100 })+ resolve()+ } else {+ reject(new Error(`pip install exited with code ${code}`))+ }+ })+ })+}++// ─── Unix dev helper ─────────────────────────────────────────────────────────++function findSystemPython(): string {+ const candidates = ['python3.12', 'python3.11', 'python3.10', 'python3', 'python']+ for (const cmd of candidates) {+ try {+ const out = execSync(`${cmd} --version`, { encoding: 'utf8', timeout: 3000 }).trim()+ if (out.startsWith('Python 3.')) {+ console.log(`[PythonSetup] Found system Python: ${cmd} → ${out}`)+ return cmd+ }+ } catch { /* not found */ }+ }+ throw new Error(+ 'Python 3 not found on your system.\n' ++ 'Please install Python 3.10+ and try again.\n' ++ 'Ubuntu/Debian : sudo apt install python3 python3-venv\n' ++ 'macOS : brew install [email protected]'+ )+}++// ─── Public orchestrator ──────────────────────────────────────────────────────++export async function runFullSetup(win: BrowserWindow, userData: string): Promise<void> {+ try {+ const requirementsPath = getRequirementsPath()+ const venvDir = getVenvDir(userData)++ if (process.platform === 'linux' && app.isPackaged) {+ // AppImage: process.resourcesPath is ephemeral — copy Python to stable userData path first+ const pythonExe = await ensureStableEmbeddedPython(userData, win)+ await createVenv(pythonExe, venvDir, win)+ const venvPython = getVenvPythonExe(userData)+ await installRequirements(venvPython, requirementsPath, win)+ } else if (process.platform === 'win32' || app.isPackaged) {+ // Windows (dev + packaged) or macOS packaged: bundled Python path is stable+ const pythonExe = getEmbeddedPythonExe()+ if (!existsSync(pythonExe)) {+ throw new Error(+ 'Bundled Python runtime not found.\n' ++ 'Please reinstall the application.\n' ++ `(expected: ${pythonExe})`+ )+ }+ await createVenv(pythonExe, venvDir, win)+ const venvPython = getVenvPythonExe(userData)+ await installRequirements(venvPython, requirementsPath, win)+ } else {+ // Linux / macOS dev: use system Python+ win.webContents.send('setup:progress', { step: 'venv', percent: 5 })+ const python3 = findSystemPython()+ await createVenv(python3, venvDir, win)+ const venvPython = getVenvPythonExe(userData)+ await installRequirements(venvPython, requirementsPath, win)+ }++ win.webContents.send('setup:complete')+ console.log('[PythonSetup] Setup complete')+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err)+ console.error('[PythonSetup] Error:', message)+ win.webContents.send('setup:error', { message })+ throw err+ }+}diff --git a/apps/forge-desktop/electron/main/secure-store.ts b/apps/forge-desktop/electron/main/secure-store.tsnew file mode 100644index 000000000..7c70cd27f--- /dev/null+++ b/apps/forge-desktop/electron/main/secure-store.ts@@ -0,0 +1,78 @@+import { safeStorage } from 'electron'+import { logger } from './logger'++// Secrets that safeStorage couldn't encrypt (no OS keychain available, e.g. some+// Linux setups without a keyring) are stored with this prefix so decryptSecret+// can tell them apart from a real ciphertext and hand them back unchanged.+const PLAINTEXT_PREFIX = 'plain:'++let warnedOnce = false++// Electron 33 (pinned in package.json) only ships the synchronous safeStorage+// API — encryptStringAsync/decryptStringAsync/isAsyncEncryptionAvailable were+// added in a later Electron release. The sync calls are cheap (no disk I/O,+// just OS keychain/DPAPI crypto), so wrapping them in an async function here+// is only to keep the IPC handler signature uniform, not for a real await.++export function encryptSecretSync(plainText: string): string {+ if (!plainText) return plainText++ if (!safeStorage.isEncryptionAvailable()) {+ if (!warnedOnce) {+ warnedOnce = true+ logger.warn('[secure-store] OS-level encryption unavailable — storing secrets in plain text')+ }+ return PLAINTEXT_PREFIX + plainText+ }++ return safeStorage.encryptString(plainText).toString('hex')+}++/**+ * True when `stored` has the shape encryptSecretSync produces: a hex blob+ * starting with Chromium OSCrypt's version tag ("v10", "v11", …). The tag+ * matters — hex alone also matched plaintext API keys that happen to be hex+ * (common for self-hosted endpoints), which then "failed to decrypt" and were+ * wiped during the migration instead of encrypted. Used to tell "this was never encrypted" apart from "this IS one of+ * our blobs but decryption just failed" — the two must not be confused: DPAPI+ * keys are per-OS-user, so a restored backup or a different Windows account+ * makes decryption fail on a perfectly valid ciphertext. Treating that as+ * plaintext would hand the ciphertext out as a credential and then re-encrypt+ * it, destroying the secret for good.+ */+function looksEncrypted(stored: string): boolean {+ return stored.length >= 32 && /^76(3[0-9]){2}([0-9a-f]{2})+$/i.test(stored)+}++/**+ * Returns the plaintext, or `null` when `stored` is one of our blobs that could+ * not be decrypted. A value that was never encrypted comes back unchanged, so+ * callers can migrate it.+ */+export function decryptSecretSync(stored: string): string | null {+ if (!stored) return stored+ if (stored.startsWith(PLAINTEXT_PREFIX)) return stored.slice(PLAINTEXT_PREFIX.length)++ if (!looksEncrypted(stored)) return stored // legacy plaintext, saved before encryption existed++ try {+ return safeStorage.decryptString(Buffer.from(stored, 'hex'))+ } catch (err) {+ logger.error(+ '[secure-store] a stored secret could not be decrypted — it was encrypted by a ' ++ `different OS user or machine. It must be re-entered. (${err})`,+ )+ return null+ }+}++// Async wrappers kept for the IPC handlers, whose signatures are all async.+export async function encryptSecret(plainText: string): Promise<string> {+ return encryptSecretSync(plainText)+}++/** `null` on an undecryptable blob — never the ciphertext, which callers would+ * otherwise use as a credential and re-encrypt. */+export async function decryptSecret(stored: string): Promise<string | null> {+ return decryptSecretSync(stored)+}diff --git a/apps/forge-desktop/electron/main/settings-store.test.mjs b/apps/forge-desktop/electron/main/settings-store.test.mjsnew file mode 100644index 000000000..06a78fc1f--- /dev/null+++ b/apps/forge-desktop/electron/main/settings-store.test.mjs@@ -0,0 +1,79 @@+/**+ * The agent's folder (local LLM engine, GGUF models, logs) sits beside the+ * other data folders. Installs set up before it existed have models/,+ * extensions/, … under the base they picked at first run, so an unsaved+ * agentDir must land next to those, not in userData.+ */+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'+import vm from 'node:vm'++function loadModule() {+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('electron/main/settings-store.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ const module = { exports: {} }+ vm.runInNewContext(result.outputFiles[0].text, { module, exports: module.exports, require })+ return module.exports+}++const { getSettings, setSettings, ensureAgentDir } = loadModule()++test('a fresh install puts the agent folder in userData beside the others', () => {+ const userData = mkdtempSync(join(tmpdir(), 'modly-settings-'))+ const s = getSettings(userData)+ assert.equal(s.agentDir, join(userData, 'agent'))+ assert.equal(s.modelsDir, join(userData, 'models'))+})++test('an existing install gets the agent folder beside its chosen data folders', () => {+ const userData = mkdtempSync(join(tmpdir(), 'modly-settings-'))+ const base = join(userData, 'Documents', 'Modly')+ writeFileSync(join(userData, 'settings.json'), JSON.stringify({+ modelsDir: join(base, 'models'),+ workspaceDir: join(base, 'workspace'),+ extensionsDir: join(base, 'extensions'),+ }))+ assert.equal(getSettings(userData).agentDir, join(base, 'agent'))+})++test('a saved agent folder is kept, and persists once any setting is written', () => {+ const userData = mkdtempSync(join(tmpdir(), 'modly-settings-'))+ const custom = join(userData, 'elsewhere', 'agent')+ writeFileSync(join(userData, 'settings.json'), JSON.stringify({ agentDir: custom }))+ assert.equal(getSettings(userData).agentDir, custom)++ setSettings(userData, { workflowsDir: join(userData, 'wf') })+ assert.equal(JSON.parse(readFileSync(join(userData, 'settings.json'), 'utf-8')).agentDir, custom)+})++test('an existing install gets its agent folder created and pinned at startup', () => {+ const userData = mkdtempSync(join(tmpdir(), 'modly-settings-'))+ const base = join(userData, 'Documents', 'Modly')+ writeFileSync(join(userData, 'settings.json'), JSON.stringify({ modelsDir: join(base, 'models') }))++ assert.equal(ensureAgentDir(userData), join(base, 'agent'))+ assert.equal(existsSync(join(base, 'agent')), true)+ assert.equal(JSON.parse(readFileSync(join(userData, 'settings.json'), 'utf-8')).agentDir, join(base, 'agent'))++ // Pinned: moving the models folder afterwards leaves the agent folder where it is.+ setSettings(userData, { modelsDir: join(userData, 'other-drive', 'models') })+ assert.equal(getSettings(userData).agentDir, join(base, 'agent'))+})++test('a fresh install gets its agent folder without settings.json being written', () => {+ const userData = mkdtempSync(join(tmpdir(), 'modly-settings-'))+ assert.equal(ensureAgentDir(userData), join(userData, 'agent'))+ assert.equal(existsSync(join(userData, 'agent')), true)+ assert.equal(existsSync(join(userData, 'settings.json')), false)+})diff --git a/apps/forge-desktop/electron/main/settings-store.ts b/apps/forge-desktop/electron/main/settings-store.tsnew file mode 100644index 000000000..a02797970--- /dev/null+++ b/apps/forge-desktop/electron/main/settings-store.ts@@ -0,0 +1,78 @@+import { dirname, join } from 'path'+import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs'++export interface AppSettings {+ modelsDir: string+ workspaceDir: string+ workflowsDir: string+ extensionsDir: string+ dependenciesDir: string+ /** Local LLM engine, GGUF models, logs and config used by the agent. */+ agentDir: string+ hfToken?: string+}++function settingsPath(userData: string): string {+ return join(userData, 'settings.json')+}++export function getSettings(userData: string): AppSettings {+ const defaults: Omit<AppSettings, 'agentDir'> = {+ modelsDir: join(userData, 'models'),+ workspaceDir: join(userData, 'workspace'),+ workflowsDir: join(userData, 'workflows'),+ extensionsDir: join(userData, 'extensions'),+ dependenciesDir: join(userData, 'dependencies'),+ }++ const file = settingsPath(userData)+ if (!existsSync(file)) return withAgentDir(defaults)++ try {+ const saved = JSON.parse(readFileSync(file, 'utf-8')) as Record<string, string>+ // Migrate legacy outputsDir key+ if (saved['outputsDir'] && !saved['workspaceDir']) {+ saved['workspaceDir'] = saved['outputsDir']+ delete saved['outputsDir']+ }+ return withAgentDir({ ...defaults, ...saved })+ } catch {+ return withAgentDir(defaults)+ }+}++/**+ * Installs set up before agentDir existed have their data folders under the base+ * chosen at first run (<base>/models, <base>/extensions, …). Defaulting agentDir+ * to userData would put the agent's multi-GB engine and models apart from all of+ * them, so it defaults to a sibling of modelsDir instead.+ */+function withAgentDir(settings: Omit<AppSettings, 'agentDir'> & { agentDir?: string }): AppSettings {+ return { ...settings, agentDir: settings.agentDir || join(dirname(settings.modelsDir), 'agent') }+}++/**+ * Create the agent folder, and pin it in settings.json for installs that predate+ * it. Until pinned it is derived from modelsDir, so moving the models folder in+ * Settings → Storage would silently take the agent folder (engine, GGUF models)+ * somewhere else. A fresh install has no settings.json yet: setup writes it.+ */+export function ensureAgentDir(userData: string): string {+ const { agentDir } = getSettings(userData)+ const file = settingsPath(userData)+ if (existsSync(file)) {+ let saved: Record<string, unknown> | null = null+ try {+ saved = JSON.parse(readFileSync(file, 'utf-8')) as Record<string, unknown>+ } catch { /* unreadable: leave it as is */ }+ if (saved && !saved['agentDir']) setSettings(userData, { agentDir })+ }+ mkdirSync(agentDir, { recursive: true })+ return agentDir+}++export function setSettings(userData: string, patch: Partial<AppSettings>): AppSettings {+ const updated = { ...getSettings(userData), ...patch }+ writeFileSync(settingsPath(userData), JSON.stringify(updated, null, 2), 'utf-8')+ return updated+}diff --git a/apps/forge-desktop/electron/main/setup-launcher.test.mjs b/apps/forge-desktop/electron/main/setup-launcher.test.mjsnew file mode 100644index 000000000..63d65ec2a--- /dev/null+++ b/apps/forge-desktop/electron/main/setup-launcher.test.mjs@@ -0,0 +1,338 @@+/**+ * Runs the setup launcher for real, with a stub standing in for pip, and checks+ * what the extension's pip invocation was rewritten into.+ *+ * The commands exercised below are copied from the official extensions'+ * setup.py, so a change that breaks AMD installs fails here rather than after a+ * multi-gigabyte download on a user's machine.+ */+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs'+import { spawnSync } from 'node:child_process'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-launcher-test-')), 'setup-launcher.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('electron/main/setup-launcher.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++const { SETUP_LAUNCHER_SOURCE } = loadModule()++function findPython() {+ for (const candidate of ['python3', 'python']) {+ const probe = spawnSync(candidate, ['--version'], { stdio: 'ignore' })+ if (probe.status === 0) return candidate+ }+ return null+}++const PYTHON = findPython()++// The launcher's _is_pip_command matches pip's executable spellings ahead of+// the subcommand, so the stub is named pip.py — matching how extensions invoke+// "<venv>/bin/pip".+const FAKE_PIP = `+import json, sys+with open(sys.argv[1], "w") as handle:+ json.dump(sys.argv[2:], handle)+`++/**+ * Runs a pip command through the launcher and returns the argv the stub+ * actually received, i.e. the command after every rewrite. `invoke` picks how+ * the stand-in setup.py issues the call — the shapes real extensions use.+ */+function runThroughLauncher(pipArgs, env = {}, invoke = 'run') {+ const dir = mkdtempSync(join(tmpdir(), 'modly-launcher-run-'))+ const fakePip = join(dir, 'pip.py')+ const capture = join(dir, 'captured.json')+ writeFileSync(fakePip, FAKE_PIP, 'utf8')++ const invocations = {+ run: 'subprocess.run(CMD, check=True)',+ run_kwarg: 'subprocess.run(args=CMD, check=True)',+ popen: 'proc = subprocess.Popen(CMD)\nassert proc.wait() == 0',+ check_call: 'subprocess.check_call(CMD)',+ }++ // Stands in for the extension's setup.py: issues one pip call, exactly as the+ // real ones do, and lets the launcher's patched subprocess handle it.+ const setupPy = join(dir, 'setup.py')+ writeFileSync(setupPy, [+ 'import subprocess, sys',+ `PIP = ${JSON.stringify([fakePip, capture])}`,+ `CMD = [sys.executable] + PIP + ${JSON.stringify(pipArgs)}`,+ invocations[invoke],+ ].join('\n'), 'utf8')++ const result = spawnSync(PYTHON, ['-c', SETUP_LAUNCHER_SOURCE, setupPy, '{}'], {+ encoding: 'utf8',+ env: { ...process.env, ...env },+ })+ assert.equal(result.status, 0, `launcher failed:\n${result.stderr}`)+ assert.ok(existsSync(capture), `pip stub was never invoked:\n${result.stderr}`)++ // Drop the stub's own two arguments; keep the pip command itself.+ return { argv: JSON.parse(readFileSync(capture, 'utf8')), stderr: result.stderr }+}++const ROCM_ENV = {+ MODLY_TORCH_FLAVOR: 'rocm',+ MODLY_TORCH_INDEX_URL: 'https://download.pytorch.org/whl/rocm7.2',+ MODLY_TORCH_SPECS: JSON.stringify(['torch', 'torchvision']),+}++test('ROCm shim redirects a CUDA-pinned install (triposg / trellis2 shape)', { skip: !PYTHON }, () => {+ const { argv, stderr } = runThroughLauncher(+ ['install', 'torch==2.6.0', 'torchvision==0.21.0', '--index-url', 'https://download.pytorch.org/whl/cu124'],+ ROCM_ENV,+ )++ assert.deepEqual(argv, [+ 'install',+ '--index-url', 'https://download.pytorch.org/whl/rocm7.2',+ 'torch', 'torchvision',+ ])+ assert.match(stderr, /Redirected PyTorch to ROCm wheels/)+})++test('ROCm shim rescues the CPU fallback hunyuan3d-mini forces on Windows', { skip: !PYTHON }, () => {+ // That setup.py hardcodes the CPU index when torch_flavor is rocm on Windows;+ // without this rewrite an AMD Windows user would silently get CPU-only torch.+ const { argv } = runThroughLauncher(+ ['install', 'torch==2.6.0', 'torchvision==0.21.0', '--index-url', 'https://download.pytorch.org/whl/cpu'],+ {+ ...ROCM_ENV,+ MODLY_TORCH_INDEX_URL: 'https://repo.amd.com/rocm/whl-multi-arch/',+ MODLY_TORCH_SPECS: JSON.stringify([+ 'torch[device-gfx1200]==2.11.0+rocm7.14.0',+ 'torchvision[device-gfx1200]==0.26.0+rocm7.14.0',+ ]),+ },+ )++ assert.deepEqual(argv, [+ 'install',+ '--index-url', 'https://repo.amd.com/rocm/whl-multi-arch/',+ 'torch[device-gfx1200]==2.11.0+rocm7.14.0',+ 'torchvision[device-gfx1200]==0.26.0+rocm7.14.0',+ ])+})++test('ROCm shim leaves an extension that already chose ROCm alone', { skip: !PYTHON }, () => {+ // hunyuan3d-mini's own rocm branch on Linux. Its index is kept; only the+ // requirements are normalised to what Modly resolved.+ const { argv } = runThroughLauncher(+ ['install', 'torch', 'torchvision', '--index-url', 'https://download.pytorch.org/whl/rocm7.2'],+ ROCM_ENV,+ )++ assert.deepEqual(argv, [+ 'install',+ 'torch', 'torchvision',+ '--index-url', 'https://download.pytorch.org/whl/rocm7.2',+ ])+})++test('ROCm shim replaces the pinned direct wheel URLs of the ARM64 path', { skip: !PYTHON }, () => {+ const { argv } = runThroughLauncher(+ [+ 'install', '--retries', '10',+ '--extra-index-url', 'https://download.pytorch.org/whl/cu128',+ 'https://download-r2.pytorch.org/whl/cu128/torch-2.7.0%2Bcu128-cp311-cp311-manylinux_2_28_aarch64.whl',+ 'https://download-r2.pytorch.org/whl/cu128/torchvision-0.22.0-cp311-cp311-manylinux_2_28_aarch64.whl',+ ],+ ROCM_ENV,+ )++ assert.deepEqual(argv, [+ 'install', '--retries', '10',+ '--index-url', 'https://download.pytorch.org/whl/rocm7.2',+ 'torch', 'torchvision',+ ])+})++test('ROCm shim handles the --index-url=VALUE spelling', { skip: !PYTHON }, () => {+ const { argv } = runThroughLauncher(+ ['install', '--index-url=https://download.pytorch.org/whl/cu124', 'torch==2.6.0'],+ ROCM_ENV,+ )++ assert.deepEqual(argv, [+ 'install',+ '--index-url', 'https://download.pytorch.org/whl/rocm7.2',+ 'torch', 'torchvision',+ ])+})++test('ROCm shim leaves non-torch installs untouched', { skip: !PYTHON }, () => {+ // The bulk of every setup.py: core deps, rembg, etc. Nothing here is ours to+ // rewrite, and an extra --index-url would send them to the ROCm index.+ const original = ['install', 'Pillow', 'numpy', 'trimesh', 'rembg', 'onnxruntime']+ const { argv } = runThroughLauncher(original, ROCM_ENV)+ assert.deepEqual(argv, original)+})++test('ROCm shim keeps PyPI reachable when torch is mixed with other packages', { skip: !PYTHON }, () => {+ // The ROCm index mirrors torch's dependency closure only: asking it for+ // trimesh returns 403, so a mixed install would hard-fail without this.+ const { argv } = runThroughLauncher(+ ['install', 'torch==2.6.0', 'trimesh', 'diffusers', '--index-url', 'https://download.pytorch.org/whl/cu124'],+ ROCM_ENV,+ )++ assert.deepEqual(argv, [+ 'install',+ '--index-url', 'https://download.pytorch.org/whl/rocm7.2',+ '--extra-index-url', 'https://pypi.org/simple',+ 'torch', 'torchvision',+ 'trimesh', 'diffusers',+ ])+})++test('ROCm shim does not add PyPI for a torch-only install', { skip: !PYTHON }, () => {+ // Keeping PyPI out of a pure torch install avoids pip ever preferring a+ // plain CUDA wheel over the ROCm one.+ const { argv } = runThroughLauncher(+ ['install', '--retries', '10', 'torch==2.6.0', '--index-url', 'https://download.pytorch.org/whl/cu124'],+ ROCM_ENV,+ )+ assert.ok(!argv.includes('--extra-index-url'))+})++test('shim is inert on a CUDA machine', { skip: !PYTHON }, () => {+ const original = ['install', 'torch==2.6.0', '--index-url', 'https://download.pytorch.org/whl/cu124']+ const { argv } = runThroughLauncher(original, {+ MODLY_TORCH_FLAVOR: 'cuda',+ MODLY_TORCH_INDEX_URL: '',+ MODLY_TORCH_SPECS: '[]',+ })+ assert.deepEqual(argv, original)+})++test('ROCm shim covers subprocess.Popen and the args= keyword too', { skip: !PYTHON }, () => {+ // Extension setup.py scripts stream pip output through Popen, or spell the+ // command as run(args=[...]); both bypassed the patch when it only wrapped+ // run/check_call/check_output positionally.+ for (const invoke of ['popen', 'run_kwarg', 'check_call']) {+ const { argv } = runThroughLauncher(+ ['install', 'torch==2.6.0', '--index-url', 'https://download.pytorch.org/whl/cu124'],+ ROCM_ENV,+ invoke,+ )+ assert.deepEqual(argv, [+ 'install',+ '--index-url', 'https://download.pytorch.org/whl/rocm7.2',+ 'torch', 'torchvision',+ ], `invocation shape "${invoke}" escaped the ROCm redirect`)+ }+})++test('ROCm shim matches "python -u -m pip install" too', { skip: !PYTHON }, () => {+ // hunyuan3d-style scripts call pip through the interpreter; "pip" is then the+ // fourth token, which the old first-three-tokens check missed.+ const dir = mkdtempSync(join(tmpdir(), 'modly-launcher-m-'))+ const capture = join(dir, 'captured.json')+ writeFileSync(join(dir, 'pip.py'), [+ 'import json, os, sys',+ 'with open(os.environ["MODLY_TEST_CAPTURE"], "w") as handle:',+ ' json.dump(sys.argv[1:], handle)',+ ].join('\n'), 'utf8')++ const setupPy = join(dir, 'setup.py')+ writeFileSync(setupPy, [+ 'import subprocess, sys',+ 'subprocess.run([sys.executable, "-u", "-m", "pip", "install", "torch==2.6.0",',+ ' "--index-url", "https://download.pytorch.org/whl/cu124"], check=True)',+ ].join('\n'), 'utf8')++ const result = spawnSync(PYTHON, ['-c', SETUP_LAUNCHER_SOURCE, setupPy, '{}'], {+ encoding: 'utf8',+ env: { ...process.env, ...ROCM_ENV, MODLY_TEST_CAPTURE: capture, PYTHONPATH: dir },+ })+ assert.equal(result.status, 0, `launcher failed:\n${result.stderr}`)++ assert.deepEqual(JSON.parse(readFileSync(capture, 'utf8')), [+ 'install',+ '--index-url', 'https://download.pytorch.org/whl/rocm7.2',+ 'torch', 'torchvision',+ ])+})++test('ROCm shim demotes a foreign primary index instead of keeping it primary', { skip: !PYTHON }, () => {+ // pip resolves a duplicated --index-url last-wins: a kept foreign primary+ // index could shadow the injected ROCm one and silently hand torch back to+ // CUDA/CPU wheels. Demoted to an extra index, its other packages stay+ // reachable while ROCm stays primary.+ const { argv } = runThroughLauncher(+ ['install', 'torch==2.6.0', '--index-url', 'https://pypi.org/simple'],+ ROCM_ENV,+ )++ assert.deepEqual(argv, [+ 'install',+ '--index-url', 'https://download.pytorch.org/whl/rocm7.2',+ 'torch', 'torchvision',+ '--extra-index-url', 'https://pypi.org/simple',+ ])+})++test('ROCm shim keeps PyPI reachable when the extension chose ROCm itself', { skip: !PYTHON }, () => {+ // The keeps-rocm-index branch needs the PyPI rescue just as much: the ROCm+ // index answers 403 for trimesh/diffusers.+ const { argv } = runThroughLauncher(+ ['install', 'torch', 'trimesh', '--index-url', 'https://download.pytorch.org/whl/rocm7.2'],+ ROCM_ENV,+ )++ assert.deepEqual(argv, [+ 'install',+ '--extra-index-url', 'https://pypi.org/simple',+ 'torch', 'torchvision',+ 'trimesh',+ '--index-url', 'https://download.pytorch.org/whl/rocm7.2',+ ])+})++test('ROCm shim recognises AMD\'s Windows index as already-ROCm', { skip: !PYTHON }, () => {+ // repo.amd.com carries no "/whl/rocm" path segment; it must still count as a+ // ROCm index or the shim would inject a second, conflicting --index-url.+ const winEnv = {+ ...ROCM_ENV,+ MODLY_TORCH_INDEX_URL: 'https://repo.amd.com/rocm/whl-multi-arch/',+ MODLY_TORCH_SPECS: JSON.stringify(['torch[device-gfx1200]==2.11.0+rocm7.14.0']),+ }+ const { argv } = runThroughLauncher(+ ['install', 'torch==2.6.0', '--index-url', 'https://repo.amd.com/rocm/whl-multi-arch/'],+ winEnv,+ )++ assert.deepEqual(argv, [+ 'install',+ 'torch[device-gfx1200]==2.11.0+rocm7.14.0',+ '--index-url', 'https://repo.amd.com/rocm/whl-multi-arch/',+ ])+})++test('--no-cache-dir is still stripped alongside the ROCm rewrite', { skip: !PYTHON }, () => {+ const { argv } = runThroughLauncher(+ ['install', '--no-cache-dir', 'torch==2.6.0', '--index-url', 'https://download.pytorch.org/whl/cu124'],+ ROCM_ENV,+ )++ assert.ok(!argv.includes('--no-cache-dir'))+ assert.ok(argv.includes('https://download.pytorch.org/whl/rocm7.2'))+})diff --git a/apps/forge-desktop/electron/main/setup-launcher.ts b/apps/forge-desktop/electron/main/setup-launcher.tsnew file mode 100644index 000000000..a31506706--- /dev/null+++ b/apps/forge-desktop/electron/main/setup-launcher.ts@@ -0,0 +1,258 @@+/**+ * Python launcher used to run an extension's setup.py.+ *+ * Extension setup scripts are third-party code we cannot edit, and they install+ * PyTorch themselves from an index they hardcode. The launcher wraps them: it+ * patches subprocess so every pip invocation passes through a few corrections+ * before it runs — dropping CUDA-only indexes on macOS, keeping the shared wheel+ * cache alive, and redirecting torch to ROCm wheels on AMD machines.+ *+ * Kept in its own module so setup-launcher.test.mjs can execute it for real+ * against the command shapes the official extensions actually use.+ */++export const SETUP_LAUNCHER_SOURCE = `+import json+import os+import re+import runpy+import subprocess+import sys++setup_py = sys.argv[1]+setup_args = sys.argv[2:]++_TORCH_REQ_RE = re.compile(r"^(torch|torchvision|torchaudio)(\\[[^\\]]*\\])?\\s*([<>=!~].*)?$", re.I)++def _is_cuda_torch_index(value):+ return isinstance(value, str) and value.startswith("https://download.pytorch.org/whl/cu")++def _is_torch_requirement(text):+ # Matches "torch", "torch==2.6.0", "torch[device-gfx1200]==2.11.0+rocm7.14.0",+ # and the pinned direct wheel URLs the ARM64 install path uses.+ if _TORCH_REQ_RE.match(text):+ return True+ if text.startswith(("http://", "https://")):+ return any(seg in text for seg in ("/torch-", "/torchvision-", "/torchaudio-"))+ return False++def _mentions_torch(command):+ if not isinstance(command, (list, tuple)):+ return False+ return any(_is_torch_requirement(str(part)) for part in command)++def _rewrite_command(command):+ if sys.platform != "darwin" or not _mentions_torch(command):+ return command+ if not isinstance(command, (list, tuple)):+ return command++ rewritten = []+ changed = False+ i = 0+ while i < len(command):+ part = command[i]+ text = str(part)+ if text in ("--index-url", "-i", "--extra-index-url") and i + 1 < len(command) and _is_cuda_torch_index(str(command[i + 1])):+ changed = True+ i += 2+ continue+ if text.startswith("--index-url=") or text.startswith("--extra-index-url="):+ value = text.split("=", 1)[1]+ if _is_cuda_torch_index(value):+ changed = True+ i += 1+ continue+ rewritten.append(part)+ i += 1++ if changed:+ print("[Modly setup compat] Removed CUDA-only PyTorch index on macOS; pip will use macOS wheels.", file=sys.stderr)+ return rewritten+ return command++# Matches the executable spellings pip arrives under: "pip", "pip3", "pip3.11",+# "pip.exe", or a stub script like "pip.py" — but not a requirement that merely+# starts with "pip" (pipdeptree) or a script like "pipeline.py".+_PIP_BASENAME_RE = re.compile(r"^pip[0-9.]*(\\.py|\\.exe)?$", re.I)++def _is_pip_command(command):+ # Scan everything ahead of the pip subcommand, so both "<venv>/bin/pip+ # install" and "python -u -m pip install" match, while requirements after+ # "install" are never mistaken for the executable.+ if not isinstance(command, (list, tuple)):+ return False+ texts = [str(part) for part in command]+ for i, text in enumerate(texts):+ if text in ("install", "download", "wheel"):+ break+ if text == "-m" and i + 1 < len(texts) and texts[i + 1].lower() in ("pip", "pip._internal"):+ return True+ if _PIP_BASENAME_RE.match(os.path.basename(text)):+ return True+ return False++def _strip_no_cache(command):+ # Extension setup scripts often hardcode --no-cache-dir, which forces pip to+ # re-download multi-GB wheels on every retry. Modly provides a shared cache+ # via PIP_CACHE_DIR, so drop the flag and let pip use it.+ if not _is_pip_command(command):+ return command+ if not any(str(part) == "--no-cache-dir" for part in command):+ return command+ print("[Modly setup compat] Removed --no-cache-dir so pip reuses the shared wheel cache.", file=sys.stderr)+ return [part for part in command if str(part) != "--no-cache-dir"]++# ROCm redirect. Most extension setup.py scripts predate AMD support and+# hardcode a CUDA index (hunyuan3d-mini even forces the CPU index on Windows),+# so on an AMD machine we swap the whole torch install for the ROCm one Modly+# resolved. An index the extension already pointed at ROCm is left alone.+_ROCM_INDEX = os.environ.get("MODLY_TORCH_INDEX_URL", "")+try:+ _ROCM_SPECS = json.loads(os.environ.get("MODLY_TORCH_SPECS", "[]"))+except ValueError:+ _ROCM_SPECS = []++def _is_pytorch_index(value):+ return isinstance(value, str) and "download.pytorch.org/whl/" in value++def _is_rocm_index(value):+ # Covers the pytorch.org rocm indexes, AMD's Windows multi-arch index, and+ # whatever MODLY_ROCM_INDEX was overridden to.+ if not isinstance(value, str):+ return False+ if _ROCM_INDEX and value.rstrip("/") == _ROCM_INDEX.rstrip("/"):+ return True+ return "/whl/rocm" in value or "repo.amd.com/rocm" in value++_PIP_VALUE_FLAGS = (+ "--index-url", "-i", "--extra-index-url", "--find-links", "-f",+ "--retries", "--timeout", "--cache-dir", "--target", "-t",+ "--requirement", "-r", "--constraint", "-c", "--progress-bar",+ "--proxy", "--cert", "--client-cert", "--trusted-host", "--log",+ "--no-binary", "--only-binary", "--prefix", "--root", "--upgrade-strategy",+ "--python-version", "--platform", "--abi", "--implementation",+)++def _has_non_torch_requirement(command):+ # Only look past the subcommand, so the interpreter and pip executable+ # paths ahead of it are never mistaken for requirements.+ texts = [str(part) for part in command]+ start = None+ for index, text in enumerate(texts):+ if text in ("install", "download", "wheel"):+ start = index + 1+ break+ if start is None:+ return False++ skip_next = False+ for text in texts[start:]:+ if skip_next:+ skip_next = False+ continue+ if text in _PIP_VALUE_FLAGS:+ skip_next = True+ continue+ if text.startswith("-") or _is_torch_requirement(text):+ continue+ return True+ return False++def _rewrite_rocm(command):+ if os.environ.get("MODLY_TORCH_FLAVOR") != "rocm" or not _ROCM_INDEX or not _ROCM_SPECS:+ return command+ if not isinstance(command, (list, tuple)):+ return command+ if not _is_pip_command(command) or not _mentions_torch(command):+ return command++ rewritten = []+ insert_at = None+ keeps_rocm_index = False+ changed = False+ i = 0+ while i < len(command):+ text = str(command[i])+ if text in ("--index-url", "-i", "--extra-index-url") and i + 1 < len(command):+ value = str(command[i + 1])+ if _is_rocm_index(value):+ keeps_rocm_index = True+ rewritten.extend(command[i:i + 2])+ elif _is_pytorch_index(value):+ changed = True+ elif text != "--extra-index-url":+ # A foreign primary index (a PyPI mirror, pypi.nvidia.com…)+ # must not stay primary: pip resolves a duplicated --index-url+ # last-wins, so it could shadow the injected ROCm index and+ # silently hand torch back to CUDA/CPU wheels. Demote it to an+ # extra index so its other packages stay reachable.+ changed = True+ rewritten.extend(["--extra-index-url", command[i + 1]])+ else:+ rewritten.extend(command[i:i + 2])+ i += 2+ continue+ if "=" in text and text.split("=", 1)[0] in ("--index-url", "--extra-index-url"):+ flag, value = text.split("=", 1)+ if _is_rocm_index(value):+ keeps_rocm_index = True+ rewritten.append(command[i])+ elif _is_pytorch_index(value):+ changed = True+ elif flag != "--extra-index-url":+ changed = True+ rewritten.append("--extra-index-url=" + value)+ else:+ rewritten.append(command[i])+ i += 1+ continue+ if _is_torch_requirement(text):+ if insert_at is None:+ insert_at = len(rewritten)+ changed = True+ i += 1+ continue+ rewritten.append(command[i])+ i += 1++ if not changed:+ return command+ if insert_at is None:+ insert_at = len(rewritten)+ index_args = [] if keeps_rocm_index else ["--index-url", _ROCM_INDEX]+ if _has_non_torch_requirement(command) and not any("pypi.org/simple" in str(part) for part in rewritten):+ # The ROCm index only mirrors torch's own dependency closure (numpy,+ # pillow…), not application packages like trimesh or diffusers. A pip+ # call that mixes both still needs PyPI reachable — also when the+ # extension supplied the ROCm index itself.+ index_args += ["--extra-index-url", "https://pypi.org/simple"]+ injected = index_args + list(_ROCM_SPECS)+ rewritten[insert_at:insert_at] = injected+ print("[Modly setup compat] Redirected PyTorch to ROCm wheels: " + " ".join(injected), file=sys.stderr)+ return rewritten++def _transform_command(command):+ return _strip_no_cache(_rewrite_rocm(_rewrite_command(command)))++# Every subprocess entry point — run, call, check_call, check_output, and a+# direct subprocess.Popen(...) — constructs the module-global Popen, so patching+# that one class covers them all exactly once, whether the command arrives+# positionally or as the args= keyword. This also holds for code that did+# "from subprocess import run" before this launcher ran: run() still looks+# Popen up on the module at call time.+_OriginalPopen = subprocess.Popen++class _PatchedPopen(_OriginalPopen):+ def __init__(self, *args, **kwargs):+ if args:+ args = (_transform_command(args[0]),) + tuple(args[1:])+ elif "args" in kwargs:+ kwargs["args"] = _transform_command(kwargs["args"])+ super().__init__(*args, **kwargs)++subprocess.Popen = _PatchedPopen++sys.argv = [setup_py] + setup_args+runpy.run_path(setup_py, run_name="__main__")+`diff --git a/apps/forge-desktop/electron/main/updater.ts b/apps/forge-desktop/electron/main/updater.tsnew file mode 100644index 000000000..6a582b816--- /dev/null+++ b/apps/forge-desktop/electron/main/updater.ts@@ -0,0 +1,68 @@+import { app, BrowserWindow } from 'electron'+import { autoUpdater } from 'electron-updater'+import { logger } from './logger'++type WindowGetter = () => BrowserWindow | null++// Les builds macOS ne sont pas signés avec un Developer ID (pas de licence Apple).+// electron-updater valide la signature du bundle avant d'appliquer une mise à+// jour : sur darwin il échouerait systématiquement, en boucle toutes les 2 h.+// Les utilisateurs mac mettent donc à jour manuellement via les releases GitHub.+export const updatesSupported = process.platform !== 'darwin'++export function initAutoUpdater(getWindow: WindowGetter): void {+ if (!updatesSupported) {+ logger.info('[updater] Disabled on macOS (unsigned build) — manual updates only')+ return+ }++ autoUpdater.logger = logger as any+ autoUpdater.autoDownload = false+ autoUpdater.autoInstallOnAppQuit = true+ autoUpdater.disableWebInstaller = true++ autoUpdater.on('update-available', (info) => {+ const running = app.getVersion()+ const incoming = info.version+ const [rMaj, rMin] = running.split('.').map(Number)+ const [iMaj, iMin] = incoming.split('.').map(Number)+ const isPatch = rMaj === iMaj && rMin === iMin++ if (isPatch) {+ logger.info(`[updater] Patch ${incoming} available — downloading`)+ autoUpdater.downloadUpdate().catch((err: Error) => {+ logger.error(`[updater] Download failed: ${err.message}`)+ })+ } else {+ logger.info(`[updater] Major/minor update ${incoming} available — notifying renderer`)+ getWindow()?.webContents.send('updater:major-minor-available', { version: incoming })+ }+ })++ autoUpdater.on('update-downloaded', (info) => {+ logger.info(`[updater] Patch ${info.version} downloaded — applying now`)+ getWindow()?.webContents.send('updater:applying', { version: info.version })+ // Small delay so the renderer can render the "Applying…" panel before quit+ setTimeout(() => {+ autoUpdater.quitAndInstall(true, true)+ }, 800)+ })++ autoUpdater.on('update-not-available', () => {+ logger.info('[updater] App is up to date')+ })++ autoUpdater.on('error', (err: Error) => {+ logger.error(`[updater] Error: ${err.message}`)+ })++ // Check immediately on startup so it can apply during the setup screen+ autoUpdater.checkForUpdates().catch((err: Error) => {+ logger.error(`[updater] Initial check failed: ${err.message}`)+ })++ // Re-check every 2 hours for long-running sessions+ setInterval(() => {+ autoUpdater.checkForUpdates().catch(() => {})+ }, 2 * 60 * 60 * 1000)+}diff --git a/apps/forge-desktop/electron/preload/artifact-registry-preload.test.ts b/apps/forge-desktop/electron/preload/artifact-registry-preload.test.tsnew file mode 100644index 000000000..9dec46fd8--- /dev/null+++ b/apps/forge-desktop/electron/preload/artifact-registry-preload.test.ts@@ -0,0 +1,69 @@+import assert from 'node:assert/strict'+import test from 'node:test'++import { createElectronApi } from './electron-api.ts'++test('preload exposes scoped workspace library list/read/open methods', async () => {+ const calls: Array<{ channel: string, payload?: unknown }> = []+ const api = createElectronApi({+ invoke: async (channel: string, payload?: unknown) => {+ calls.push({ channel, payload })+ return { success: true, entries: [] }+ },+ send: () => undefined,+ on: () => undefined,+ removeAllListeners: () => undefined,+ }, { setZoomFactor: () => undefined }, { getPathForFile: () => '' })++ await api.workspace.library.list()+ await api.workspace.library.read({+ workspacePath: 'Workflows/checkpoints/hero.landmarks.v1.json',+ sourceWorkspacePath: 'Workflows/checkpoints/hero.glb',+ })+ await api.workspace.library.open({+ workspacePath: 'Workflows/checkpoints/hero.landmarks.v1.json',+ sourceWorkspacePath: 'Workflows/checkpoints/hero.glb',+ })++ assert.deepEqual(calls, [+ { channel: 'workspace:library:list', payload: undefined },+ {+ channel: 'workspace:library:read',+ payload: {+ workspacePath: 'Workflows/checkpoints/hero.landmarks.v1.json',+ sourceWorkspacePath: 'Workflows/checkpoints/hero.glb',+ },+ },+ {+ channel: 'workspace:library:open',+ payload: {+ workspacePath: 'Workflows/checkpoints/hero.landmarks.v1.json',+ sourceWorkspacePath: 'Workflows/checkpoints/hero.glb',+ },+ },+ ])+})++test('preload resolves dropped file paths through Electron webUtils', () => {+ const files: unknown[] = []+ const calls: string[] = []+ const api = createElectronApi({+ invoke: async (channel: string) => {+ calls.push(channel)+ return null+ },+ send: () => undefined,+ on: () => undefined,+ removeAllListeners: () => undefined,+ }, { setZoomFactor: () => undefined }, {+ getPathForFile: (file) => {+ files.push(file)+ return 'C:\\images\\input.png'+ },+ })+ const file = {} as Parameters<typeof api.fs.getPathForFile>[0]++ assert.equal(api.fs.getPathForFile(file), 'C:\\images\\input.png')+ assert.deepEqual(files, [file])+ assert.deepEqual(calls, [])+})diff --git a/apps/forge-desktop/electron/preload/electron-api.ts b/apps/forge-desktop/electron/preload/electron-api.tsnew file mode 100644index 000000000..33944a57c--- /dev/null+++ b/apps/forge-desktop/electron/preload/electron-api.ts@@ -0,0 +1,343 @@+import type {+ AssetLibraryListResult,+ AssetLibraryOpenRequest,+ AssetLibraryOpenResult,+ AssetLibraryReadRequest,+ AssetLibraryReadResult,+} from '../../src/shared/types/assetLibrary'++export interface IpcRendererLike {+ invoke(channel: string, ...args: unknown[]): Promise<unknown>+ send(channel: string, ...args: unknown[]): void+ on(channel: string, listener: (...args: unknown[]) => void): void+ removeAllListeners(channel: string): void+}++export interface WebFrameLike {+ setZoomFactor(factor: number): void+}++export type WebUtilsLike = Pick<typeof import('electron').webUtils, 'getPathForFile'>++export function createElectronApi(ipcRenderer: IpcRendererLike, webFrame: WebFrameLike, webUtils: WebUtilsLike) {+ return {+ // Window controls+ window: {+ minimize: () => ipcRenderer.send('window:minimize'),+ maximize: () => ipcRenderer.send('window:maximize'),+ close: () => ipcRenderer.send('window:close'),+ isMaximized: () => ipcRenderer.invoke('window:isMaximized') as Promise<boolean>,+ onMaximizeChange: (cb: (isMaximized: boolean) => void) => {+ ipcRenderer.on('window:maximizeChanged', (_event, isMaximized) => cb(isMaximized as boolean))+ },+ offMaximizeChange: () => ipcRenderer.removeAllListeners('window:maximizeChanged'),+ },++ // Native OS notifications (Windows toast / macOS Notification Center / Linux)+ notifications: {+ show: (title: string, body: string): Promise<{ success: boolean; error?: string }> =>+ ipcRenderer.invoke('notifications:show', title, body) as Promise<{ success: boolean; error?: string }>,+ },++ // Renderer UI (zoom whole page — scales every px/rem consistently)+ ui: { setZoomFactor: (factor: number) => webFrame.setZoomFactor(factor) },++ // Shell utilities+ shell: { openExternal: (url: string) => ipcRenderer.invoke('shell:openExternal', url) },++ // Slicer integration — open a model in OrcaSlicer via its deeplink+ slicer: {+ open: (url: string): Promise<{ success: boolean; error?: string }> =>+ ipcRenderer.invoke('slicer:open', url) as Promise<{ success: boolean; error?: string }>,+ },++ // System info+ system: {+ memory: (): Promise<{ total: number; used: number; available: number }> =>+ ipcRenderer.invoke('system:memory') as Promise<{ total: number; used: number; available: number }>,+ },++ // Python / FastAPI bridge+ python: {+ start: (): Promise<{ success: boolean; port?: number; error?: string }> =>+ ipcRenderer.invoke('python:start') as Promise<{ success: boolean; port?: number; error?: string }>,+ status: (): Promise<{ ready: boolean; apiUrl: string }> =>+ ipcRenderer.invoke('python:status') as Promise<{ ready: boolean; apiUrl: string }>,+ onCrashed: (cb: (data: { code: number | null }) => void) => {+ ipcRenderer.on('python:crashed', (_event, data) => cb(data as { code: number | null }))+ },+ offCrashed: () => ipcRenderer.removeAllListeners('python:crashed'),+ onLog: (cb: (line: string) => void) => {+ ipcRenderer.on('python:log', (_event, line) => cb(line as string))+ },+ offLog: () => ipcRenderer.removeAllListeners('python:log'),+ },++ // File system dialogs + local file reading+ fs: {+ getPathForFile: (file: Parameters<WebUtilsLike['getPathForFile']>[0]): string =>+ webUtils.getPathForFile(file),+ selectImage: (): Promise<string | null> =>+ ipcRenderer.invoke('fs:selectImage') as Promise<string | null>,+ selectMeshFile: (): Promise<string | null> =>+ ipcRenderer.invoke('fs:selectMeshFile') as Promise<string | null>,+ saveModel: (defaultName: string): Promise<string | null> =>+ ipcRenderer.invoke('fs:saveModel', defaultName) as Promise<string | null>,+ readFileBase64: (filePath: string): Promise<string> =>+ ipcRenderer.invoke('fs:readFileBase64', filePath) as Promise<string>,+ selectDirectory: (defaultPath?: string): Promise<string | null> =>+ ipcRenderer.invoke('fs:selectDirectory', defaultPath) as Promise<string | null>,+ savePath: (args: { filters: { name: string; extensions: string[] }[]; defaultPath?: string }): Promise<string | null> =>+ ipcRenderer.invoke('fs:savePath', args) as Promise<string | null>,+ listDir: (dirPath: string): Promise<string[]> =>+ ipcRenderer.invoke('fs:listDir', dirPath) as Promise<string[]>,+ listFiles: (dirPath: string, extensions?: string[]): Promise<string[]> =>+ ipcRenderer.invoke('fs:listFiles', dirPath, extensions) as Promise<string[]>,+ selectTextFile: (): Promise<string | null> =>+ ipcRenderer.invoke('fs:selectTextFile') as Promise<string | null>,+ moveDirectory: (args: { src: string; dest: string }): Promise<{ success: boolean; error?: string }> =>+ ipcRenderer.invoke('fs:moveDirectory', args) as Promise<{ success: boolean; error?: string }>,+ deleteDirectory: (dirPath: string): Promise<{ success: boolean; error?: string }> =>+ ipcRenderer.invoke('fs:deleteDirectory', dirPath) as Promise<{ success: boolean; error?: string }>,+ readScreenshotDataUrl: (filename: string): Promise<string> =>+ ipcRenderer.invoke('fs:readScreenshotDataUrl', filename) as Promise<string>,+ },++ // Secure storage — OS-level encryption for secrets (API keys, …)+ secureStore: {+ encrypt: (plainText: string): Promise<string> => ipcRenderer.invoke('secure:encrypt', plainText) as Promise<string>,+ // null = one of our blobs that couldn't be decrypted here (different OS+ // user/machine). Never the ciphertext — see secure-store.ts.+ decrypt: (stored: string): Promise<string | null> => ipcRenderer.invoke('secure:decrypt', stored) as Promise<string | null>,+ },++ // Agent — local LLM models+ agent: {+ // Opens a file picker and copies the chosen .gguf into the agent's models folder.+ addModel: (): Promise<{ success: boolean; cancelled?: boolean; fileName?: string; error?: string }> =>+ ipcRenderer.invoke('agent:addModel') as Promise<{ success: boolean; cancelled?: boolean; fileName?: string; error?: string }>,+ },++ // Settings+ settings: {+ get: (): Promise<{ modelsDir: string; workspaceDir: string; workflowsDir: string; extensionsDir: string; hfToken?: string }> =>+ ipcRenderer.invoke('settings:get') as Promise<{ modelsDir: string; workspaceDir: string; workflowsDir: string; extensionsDir: string; hfToken?: string }>,+ set: (patch: { modelsDir?: string; workspaceDir?: string; workflowsDir?: string; extensionsDir?: string; hfToken?: string }): Promise<{ modelsDir: string; workspaceDir: string; workflowsDir: string; extensionsDir: string; hfToken?: string }> =>+ ipcRenderer.invoke('settings:set', patch) as Promise<{ modelsDir: string; workspaceDir: string; workflowsDir: string; extensionsDir: string; hfToken?: string }>,+ },++ // Cache+ cache: {+ clear: (): Promise<{ success: boolean; error?: string }> =>+ ipcRenderer.invoke('cache:clear') as Promise<{ success: boolean; error?: string }>,+ },++ // API helpers (calls FastAPI from the main process)+ api: {+ updatePaths: (patch: { modelsDir?: string; workspaceDir?: string; extensionsDir?: string }): Promise<{ success: boolean; error?: string }> =>+ ipcRenderer.invoke('api:updatePaths', patch) as Promise<{ success: boolean; error?: string }>,+ },++ // Model management+ model: {+ export: (args: { outputUrl: string; format: string }) => ipcRenderer.invoke('model:export', args),+ listDownloaded: () => ipcRenderer.invoke('model:listDownloaded'),+ isDownloaded: (modelId: string) => ipcRenderer.invoke('model:isDownloaded', modelId),+ hasLocalData: (modelId: string) => ipcRenderer.invoke('model:hasLocalData', modelId),+ sharedGroups: (extensionId: string) => ipcRenderer.invoke('model:sharedGroups', extensionId),+ download: (modelId: string, variantId?: string) => (variantId === undefined+ ? ipcRenderer.invoke('model:download', modelId)+ : ipcRenderer.invoke('model:download', modelId, variantId)),+ pauseDownload: (modelId: string) => ipcRenderer.invoke('model:pauseDownload', modelId),+ cancelDownload: (modelId: string) => ipcRenderer.invoke('model:cancelDownload', modelId),+ delete: (modelId: string) => ipcRenderer.invoke('model:delete', modelId),+ deleteSharedGroup: (extensionId: string, groupId: string) => ipcRenderer.invoke('model:deleteSharedGroup', extensionId, groupId),+ deleteExtensionWeights: (extensionId: string) => ipcRenderer.invoke('model:deleteExtensionWeights', extensionId),+ installedWeightVariants: (modelId: string) => ipcRenderer.invoke('model:installedWeightVariants', modelId),+ deleteWeightVariant: (modelId: string, variantId: string) => ipcRenderer.invoke('model:deleteWeightVariant', modelId, variantId),+ unloadAll: () => ipcRenderer.invoke('model:unloadAll'),+ showInFolder: (modelId: string) => ipcRenderer.invoke('model:showInFolder', modelId),+ activeDownloads: (): Promise<{ modelId: string; percent: number; file?: string; fileIndex?: number; totalFiles?: number }[]> =>+ ipcRenderer.invoke('model:activeDownloads') as Promise<{ modelId: string; percent: number; file?: string; fileIndex?: number; totalFiles?: number }[]>,+ onProgress: (cb: (data: {+ modelId: string+ percent: number+ file?: string+ fileIndex?: number+ totalFiles?: number+ status?: string+ bytesDownloaded?: number+ totalBytes?: number+ stalledSeconds?: number+ paused?: boolean+ cancelled?: boolean+ }) => void) => {+ ipcRenderer.on('model:downloadProgress', (_event, data) => cb(data as {+ modelId: string+ percent: number+ file?: string+ fileIndex?: number+ totalFiles?: number+ status?: string+ bytesDownloaded?: number+ totalBytes?: number+ stalledSeconds?: number+ paused?: boolean+ cancelled?: boolean+ }))+ },+ offProgress: () => ipcRenderer.removeAllListeners('model:downloadProgress'),+ onWeightsChanged: (cb: () => void) => ipcRenderer.on('model:weightsChanged', cb),+ offWeightsChanged: () => ipcRenderer.removeAllListeners('model:weightsChanged'),+ },++ // App metadata+ app: {+ info: (): Promise<{ version: string; userData: string; modelsDir: string; apiUrl: string; platform: string; arch: string }> =>+ ipcRenderer.invoke('app:info') as Promise<{ version: string; userData: string; modelsDir: string; apiUrl: string; platform: string; arch: string }>,+ onError: (cb: (message: string) => void) => {+ ipcRenderer.on('app:error', (_event, message) => cb(message as string))+ },+ offError: () => ipcRenderer.removeAllListeners('app:error'),+ },++ // Logging+ log: {+ error: (message: string) => ipcRenderer.send('log:error', message),+ getPath: (): Promise<string> => ipcRenderer.invoke('log:getPath') as Promise<string>,+ readAll: (session?: string): Promise<Record<string, string>> => ipcRenderer.invoke('log:readAll', session) as Promise<Record<string, string>>,+ listSessions: (): Promise<string[]> => ipcRenderer.invoke('log:listSessions') as Promise<string[]>,+ },++ // Workspace filesystem-based persistence+ workspace: {+ listCollections: (): Promise<string[]> =>+ ipcRenderer.invoke('workspace:listCollections') as Promise<string[]>,+ createCollection: (name: string): Promise<void> =>+ ipcRenderer.invoke('workspace:createCollection', name) as Promise<void>,+ renameCollection: (oldName: string, newName: string): Promise<void> =>+ ipcRenderer.invoke('workspace:renameCollection', { oldName, newName }) as Promise<void>,+ deleteCollection: (name: string): Promise<void> =>+ ipcRenderer.invoke('workspace:deleteCollection', name) as Promise<void>,+ listJobs: (collection: string): Promise<unknown[]> =>+ ipcRenderer.invoke('workspace:listJobs', collection) as Promise<unknown[]>,+ saveJobMeta: (collection: string, filename: string, meta: unknown): Promise<void> =>+ ipcRenderer.invoke('workspace:saveJobMeta', { collection, filename, meta }) as Promise<void>,+ deleteJob: (collection: string, filename: string): Promise<void> =>+ ipcRenderer.invoke('workspace:deleteJob', { collection, filename }) as Promise<void>,+ library: {+ list: (): Promise<AssetLibraryListResult> => ipcRenderer.invoke('workspace:library:list') as Promise<AssetLibraryListResult>,+ read: (request: AssetLibraryReadRequest): Promise<AssetLibraryReadResult> => ipcRenderer.invoke('workspace:library:read', request) as Promise<AssetLibraryReadResult>,+ open: (request: AssetLibraryOpenRequest): Promise<AssetLibraryOpenResult> => ipcRenderer.invoke('workspace:library:open', request) as Promise<AssetLibraryOpenResult>,+ },+ },++ // Extensions+ extensions: {+ list: (): Promise<unknown[]> =>+ ipcRenderer.invoke('extensions:list') as Promise<unknown[]>,++ installFromGitHub: (url: string): Promise<{+ success: boolean; error?: string; cancelled?: boolean+ extensionId?: string+ extension?: unknown+ }> => ipcRenderer.invoke('extensions:installFromGitHub', url) as Promise<{+ success: boolean; error?: string; cancelled?: boolean+ extensionId?: string+ extension?: unknown+ }>,++ installFromLocal: (): Promise<{+ success: boolean; error?: string; cancelled?: boolean+ needsRepair?: boolean+ extensionId?: string+ extension?: unknown+ localPath?: string+ }> => ipcRenderer.invoke('extensions:installFromLocal') as Promise<{+ success: boolean; error?: string; cancelled?: boolean+ needsRepair?: boolean+ extensionId?: string+ extension?: unknown+ localPath?: string+ }>,++ uninstall: (extensionId: string): Promise<{ success: boolean; error?: string }> =>+ ipcRenderer.invoke('extensions:uninstall', extensionId) as Promise<{ success: boolean; error?: string }>,++ repair: (extensionId: string): Promise<{ success: boolean; error?: string }> =>+ ipcRenderer.invoke('extensions:repair', extensionId) as Promise<{ success: boolean; error?: string }>,++ reload: (): Promise<{ success: boolean; error?: string }> =>+ ipcRenderer.invoke('extensions:reload') as Promise<{ success: boolean; error?: string }>,++ runProcess: (+ extensionId: string,+ input: { filePath?: string; text?: string; texts?: (string | undefined)[]; nodeId?: string },+ params: Record<string, unknown>,+ ): Promise<{ success: boolean; result?: { filePath?: string; text?: string }; error?: string }> =>+ ipcRenderer.invoke('extensions:runProcess', extensionId, input, params) as Promise<{ success: boolean; result?: { filePath?: string; text?: string }; error?: string }>,++ onInstallProgress: (cb: (data: {+ step: 'downloading' | 'extracting' | 'validating' | 'setting_up' | 'done' | 'error'+ percent?: number+ extensionId?: string+ message?: string+ }) => void) => {+ ipcRenderer.on('extensions:installProgress', (_event, data) => cb(data as {+ step: 'downloading' | 'extracting' | 'validating' | 'setting_up' | 'done' | 'error'+ percent?: number+ extensionId?: string+ message?: string+ }))+ },+ offInstallProgress: () => ipcRenderer.removeAllListeners('extensions:installProgress'),+ },++ // Workflows+ workflows: {+ list: (): Promise<unknown[]> => ipcRenderer.invoke('workflows:list') as Promise<unknown[]>,+ save: (workflow: { id: string; [key: string]: unknown }): Promise<{ success: boolean; error?: string }> => ipcRenderer.invoke('workflows:save', workflow) as Promise<{ success: boolean; error?: string }>,+ delete: (id: string): Promise<{ success: boolean; error?: string }> => ipcRenderer.invoke('workflows:delete', id) as Promise<{ success: boolean; error?: string }>,+ import: (): Promise<{ success: boolean; error?: string; workflow?: unknown }> => ipcRenderer.invoke('workflows:import') as Promise<{ success: boolean; error?: string; workflow?: unknown }>,+ export: (workflow: { id: string; name?: string; [key: string]: unknown }): Promise<{ success: boolean; error?: string }> => ipcRenderer.invoke('workflows:export', workflow) as Promise<{ success: boolean; error?: string }>,+ },++ // Auto-updater+ updater: {+ check: (): Promise<{ success: boolean }> =>+ ipcRenderer.invoke('updater:check') as Promise<{ success: boolean }>,+ quitAndInstall: (): Promise<void> =>+ ipcRenderer.invoke('updater:quitAndInstall') as Promise<void>,+ onApplying: (cb: (data: { version: string }) => void) => {+ ipcRenderer.on('updater:applying', (_event, data) => cb(data as { version: string }))+ },+ offApplying: () => ipcRenderer.removeAllListeners('updater:applying'),+ onMajorMinorAvailable: (cb: (data: { version: string }) => void) => {+ ipcRenderer.on('updater:major-minor-available', (_event, data) => cb(data as { version: string }))+ },+ offMajorMinorAvailable: () => ipcRenderer.removeAllListeners('updater:major-minor-available'),+ },++ // First-run setup+ setup: {+ check: (): Promise<{ needed: boolean; defaultDataDir: string; platform: string; arch: string }> =>+ ipcRenderer.invoke('setup:check') as Promise<{ needed: boolean; defaultDataDir: string; platform: string; arch: string }>,+ run: (): Promise<{ success: boolean; error?: string }> =>+ ipcRenderer.invoke('setup:run') as Promise<{ success: boolean; error?: string }>,+ saveDataDir: (baseDir: string): Promise<void> =>+ ipcRenderer.invoke('setup:saveDataDir', { baseDir }) as Promise<void>,+ onProgress: (cb: (data: { step: string; percent: number; currentPackage?: string }) => void) => {+ ipcRenderer.on('setup:progress', (_event, data) => cb(data as { step: string; percent: number; currentPackage?: string }))+ },+ offProgress: () => ipcRenderer.removeAllListeners('setup:progress'),+ onComplete: (cb: () => void) => {+ ipcRenderer.on('setup:complete', () => cb())+ },+ offComplete: () => ipcRenderer.removeAllListeners('setup:complete'),+ onError: (cb: (data: { message: string }) => void) => {+ ipcRenderer.on('setup:error', (_event, data) => cb(data as { message: string }))+ },+ offError: () => ipcRenderer.removeAllListeners('setup:error'),+ },+ }+}diff --git a/apps/forge-desktop/electron/preload/index.ts b/apps/forge-desktop/electron/preload/index.tsnew file mode 100644index 000000000..03b803633--- /dev/null+++ b/apps/forge-desktop/electron/preload/index.ts@@ -0,0 +1,6 @@+import { contextBridge, ipcRenderer, webFrame, webUtils } from 'electron'++import { createElectronApi } from './electron-api'++// Expose a typed API to the renderer process via window.electron+contextBridge.exposeInMainWorld('electron', createElectronApi(ipcRenderer, webFrame, webUtils))diff --git a/apps/forge-desktop/eslint.config.mjs b/apps/forge-desktop/eslint.config.mjsnew file mode 100644index 000000000..acc2a489c--- /dev/null+++ b/apps/forge-desktop/eslint.config.mjs@@ -0,0 +1,63 @@+import js from '@eslint/js'+import tseslint from 'typescript-eslint'+import reactHooks from 'eslint-plugin-react-hooks'+import globals from 'globals'++export default tseslint.config(+ {+ ignores: [+ 'dist/**',+ 'out/**',+ 'node_modules/**',+ 'resources/**',+ 'api/**',+ 'arch/**',+ 'docs/**',+ '**/*.test.mjs'+ ]+ },+ js.configs.recommended,+ ...tseslint.configs.recommended,+ // Renderer (React, browser environment)+ {+ files: ['src/**/*.{ts,tsx}'],+ plugins: { 'react-hooks': reactHooks },+ languageOptions: {+ globals: { ...globals.browser }+ },+ rules: {+ // Proven, high-value hook rules. The v7 "recommended" set adds many+ // opinionated React-Compiler-era rules that flood a legacy codebase.+ 'react-hooks/rules-of-hooks': 'error',+ 'react-hooks/exhaustive-deps': 'warn'+ }+ },+ // Main / preload / scripts (Node environment)+ {+ files: ['electron/**/*.{ts,mts,mjs}', 'scripts/**/*.{js,mjs,cjs}', 'tools/**/*.{ts,mjs}'],+ languageOptions: {+ globals: { ...globals.node }+ }+ },+ // CommonJS files (Node, require/module)+ {+ files: ['scripts/**/*.{js,cjs}', 'tailwind.config.js', 'postcss.config.js', '**/*.cjs'],+ languageOptions: {+ sourceType: 'commonjs',+ globals: { ...globals.node }+ }+ },+ // Project-wide rule tuning+ {+ rules: {+ '@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],+ '@typescript-eslint/no-explicit-any': 'off',+ // require() is used intentionally in Electron main and Node build scripts+ '@typescript-eslint/no-require-imports': 'off',+ '@typescript-eslint/no-unused-expressions': ['error', { allowShortCircuit: true, allowTernary: true }],+ // Stripping ANSI escape codes requires control chars in regex+ 'no-control-regex': 'off',+ 'no-empty': ['warn', { allowEmptyCatch: true }]+ }+ }+)diff --git a/apps/forge-desktop/launch.sh b/apps/forge-desktop/launch.shnew file mode 100644index 000000000..56955d89b--- /dev/null+++ b/apps/forge-desktop/launch.sh@@ -0,0 +1,30 @@+#!/bin/bash++echo " Modly — Production Launcher"+echo "================================"+echo++# Check Node.js+if ! command -v node &> /dev/null; then+ echo "[ERROR] Node.js is not installed or not in PATH."+ echo " Download it from https://nodejs.org"+ exit 1+fi++# Install dependencies if node_modules is missing+if [ ! -d "node_modules" ]; then+ echo "[1/2] Installing dependencies..."+ npm install || { echo "[ERROR] npm install failed."; exit 1; }+ echo+fi++# Build if out/ is missing+if [ ! -d "out" ]; then+ echo "[2/2] Building the app..."+ npm run build || { echo "[ERROR] Build failed."; exit 1; }+ echo+fi++# Launch+echo "Launching Modly..."+npm run previewdiff --git a/apps/forge-desktop/package-lock.json b/apps/forge-desktop/package-lock.jsonnew file mode 100644index 000000000..d7b522f68--- /dev/null+++ b/apps/forge-desktop/package-lock.json@@ -0,0 +1,8837 @@+{+ "name": "modly",+ "version": "0.4.2",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "modly",+ "version": "0.4.2",+ "dependencies": {+ "@electron-toolkit/utils": "^4.0.0",+ "@mkkellogg/gaussian-splats-3d": "^0.4.7",+ "@react-three/drei": "^9.120.0",+ "@react-three/fiber": "^8.17.10",+ "@react-three/postprocessing": "^2.19.1",+ "@xyflow/react": "^12.10.2",+ "axios": "^1.7.9",+ "electron-updater": "^6.8.3",+ "esbuild": "^0.28.0",+ "react": "^18.3.1",+ "react-dom": "^18.3.1",+ "tar": "^7.5.9",+ "three": "^0.171.0",+ "three-mesh-bvh": "^0.9.9",+ "zustand": "^5.0.3"+ },+ "devDependencies": {+ "@eslint/js": "^9.39.4",+ "@types/node": "^22.10.1",+ "@types/react": "^18.3.17",+ "@types/react-dom": "^18.3.5",+ "@types/tar": "^7.0.87",+ "@types/three": "^0.171.0",+ "@vitejs/plugin-react": "^4.3.4",+ "autoprefixer": "^10.4.20",+ "cross-env": "^10.1.0",+ "electron": "^42.11.1",+ "electron-builder": "^26.15.3",+ "electron-vite": "^5.0.0",+ "eslint": "^9.17.0",+ "eslint-plugin-react-hooks": "^7.1.1",+ "globals": "^17.6.0",+ "jsdom": "^29.1.1",+ "postcss": "^8.4.49",+ "tailwindcss": "^3.4.17",+ "typescript": "^5.7.2",+ "typescript-eslint": "^8.61.1",+ "vite": "^7.0.0"+ }+ },+ "node_modules/@alloc/quick-lru": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz",+ "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==",+ "dev": true,+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/@asamuzakjp/css-color": {+ "version": "5.1.11",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.11.tgz",+ "integrity": "sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/generational-cache": "^1.0.1",+ "@csstools/css-calc": "^3.2.0",+ "@csstools/css-color-parser": "^4.1.0",+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/dom-selector": {+ "version": "7.1.1",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-7.1.1.tgz",+ "integrity": "sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/generational-cache": "^1.0.1",+ "@asamuzakjp/nwsapi": "^2.3.9",+ "bidi-js": "^1.0.3",+ "css-tree": "^3.2.1",+ "is-potential-custom-element-name": "^1.0.1"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/generational-cache": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/generational-cache/-/generational-cache-1.0.1.tgz",+ "integrity": "sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/nwsapi": {+ "version": "2.3.9",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz",+ "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@babel/code-frame": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",+ "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/helper-validator-identifier": "^7.29.7",+ "js-tokens": "^4.0.0",+ "picocolors": "^1.1.1"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/compat-data": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz",+ "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/core": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",+ "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/code-frame": "^7.29.7",+ "@babel/generator": "^7.29.7",+ "@babel/helper-compilation-targets": "^7.29.7",+ "@babel/helper-module-transforms": "^7.29.7",+ "@babel/helpers": "^7.29.7",+ "@babel/parser": "^7.29.7",+ "@babel/template": "^7.29.7",+ "@babel/traverse": "^7.29.7",+ "@babel/types": "^7.29.7",+ "@jridgewell/remapping": "^2.3.5",+ "convert-source-map": "^2.0.0",+ "debug": "^4.1.0",+ "gensync": "^1.0.0-beta.2",+ "json5": "^2.2.3",+ "semver": "^6.3.1"+ },+ "engines": {+ "node": ">=6.9.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/babel"+ }+ },+ "node_modules/@babel/generator": {+ "version": "7.29.8",+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz",+ "integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/parser": "^7.29.8",+ "@babel/types": "^7.29.8",+ "@jridgewell/gen-mapping": "^0.3.12",+ "@jridgewell/trace-mapping": "^0.3.28",+ "jsesc": "^3.0.2"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-compilation-targets": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz",+ "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/compat-data": "^7.29.7",+ "@babel/helper-validator-option": "^7.29.7",+ "browserslist": "^4.24.0",+ "lru-cache": "^5.1.1",+ "semver": "^6.3.1"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-globals": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz",+ "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-module-imports": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz",+ "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/traverse": "^7.29.7",+ "@babel/types": "^7.29.7"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-module-transforms": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz",+ "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/helper-module-imports": "^7.29.7",+ "@babel/helper-validator-identifier": "^7.29.7",+ "@babel/traverse": "^7.29.7"+ },+ "engines": {+ "node": ">=6.9.0"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0"+ }+ },+ "node_modules/@babel/helper-plugin-utils": {+ "version": "7.28.6",+ "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.28.6.tgz",+ "integrity": "sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==",+ "dev": true,+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-string-parser": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",+ "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-validator-identifier": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",+ "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helper-validator-option": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz",+ "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/helpers": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz",+ "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/template": "^7.29.7",+ "@babel/types": "^7.29.7"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/parser": {+ "version": "7.29.8",+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.8.tgz",+ "integrity": "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/types": "^7.29.8"+ },+ "bin": {+ "parser": "bin/babel-parser.js"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@babel/plugin-transform-arrow-functions": {+ "version": "7.27.1",+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.27.1.tgz",+ "integrity": "sha512-8Z4TGic6xW70FKThA5HYEKKyBpOOsucTOD1DjU3fZxDg+K3zBJcXMFnt/4yQiZnf5+MiOMSXQ9PaEK/Ilh1DeA==",+ "dev": true,+ "dependencies": {+ "@babel/helper-plugin-utils": "^7.27.1"+ },+ "engines": {+ "node": ">=6.9.0"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0-0"+ }+ },+ "node_modules/@babel/plugin-transform-react-jsx-self": {+ "version": "7.27.1",+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.27.1.tgz",+ "integrity": "sha512-6UzkCs+ejGdZ5mFFC/OCUrv028ab2fp1znZmCZjAOBKiBK2jXD1O+BPSfX8X2qjJ75fZBMSnQn3Rq2mrBJK2mw==",+ "dev": true,+ "dependencies": {+ "@babel/helper-plugin-utils": "^7.27.1"+ },+ "engines": {+ "node": ">=6.9.0"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0-0"+ }+ },+ "node_modules/@babel/plugin-transform-react-jsx-source": {+ "version": "7.27.1",+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.27.1.tgz",+ "integrity": "sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw==",+ "dev": true,+ "dependencies": {+ "@babel/helper-plugin-utils": "^7.27.1"+ },+ "engines": {+ "node": ">=6.9.0"+ },+ "peerDependencies": {+ "@babel/core": "^7.0.0-0"+ }+ },+ "node_modules/@babel/runtime": {+ "version": "7.28.6",+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.6.tgz",+ "integrity": "sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA==",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/template": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",+ "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/code-frame": "^7.29.7",+ "@babel/parser": "^7.29.7",+ "@babel/types": "^7.29.7"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/traverse": {+ "version": "7.29.8",+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.8.tgz",+ "integrity": "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/code-frame": "^7.29.7",+ "@babel/generator": "^7.29.8",+ "@babel/helper-globals": "^7.29.7",+ "@babel/parser": "^7.29.8",+ "@babel/template": "^7.29.7",+ "@babel/types": "^7.29.8",+ "debug": "^4.3.1"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@babel/types": {+ "version": "7.29.8",+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",+ "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/helper-string-parser": "^7.29.7",+ "@babel/helper-validator-identifier": "^7.29.7"+ },+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@bramus/specificity": {+ "version": "2.4.2",+ "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz",+ "integrity": "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "css-tree": "^3.0.0"+ },+ "bin": {+ "specificity": "bin/cli.js"+ }+ },+ "node_modules/@csstools/color-helpers": {+ "version": "6.1.2",+ "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.2.tgz",+ "integrity": "sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT-0",+ "engines": {+ "node": ">=20.19.0"+ }+ },+ "node_modules/@csstools/css-calc": {+ "version": "3.4.3",+ "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.3.tgz",+ "integrity": "sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^4.0.2",+ "@csstools/css-tokenizer": "^4.0.2"+ }+ },+ "node_modules/@csstools/css-color-parser": {+ "version": "4.2.6",+ "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.6.tgz",+ "integrity": "sha512-iiPQ3iRWwnJkeEn6RIu6SJPr7hYrLz6XZ9s/QZl+2/LI5KQVjpl2fdmDSZKuD4xP6GMmMPgHFFXg6k1Wkz0Trg==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@csstools/color-helpers": "^6.1.2",+ "@csstools/css-calc": "^3.4.3"+ },+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^4.0.2",+ "@csstools/css-tokenizer": "^4.0.2"+ }+ },+ "node_modules/@csstools/css-parser-algorithms": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.2.tgz",+ "integrity": "sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-tokenizer": "^4.0.2"+ }+ },+ "node_modules/@csstools/css-syntax-patches-for-csstree": {+ "version": "1.1.15",+ "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.15.tgz",+ "integrity": "sha512-J0u7HkVl2nzSlhsiTOp4AmwcUQ3D+mGEEKfBy/7To5/y7F2OHwyLrXfrhR0SMgr4p5Lo+eaMVSeai24zUcBIxA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT-0",+ "peerDependencies": {+ "css-tree": "^3.2.1"+ },+ "peerDependenciesMeta": {+ "css-tree": {+ "optional": true+ }+ }+ },+ "node_modules/@csstools/css-tokenizer": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.2.tgz",+ "integrity": "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ }+ },+ "node_modules/@electron-internal/extract-zip": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/@electron-internal/extract-zip/-/extract-zip-1.0.5.tgz",+ "integrity": "sha512-+bqFCP98pLI0Tt0XQo1TmlXtwjWchISndDOxCkEcIuUgXWpBnLyRI+2DU+mesvnMMX6L1XDqYNA0lXNDHd/yiA==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=22.12.0"+ }+ },+ "node_modules/@electron-toolkit/utils": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@electron-toolkit/utils/-/utils-4.0.0.tgz",+ "integrity": "sha512-qXSntwEzluSzKl4z5yFNBknmPGjPa3zFhE4mp9+h0cgokY5ornAeP+CJQDBhKsL1S58aOQfcwkD3NwLZCl+64g==",+ "peerDependencies": {+ "electron": ">=13.0.0"+ }+ },+ "node_modules/@electron/asar": {+ "version": "3.4.1",+ "resolved": "https://registry.npmjs.org/@electron/asar/-/asar-3.4.1.tgz",+ "integrity": "sha512-i4/rNPRS84t0vSRa2HorerGRXWyF4vThfHesw0dmcWHp+cspK743UanA0suA5Q5y8kzY2y6YKrvbIUn69BCAiA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "commander": "^5.0.0",+ "glob": "^7.1.6",+ "minimatch": "^3.0.4"+ },+ "bin": {+ "asar": "bin/asar.js"+ },+ "engines": {+ "node": ">=10.12.0"+ }+ },+ "node_modules/@electron/asar/node_modules/brace-expansion": {+ "version": "1.1.18",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",+ "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0",+ "concat-map": "0.0.1"+ }+ },+ "node_modules/@electron/asar/node_modules/minimatch": {+ "version": "3.1.5",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^1.1.7"+ },+ "engines": {+ "node": "*"+ }+ },+ "node_modules/@electron/fuses": {+ "version": "1.8.0",+ "resolved": "https://registry.npmjs.org/@electron/fuses/-/fuses-1.8.0.tgz",+ "integrity": "sha512-zx0EIq78WlY/lBb1uXlziZmDZI4ubcCXIMJ4uGjXzZW0nS19TjSPeXPAjzzTmKQlJUZm0SbmZhPKP7tuQ1SsEw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "chalk": "^4.1.1",+ "fs-extra": "^9.0.1",+ "minimist": "^1.2.5"+ },+ "bin": {+ "electron-fuses": "dist/bin.js"+ }+ },+ "node_modules/@electron/fuses/node_modules/fs-extra": {+ "version": "9.1.0",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz",+ "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "at-least-node": "^1.0.0",+ "graceful-fs": "^4.2.0",+ "jsonfile": "^6.0.1",+ "universalify": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@electron/get": {+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/@electron/get/-/get-5.1.0.tgz",+ "integrity": "sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.1.1",+ "env-paths": "^3.0.0",+ "graceful-fs": "^4.2.11",+ "progress": "^2.0.3",+ "semver": "^7.6.3",+ "sumchecker": "^3.0.1"+ },+ "engines": {+ "node": ">=22.12.0"+ },+ "optionalDependencies": {+ "undici": "^7.24.4"+ }+ },+ "node_modules/@electron/get/node_modules/semver": {+ "version": "7.8.5",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@electron/notarize": {+ "version": "2.5.0",+ "resolved": "https://registry.npmjs.org/@electron/notarize/-/notarize-2.5.0.tgz",+ "integrity": "sha512-jNT8nwH1f9X5GEITXaQ8IF/KdskvIkOFfB2CvwumsveVidzpSc+mvhhTMdAGSYF3O+Nq49lJ7y+ssODRXu06+A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "debug": "^4.1.1",+ "fs-extra": "^9.0.1",+ "promise-retry": "^2.0.1"+ },+ "engines": {+ "node": ">= 10.0.0"+ }+ },+ "node_modules/@electron/notarize/node_modules/fs-extra": {+ "version": "9.1.0",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz",+ "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "at-least-node": "^1.0.0",+ "graceful-fs": "^4.2.0",+ "jsonfile": "^6.0.1",+ "universalify": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@electron/osx-sign": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/@electron/osx-sign/-/osx-sign-1.3.3.tgz",+ "integrity": "sha512-KZ8mhXvWv2rIEgMbWZ4y33bDHyUKMXnx4M0sTyPNK/vcB81ImdeY9Ggdqy0SWbMDgmbqyQ+phgejh6V3R2QuSg==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "compare-version": "^0.1.2",+ "debug": "^4.3.4",+ "fs-extra": "^10.0.0",+ "isbinaryfile": "^4.0.8",+ "minimist": "^1.2.6",+ "plist": "^3.0.5"+ },+ "bin": {+ "electron-osx-flat": "bin/electron-osx-flat.js",+ "electron-osx-sign": "bin/electron-osx-sign.js"+ },+ "engines": {+ "node": ">=12.0.0"+ }+ },+ "node_modules/@electron/osx-sign/node_modules/isbinaryfile": {+ "version": "4.0.10",+ "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-4.0.10.tgz",+ "integrity": "sha512-iHrqe5shvBUcFbmZq9zOQHBoeOhZJu6RQGrDpBgenUm/Am+F3JM2MgQj+rK3Z601fzrL5gLZWtAPH2OBaSVcyw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 8.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/gjtorikian/"+ }+ },+ "node_modules/@electron/rebuild": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/@electron/rebuild/-/rebuild-4.2.0.tgz",+ "integrity": "sha512-RKL/O+jGoXJMxrx/5771y1n0xTKmFuOYGO3gMmwypBM6rsH0kou0mswwdXA2JrhIkE4xyC7v9vGk0n6NPzgOxQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@malept/cross-spawn-promise": "^2.0.0",+ "debug": "^4.1.1",+ "node-abi": "^4.2.0",+ "node-api-version": "^0.2.1",+ "node-gyp": "^12.2.0",+ "read-binary-file-arch": "^1.0.6"+ },+ "bin": {+ "electron-rebuild": "lib/cli.js"+ },+ "engines": {+ "node": ">=22.12.0"+ }+ },+ "node_modules/@electron/universal": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/@electron/universal/-/universal-2.0.3.tgz",+ "integrity": "sha512-Wn9sPYIVFRFl5HmwMJkARCCf7rqK/EurkfQ/rJZ14mHP3iYTjZSIOSVonEAnhWeAXwtw7zOekGRlc6yTtZ0t+g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@electron/asar": "^3.3.1",+ "@malept/cross-spawn-promise": "^2.0.0",+ "debug": "^4.3.1",+ "dir-compare": "^4.2.0",+ "fs-extra": "^11.1.1",+ "minimatch": "^9.0.3",+ "plist": "^3.1.0"+ },+ "engines": {+ "node": ">=16.4"+ }+ },+ "node_modules/@electron/universal/node_modules/brace-expansion": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",+ "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0"+ }+ },+ "node_modules/@electron/universal/node_modules/fs-extra": {+ "version": "11.4.0",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.0.tgz",+ "integrity": "sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.2.0",+ "jsonfile": "^6.0.1",+ "universalify": "^2.0.0"+ },+ "engines": {+ "node": ">=14.14"+ }+ },+ "node_modules/@electron/universal/node_modules/minimatch": {+ "version": "9.0.9",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",+ "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^2.0.2"+ },+ "engines": {+ "node": ">=16 || 14 >=14.17"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },+ "node_modules/@electron/windows-sign": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/@electron/windows-sign/-/windows-sign-1.2.2.tgz",+ "integrity": "sha512-dfZeox66AvdPtb2lD8OsIIQh12Tp0GNCRUDfBHIKGpbmopZto2/A8nSpYYLoedPIHpqkeblZ/k8OV0Gy7PYuyQ==",+ "dev": true,+ "license": "BSD-2-Clause",+ "optional": true,+ "peer": true,+ "dependencies": {+ "cross-dirname": "^0.1.0",+ "debug": "^4.3.4",+ "fs-extra": "^11.1.1",+ "minimist": "^1.2.8",+ "postject": "^1.0.0-alpha.6"+ },+ "bin": {+ "electron-windows-sign": "bin/electron-windows-sign.js"+ },+ "engines": {+ "node": ">=14.14"+ }+ },+ "node_modules/@electron/windows-sign/node_modules/fs-extra": {+ "version": "11.4.0",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.0.tgz",+ "integrity": "sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "peer": true,+ "dependencies": {+ "graceful-fs": "^4.2.0",+ "jsonfile": "^6.0.1",+ "universalify": "^2.0.0"+ },+ "engines": {+ "node": ">=14.14"+ }+ },+ "node_modules/@epic-web/invariant": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/@epic-web/invariant/-/invariant-1.0.0.tgz",+ "integrity": "sha512-lrTPqgvfFQtR/eY/qkIzp98OGdNJu0m5ji3q/nJI8v3SXkRKEnWiOxMmbvcSoAIzv/cGiuvRy57k4suKQSAdwA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",+ "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",+ "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",+ "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",+ "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",+ "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",+ "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",+ "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",+ "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",+ "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",+ "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",+ "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",+ "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",+ "cpu": [+ "loong64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",+ "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",+ "cpu": [+ "mips64el"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",+ "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",+ "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",+ "cpu": [+ "riscv64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",+ "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",+ "cpu": [+ "s390x"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",+ "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",+ "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",+ "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",+ "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",+ "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",+ "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",+ "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",+ "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",+ "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",+ "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@eslint-community/eslint-utils": {+ "version": "4.9.1",+ "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz",+ "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==",+ "dev": true,+ "dependencies": {+ "eslint-visitor-keys": "^3.4.3"+ },+ "engines": {+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ },+ "peerDependencies": {+ "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0"+ }+ },+ "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": {+ "version": "3.4.3",+ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz",+ "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==",+ "dev": true,+ "engines": {+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/@eslint-community/regexpp": {+ "version": "4.12.2",+ "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz",+ "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==",+ "dev": true,+ "engines": {+ "node": "^12.0.0 || ^14.0.0 || >=16.0.0"+ }+ },+ "node_modules/@eslint/config-array": {+ "version": "0.21.1",+ "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.1.tgz",+ "integrity": "sha512-aw1gNayWpdI/jSYVgzN5pL0cfzU02GT3NBpeT/DXbx1/1x7ZKxFPd9bwrzygx/qiwIQiJ1sw/zD8qY/kRvlGHA==",+ "dev": true,+ "dependencies": {+ "@eslint/object-schema": "^2.1.7",+ "debug": "^4.3.1",+ "minimatch": "^3.1.2"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@eslint/config-array/node_modules/brace-expansion": {+ "version": "1.1.18",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",+ "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0",+ "concat-map": "0.0.1"+ }+ },+ "node_modules/@eslint/config-array/node_modules/minimatch": {+ "version": "3.1.5",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^1.1.7"+ },+ "engines": {+ "node": "*"+ }+ },+ "node_modules/@eslint/config-helpers": {+ "version": "0.4.2",+ "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz",+ "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==",+ "dev": true,+ "dependencies": {+ "@eslint/core": "^0.17.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@eslint/core": {+ "version": "0.17.0",+ "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz",+ "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==",+ "dev": true,+ "dependencies": {+ "@types/json-schema": "^7.0.15"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@eslint/eslintrc": {+ "version": "3.3.4",+ "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.4.tgz",+ "integrity": "sha512-4h4MVF8pmBsncB60r0wSJiIeUKTSD4m7FmTFThG8RHlsg9ajqckLm9OraguFGZE4vVdpiI1Q4+hFnisopmG6gQ==",+ "dev": true,+ "dependencies": {+ "ajv": "^6.14.0",+ "debug": "^4.3.2",+ "espree": "^10.0.1",+ "globals": "^14.0.0",+ "ignore": "^5.2.0",+ "import-fresh": "^3.2.1",+ "js-yaml": "^4.1.1",+ "minimatch": "^3.1.3",+ "strip-json-comments": "^3.1.1"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/@eslint/eslintrc/node_modules/brace-expansion": {+ "version": "1.1.18",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",+ "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0",+ "concat-map": "0.0.1"+ }+ },+ "node_modules/@eslint/eslintrc/node_modules/globals": {+ "version": "14.0.0",+ "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz",+ "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/@eslint/eslintrc/node_modules/minimatch": {+ "version": "3.1.5",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^1.1.7"+ },+ "engines": {+ "node": "*"+ }+ },+ "node_modules/@eslint/js": {+ "version": "9.39.5",+ "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.5.tgz",+ "integrity": "sha512-QywQuszQh77pIXCsq998c8hbhSTI/azTty1Z6N53dmAudKHhy573j3yvRLsX2BSp8YpLtoCEG8E9DJe+8zUh4A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://eslint.org/donate"+ }+ },+ "node_modules/@eslint/object-schema": {+ "version": "2.1.7",+ "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz",+ "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==",+ "dev": true,+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@eslint/plugin-kit": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz",+ "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==",+ "dev": true,+ "dependencies": {+ "@eslint/core": "^0.17.0",+ "levn": "^0.4.1"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ }+ },+ "node_modules/@exodus/bytes": {+ "version": "1.16.0",+ "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz",+ "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ },+ "peerDependencies": {+ "@noble/hashes": "^1.8.0 || ^2.0.0"+ },+ "peerDependenciesMeta": {+ "@noble/hashes": {+ "optional": true+ }+ }+ },+ "node_modules/@humanfs/core": {+ "version": "0.19.1",+ "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz",+ "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==",+ "dev": true,+ "engines": {+ "node": ">=18.18.0"+ }+ },+ "node_modules/@humanfs/node": {+ "version": "0.16.7",+ "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz",+ "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==",+ "dev": true,+ "dependencies": {+ "@humanfs/core": "^0.19.1",+ "@humanwhocodes/retry": "^0.4.0"+ },+ "engines": {+ "node": ">=18.18.0"+ }+ },+ "node_modules/@humanwhocodes/module-importer": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz",+ "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==",+ "dev": true,+ "engines": {+ "node": ">=12.22"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/nzakas"+ }+ },+ "node_modules/@humanwhocodes/retry": {+ "version": "0.4.3",+ "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz",+ "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==",+ "dev": true,+ "engines": {+ "node": ">=18.18"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/nzakas"+ }+ },+ "node_modules/@isaacs/fs-minipass": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz",+ "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==",+ "dependencies": {+ "minipass": "^7.0.4"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@isaacs/fs-minipass/node_modules/minipass": {+ "version": "7.1.3",+ "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",+ "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",+ "engines": {+ "node": ">=16 || 14 >=14.17"+ }+ },+ "node_modules/@jridgewell/gen-mapping": {+ "version": "0.3.13",+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",+ "dev": true,+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.0",+ "@jridgewell/trace-mapping": "^0.3.24"+ }+ },+ "node_modules/@jridgewell/remapping": {+ "version": "2.3.5",+ "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",+ "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",+ "dev": true,+ "dependencies": {+ "@jridgewell/gen-mapping": "^0.3.5",+ "@jridgewell/trace-mapping": "^0.3.24"+ }+ },+ "node_modules/@jridgewell/resolve-uri": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",+ "dev": true,+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@jridgewell/sourcemap-codec": {+ "version": "1.5.5",+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",+ "dev": true+ },+ "node_modules/@jridgewell/trace-mapping": {+ "version": "0.3.31",+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",+ "dev": true,+ "dependencies": {+ "@jridgewell/resolve-uri": "^3.1.0",+ "@jridgewell/sourcemap-codec": "^1.4.14"+ }+ },+ "node_modules/@malept/cross-spawn-promise": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/@malept/cross-spawn-promise/-/cross-spawn-promise-2.0.0.tgz",+ "integrity": "sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==",+ "dev": true,+ "funding": [+ {+ "type": "individual",+ "url": "https://github.com/sponsors/malept"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/subscription/pkg/npm-.malept-cross-spawn-promise?utm_medium=referral&utm_source=npm_fund"+ }+ ],+ "license": "Apache-2.0",+ "dependencies": {+ "cross-spawn": "^7.0.1"+ },+ "engines": {+ "node": ">= 12.13.0"+ }+ },+ "node_modules/@malept/flatpak-bundler": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/@malept/flatpak-bundler/-/flatpak-bundler-0.4.0.tgz",+ "integrity": "sha512-9QOtNffcOF/c1seMCDnjckb3R9WHcG34tky+FHpNKKCW0wc/scYLwMtO+ptyGUfMW0/b/n4qRiALlaFHc9Oj7Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "debug": "^4.1.1",+ "fs-extra": "^9.0.0",+ "lodash": "^4.17.15",+ "tmp-promise": "^3.0.2"+ },+ "engines": {+ "node": ">= 10.0.0"+ }+ },+ "node_modules/@malept/flatpak-bundler/node_modules/fs-extra": {+ "version": "9.1.0",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz",+ "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "at-least-node": "^1.0.0",+ "graceful-fs": "^4.2.0",+ "jsonfile": "^6.0.1",+ "universalify": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@mediapipe/tasks-vision": {+ "version": "0.10.17",+ "resolved": "https://registry.npmjs.org/@mediapipe/tasks-vision/-/tasks-vision-0.10.17.tgz",+ "integrity": "sha512-CZWV/q6TTe8ta61cZXjfnnHsfWIdFhms03M9T7Cnd5y2mdpylJM0rF1qRq+wsQVRMLz1OYPVEBU9ph2Bx8cxrg=="+ },+ "node_modules/@mkkellogg/gaussian-splats-3d": {+ "version": "0.4.7",+ "resolved": "https://registry.npmjs.org/@mkkellogg/gaussian-splats-3d/-/gaussian-splats-3d-0.4.7.tgz",+ "integrity": "sha512-0vy9/i9sJLFH/v3WJZ4axCsqjkToe8UsV3xY7bvK5EUC0akiRsWZODoCiSzpxhTLNyzSKTsyQKozIFeNA5RWRA==",+ "license": "MIT",+ "peerDependencies": {+ "three": ">=0.160.0"+ }+ },+ "node_modules/@monogrid/gainmap-js": {+ "version": "3.4.0",+ "resolved": "https://registry.npmjs.org/@monogrid/gainmap-js/-/gainmap-js-3.4.0.tgz",+ "integrity": "sha512-2Z0FATFHaoYJ8b+Y4y4Hgfn3FRFwuU5zRrk+9dFWp4uGAdHGqVEdP7HP+gLA3X469KXHmfupJaUbKo1b/aDKIg==",+ "dependencies": {+ "promise-worker-transferable": "^1.0.4"+ },+ "peerDependencies": {+ "three": ">= 0.159.0"+ }+ },+ "node_modules/@noble/hashes": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.3.0.tgz",+ "integrity": "sha512-oN+QwyX7VSHotibwubG3kpzbwKrfnyR6OOO+3Nk/53ADL7FmgHHz4TgrbaYKvvOw09u6QTx0oiH1cNCIOuN0CQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 20.19.0"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/@nodelib/fs.scandir": {+ "version": "2.1.5",+ "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",+ "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==",+ "dev": true,+ "dependencies": {+ "@nodelib/fs.stat": "2.0.5",+ "run-parallel": "^1.1.9"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/@nodelib/fs.stat": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz",+ "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==",+ "dev": true,+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/@nodelib/fs.walk": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz",+ "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==",+ "dev": true,+ "dependencies": {+ "@nodelib/fs.scandir": "2.1.5",+ "fastq": "^1.6.0"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/@peculiar/asn1-schema": {+ "version": "2.9.4",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.9.4.tgz",+ "integrity": "sha512-GjzePcT9Iw8NzeOPf73iNS9xM+TBhd/FilAfP+RQGkTMQJTVWtytN3JHJACCjf/ABNau5S7mS3g+DcuxmRgYEg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@peculiar/utils": "^2.0.2",+ "asn1js": "^3.0.10",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@peculiar/json-schema": {+ "version": "1.1.12",+ "resolved": "https://registry.npmjs.org/@peculiar/json-schema/-/json-schema-1.1.12.tgz",+ "integrity": "sha512-coUfuoMeIB7B8/NMekxaDzLhaYmp0HZNPEjYRm9goRou8UZIC3z21s0sL9AWoCw4EG876QyO3kYrc61WNF9B/w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.0.0"+ },+ "engines": {+ "node": ">=8.0.0"+ }+ },+ "node_modules/@peculiar/utils": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/@peculiar/utils/-/utils-2.0.3.tgz",+ "integrity": "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.8.1"+ }+ },+ "node_modules/@peculiar/webcrypto": {+ "version": "1.7.1",+ "resolved": "https://registry.npmjs.org/@peculiar/webcrypto/-/webcrypto-1.7.1.tgz",+ "integrity": "sha512-ODOov0sGMJMf3jPonOkgGqPknTsu+DdQ7kD++gz8aI+aFMOMHFbWAA2taqXXVTdP+OTOQR/znGvSpmkeI0WTYQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@peculiar/asn1-schema": "^2.7.0",+ "@peculiar/json-schema": "^1.1.12",+ "@peculiar/utils": "^2.0.2",+ "tslib": "^2.8.1",+ "webcrypto-core": "^1.9.2"+ },+ "engines": {+ "node": ">=14.18.0"+ }+ },+ "node_modules/@react-spring/animated": {+ "version": "9.7.5",+ "resolved": "https://registry.npmjs.org/@react-spring/animated/-/animated-9.7.5.tgz",+ "integrity": "sha512-Tqrwz7pIlsSDITzxoLS3n/v/YCUHQdOIKtOJf4yL6kYVSDTSmVK1LI1Q3M/uu2Sx4X3pIWF3xLUhlsA6SPNTNg==",+ "dependencies": {+ "@react-spring/shared": "~9.7.5",+ "@react-spring/types": "~9.7.5"+ },+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0"+ }+ },+ "node_modules/@react-spring/core": {+ "version": "9.7.5",+ "resolved": "https://registry.npmjs.org/@react-spring/core/-/core-9.7.5.tgz",+ "integrity": "sha512-rmEqcxRcu7dWh7MnCcMXLvrf6/SDlSokLaLTxiPlAYi11nN3B5oiCUAblO72o+9z/87j2uzxa2Inm8UbLjXA+w==",+ "dependencies": {+ "@react-spring/animated": "~9.7.5",+ "@react-spring/shared": "~9.7.5",+ "@react-spring/types": "~9.7.5"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/react-spring/donate"+ },+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0"+ }+ },+ "node_modules/@react-spring/rafz": {+ "version": "9.7.5",+ "resolved": "https://registry.npmjs.org/@react-spring/rafz/-/rafz-9.7.5.tgz",+ "integrity": "sha512-5ZenDQMC48wjUzPAm1EtwQ5Ot3bLIAwwqP2w2owG5KoNdNHpEJV263nGhCeKKmuA3vG2zLLOdu3or6kuDjA6Aw=="+ },+ "node_modules/@react-spring/shared": {+ "version": "9.7.5",+ "resolved": "https://registry.npmjs.org/@react-spring/shared/-/shared-9.7.5.tgz",+ "integrity": "sha512-wdtoJrhUeeyD/PP/zo+np2s1Z820Ohr/BbuVYv+3dVLW7WctoiN7std8rISoYoHpUXtbkpesSKuPIw/6U1w1Pw==",+ "dependencies": {+ "@react-spring/rafz": "~9.7.5",+ "@react-spring/types": "~9.7.5"+ },+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0"+ }+ },+ "node_modules/@react-spring/three": {+ "version": "9.7.5",+ "resolved": "https://registry.npmjs.org/@react-spring/three/-/three-9.7.5.tgz",+ "integrity": "sha512-RxIsCoQfUqOS3POmhVHa1wdWS0wyHAUway73uRLp3GAL5U2iYVNdnzQsep6M2NZ994BlW8TcKuMtQHUqOsy6WA==",+ "dependencies": {+ "@react-spring/animated": "~9.7.5",+ "@react-spring/core": "~9.7.5",+ "@react-spring/shared": "~9.7.5",+ "@react-spring/types": "~9.7.5"+ },+ "peerDependencies": {+ "@react-three/fiber": ">=6.0",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0",+ "three": ">=0.126"+ }+ },+ "node_modules/@react-spring/types": {+ "version": "9.7.5",+ "resolved": "https://registry.npmjs.org/@react-spring/types/-/types-9.7.5.tgz",+ "integrity": "sha512-HVj7LrZ4ReHWBimBvu2SKND3cDVUPWKLqRTmWe/fNY6o1owGOX0cAHbdPDTMelgBlVbrTKrre6lFkhqGZErK/g=="+ },+ "node_modules/@react-three/drei": {+ "version": "9.122.0",+ "resolved": "https://registry.npmjs.org/@react-three/drei/-/drei-9.122.0.tgz",+ "integrity": "sha512-SEO/F/rBCTjlLez7WAlpys+iGe9hty4rNgjZvgkQeXFSiwqD4Hbk/wNHMAbdd8vprO2Aj81mihv4dF5bC7D0CA==",+ "dependencies": {+ "@babel/runtime": "^7.26.0",+ "@mediapipe/tasks-vision": "0.10.17",+ "@monogrid/gainmap-js": "^3.0.6",+ "@react-spring/three": "~9.7.5",+ "@use-gesture/react": "^10.3.1",+ "camera-controls": "^2.9.0",+ "cross-env": "^7.0.3",+ "detect-gpu": "^5.0.56",+ "glsl-noise": "^0.0.0",+ "hls.js": "^1.5.17",+ "maath": "^0.10.8",+ "meshline": "^3.3.1",+ "react-composer": "^5.0.3",+ "stats-gl": "^2.2.8",+ "stats.js": "^0.17.0",+ "suspend-react": "^0.1.3",+ "three-mesh-bvh": "^0.7.8",+ "three-stdlib": "^2.35.6",+ "troika-three-text": "^0.52.0",+ "tunnel-rat": "^0.1.2",+ "utility-types": "^3.11.0",+ "zustand": "^5.0.1"+ },+ "peerDependencies": {+ "@react-three/fiber": "^8",+ "react": "^18",+ "react-dom": "^18",+ "three": ">=0.137"+ },+ "peerDependenciesMeta": {+ "react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@react-three/drei/node_modules/cross-env": {+ "version": "7.0.3",+ "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz",+ "integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==",+ "license": "MIT",+ "dependencies": {+ "cross-spawn": "^7.0.1"+ },+ "bin": {+ "cross-env": "src/bin/cross-env.js",+ "cross-env-shell": "src/bin/cross-env-shell.js"+ },+ "engines": {+ "node": ">=10.14",+ "npm": ">=6",+ "yarn": ">=1"+ }+ },+ "node_modules/@react-three/drei/node_modules/three-mesh-bvh": {+ "version": "0.7.8",+ "resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.7.8.tgz",+ "integrity": "sha512-BGEZTOIC14U0XIRw3tO4jY7IjP7n7v24nv9JXS1CyeVRWOCkcOMhRnmENUjuV39gktAw4Ofhr0OvIAiTspQrrw==",+ "deprecated": "Deprecated due to three.js version incompatibility. Please use v0.8.0, instead.",+ "license": "MIT",+ "peerDependencies": {+ "three": ">= 0.151.0"+ }+ },+ "node_modules/@react-three/fiber": {+ "version": "8.18.0",+ "resolved": "https://registry.npmjs.org/@react-three/fiber/-/fiber-8.18.0.tgz",+ "integrity": "sha512-FYZZqD0UUHUswKz3LQl2Z7H24AhD14XGTsIRw3SJaXUxyfVMi+1yiZGmqTcPt/CkPpdU7rrxqcyQ1zJE5DjvIQ==",+ "dependencies": {+ "@babel/runtime": "^7.17.8",+ "@types/react-reconciler": "^0.26.7",+ "@types/webxr": "*",+ "base64-js": "^1.5.1",+ "buffer": "^6.0.3",+ "its-fine": "^1.0.6",+ "react-reconciler": "^0.27.0",+ "react-use-measure": "^2.1.7",+ "scheduler": "^0.21.0",+ "suspend-react": "^0.1.3",+ "zustand": "^3.7.1"+ },+ "peerDependencies": {+ "expo": ">=43.0",+ "expo-asset": ">=8.4",+ "expo-file-system": ">=11.0",+ "expo-gl": ">=11.0",+ "react": ">=18 <19",+ "react-dom": ">=18 <19",+ "react-native": ">=0.64",+ "three": ">=0.133"+ },+ "peerDependenciesMeta": {+ "expo": {+ "optional": true+ },+ "expo-asset": {+ "optional": true+ },+ "expo-file-system": {+ "optional": true+ },+ "expo-gl": {+ "optional": true+ },+ "react-dom": {+ "optional": true+ },+ "react-native": {+ "optional": true+ }+ }+ },+ "node_modules/@react-three/fiber/node_modules/zustand": {+ "version": "3.7.2",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-3.7.2.tgz",+ "integrity": "sha512-PIJDIZKtokhof+9+60cpockVOq05sJzHCriyvaLBmEJixseQ1a5Kdov6fWZfWOu5SK9c+FhH1jU0tntLxRJYMA==",+ "engines": {+ "node": ">=12.7.0"+ },+ "peerDependencies": {+ "react": ">=16.8"+ },+ "peerDependenciesMeta": {+ "react": {+ "optional": true+ }+ }+ },+ "node_modules/@react-three/postprocessing": {+ "version": "2.19.1",+ "resolved": "https://registry.npmjs.org/@react-three/postprocessing/-/postprocessing-2.19.1.tgz",+ "integrity": "sha512-7P25LOSToH/I6b3UipNK17IIFlX4FDUmWcaomfwu82+CzhXTOz8Fcc1ZXEZ7vFA/5Fr/2peNlXgXZJvoa+aCdA==",+ "license": "MIT",+ "dependencies": {+ "buffer": "^6.0.3",+ "maath": "^0.6.0",+ "n8ao": "^1.6.6",+ "postprocessing": "^6.32.1",+ "three-stdlib": "^2.23.4"+ },+ "peerDependencies": {+ "@react-three/fiber": "^8.0",+ "react": "^18.0",+ "three": ">= 0.138.0"+ }+ },+ "node_modules/@react-three/postprocessing/node_modules/maath": {+ "version": "0.6.0",+ "resolved": "https://registry.npmjs.org/maath/-/maath-0.6.0.tgz",+ "integrity": "sha512-dSb2xQuP7vDnaYqfoKzlApeRcR2xtN8/f7WV/TMAkBC8552TwTLtOO0JTcSygkYMjNDPoo6V01jTw/aPi4JrMw==",+ "license": "MIT",+ "peerDependencies": {+ "@types/three": ">=0.144.0",+ "three": ">=0.144.0"+ }+ },+ "node_modules/@rolldown/pluginutils": {+ "version": "1.0.0-beta.27",+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",+ "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==",+ "dev": true+ },+ "node_modules/@rollup/rollup-android-arm-eabi": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz",+ "integrity": "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@rollup/rollup-android-arm64": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.59.0.tgz",+ "integrity": "sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@rollup/rollup-darwin-arm64": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.59.0.tgz",+ "integrity": "sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rollup/rollup-darwin-x64": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.59.0.tgz",+ "integrity": "sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rollup/rollup-freebsd-arm64": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.59.0.tgz",+ "integrity": "sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@rollup/rollup-freebsd-x64": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.59.0.tgz",+ "integrity": "sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.59.0.tgz",+ "integrity": "sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.59.0.tgz",+ "integrity": "sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm64-gnu": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.59.0.tgz",+ "integrity": "sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm64-musl": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.59.0.tgz",+ "integrity": "sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-loong64-gnu": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.59.0.tgz",+ "integrity": "sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-loong64-musl": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.59.0.tgz",+ "integrity": "sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.59.0.tgz",+ "integrity": "sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-ppc64-musl": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.59.0.tgz",+ "integrity": "sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.59.0.tgz",+ "integrity": "sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-riscv64-musl": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.59.0.tgz",+ "integrity": "sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-s390x-gnu": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.59.0.tgz",+ "integrity": "sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-x64-gnu": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.59.0.tgz",+ "integrity": "sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-x64-musl": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.59.0.tgz",+ "integrity": "sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-openbsd-x64": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.59.0.tgz",+ "integrity": "sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "openbsd"+ ]+ },+ "node_modules/@rollup/rollup-openharmony-arm64": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.59.0.tgz",+ "integrity": "sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "openharmony"+ ]+ },+ "node_modules/@rollup/rollup-win32-arm64-msvc": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.59.0.tgz",+ "integrity": "sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-ia32-msvc": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.59.0.tgz",+ "integrity": "sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-x64-gnu": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.59.0.tgz",+ "integrity": "sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-x64-msvc": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.59.0.tgz",+ "integrity": "sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@sindresorhus/is": {+ "version": "4.6.0",+ "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz",+ "integrity": "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/is?sponsor=1"+ }+ },+ "node_modules/@szmarczak/http-timer": {+ "version": "4.0.6",+ "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.6.tgz",+ "integrity": "sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "defer-to-connect": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@tweenjs/tween.js": {+ "version": "23.1.3",+ "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",+ "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA=="+ },+ "node_modules/@types/babel__core": {+ "version": "7.20.5",+ "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",+ "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==",+ "dev": true,+ "dependencies": {+ "@babel/parser": "^7.20.7",+ "@babel/types": "^7.20.7",+ "@types/babel__generator": "*",+ "@types/babel__template": "*",+ "@types/babel__traverse": "*"+ }+ },+ "node_modules/@types/babel__generator": {+ "version": "7.27.0",+ "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz",+ "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==",+ "dev": true,+ "dependencies": {+ "@babel/types": "^7.0.0"+ }+ },+ "node_modules/@types/babel__template": {+ "version": "7.4.4",+ "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz",+ "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==",+ "dev": true,+ "dependencies": {+ "@babel/parser": "^7.1.0",+ "@babel/types": "^7.0.0"+ }+ },+ "node_modules/@types/babel__traverse": {+ "version": "7.28.0",+ "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz",+ "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==",+ "dev": true,+ "dependencies": {+ "@babel/types": "^7.28.2"+ }+ },+ "node_modules/@types/cacheable-request": {+ "version": "6.0.3",+ "resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.3.tgz",+ "integrity": "sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/http-cache-semantics": "*",+ "@types/keyv": "^3.1.4",+ "@types/node": "*",+ "@types/responselike": "^1.0.0"+ }+ },+ "node_modules/@types/d3-color": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",+ "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",+ "license": "MIT"+ },+ "node_modules/@types/d3-drag": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz",+ "integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/d3-interpolate": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",+ "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-color": "*"+ }+ },+ "node_modules/@types/d3-selection": {+ "version": "3.0.11",+ "resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.11.tgz",+ "integrity": "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==",+ "license": "MIT"+ },+ "node_modules/@types/d3-transition": {+ "version": "3.0.9",+ "resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz",+ "integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/d3-zoom": {+ "version": "3.0.8",+ "resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.8.tgz",+ "integrity": "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-interpolate": "*",+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/debug": {+ "version": "4.1.13",+ "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz",+ "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/ms": "*"+ }+ },+ "node_modules/@types/draco3d": {+ "version": "1.4.10",+ "resolved": "https://registry.npmjs.org/@types/draco3d/-/draco3d-1.4.10.tgz",+ "integrity": "sha512-AX22jp8Y7wwaBgAixaSvkoG4M/+PlAcm3Qs4OW8yT9DM4xUpWKeFhLueTAyZF39pviAdcDdeJoACapiAceqNcw=="+ },+ "node_modules/@types/estree": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",+ "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",+ "dev": true+ },+ "node_modules/@types/fs-extra": {+ "version": "9.0.13",+ "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-9.0.13.tgz",+ "integrity": "sha512-nEnwB++1u5lVDM2UI4c1+5R+FYaKfaAzS4OococimjVm3nQw3TuzH5UNsocrcTBbhnerblyHj4A49qXbIiZdpA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/http-cache-semantics": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",+ "integrity": "sha512-L3LgimLHXtGkWikKnsPg0/VFx9OGZaC+eN1u4r+OB1XRqH3meBIAVC2zr1WdMH+RHmnRkqliQAOHNJ/E0j/e0Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/json-schema": {+ "version": "7.0.15",+ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",+ "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",+ "dev": true+ },+ "node_modules/@types/keyv": {+ "version": "3.1.4",+ "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz",+ "integrity": "sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/ms": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/node": {+ "version": "22.19.11",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.11.tgz",+ "integrity": "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w==",+ "dev": true,+ "dependencies": {+ "undici-types": "~6.21.0"+ }+ },+ "node_modules/@types/offscreencanvas": {+ "version": "2019.7.3",+ "resolved": "https://registry.npmjs.org/@types/offscreencanvas/-/offscreencanvas-2019.7.3.tgz",+ "integrity": "sha512-ieXiYmgSRXUDeOntE1InxjWyvEelZGP63M+cGuquuRLuIKKT1osnkXjxev9B7d1nXSug5vpunx+gNlbVxMlC9A=="+ },+ "node_modules/@types/prop-types": {+ "version": "15.7.15",+ "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",+ "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw=="+ },+ "node_modules/@types/react": {+ "version": "18.3.28",+ "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.28.tgz",+ "integrity": "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==",+ "dependencies": {+ "@types/prop-types": "*",+ "csstype": "^3.2.2"+ }+ },+ "node_modules/@types/react-dom": {+ "version": "18.3.7",+ "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz",+ "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",+ "dev": true,+ "peerDependencies": {+ "@types/react": "^18.0.0"+ }+ },+ "node_modules/@types/react-reconciler": {+ "version": "0.26.7",+ "resolved": "https://registry.npmjs.org/@types/react-reconciler/-/react-reconciler-0.26.7.tgz",+ "integrity": "sha512-mBDYl8x+oyPX/VBb3E638N0B7xG+SPk/EAMcVPeexqus/5aTpTphQi0curhhshOqRrc9t6OPoJfEUkbymse/lQ==",+ "dependencies": {+ "@types/react": "*"+ }+ },+ "node_modules/@types/responselike": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.3.tgz",+ "integrity": "sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/stats.js": {+ "version": "0.17.4",+ "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz",+ "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA=="+ },+ "node_modules/@types/tar": {+ "version": "7.0.87",+ "resolved": "https://registry.npmjs.org/@types/tar/-/tar-7.0.87.tgz",+ "integrity": "sha512-3IxNBV8LeY5oi2ZFpvAhOtW1+mHswkzM7BuisVrwJgPv67GBO2rkLPQlEKtzfHuLdhDDczhkCZeT+RuizMay4A==",+ "deprecated": "This is a stub types definition. tar provides its own type definitions, so you do not need this installed.",+ "dev": true,+ "dependencies": {+ "tar": "*"+ }+ },+ "node_modules/@types/three": {+ "version": "0.171.0",+ "resolved": "https://registry.npmjs.org/@types/three/-/three-0.171.0.tgz",+ "integrity": "sha512-oLuT1SAsT+CUg/wxUTFHo0K3NtJLnx9sJhZWQJp/0uXqFpzSk1hRHmvWvpaAWSfvx2db0lVKZ5/wV0I0isD2mQ==",+ "dependencies": {+ "@tweenjs/tween.js": "~23.1.3",+ "@types/stats.js": "*",+ "@types/webxr": "*",+ "@webgpu/types": "*",+ "fflate": "~0.8.2",+ "meshoptimizer": "~0.18.1"+ }+ },+ "node_modules/@types/webxr": {+ "version": "0.5.24",+ "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz",+ "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg=="+ },+ "node_modules/@typescript-eslint/eslint-plugin": {+ "version": "8.67.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.67.0.tgz",+ "integrity": "sha512-Un7Heoyj65NREbKAyIrFxeM143NZpExWmy1Nep4DLeQOeLlTeumPjoNKnBrU5D5moWXbPJgRa5Uwcdu0faVNGQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@eslint-community/regexpp": "^4.12.2",+ "@typescript-eslint/scope-manager": "8.67.0",+ "@typescript-eslint/type-utils": "8.67.0",+ "@typescript-eslint/utils": "8.67.0",+ "@typescript-eslint/visitor-keys": "8.67.0",+ "ignore": "^7.0.5",+ "natural-compare": "^1.4.0",+ "ts-api-utils": "^2.5.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "@typescript-eslint/parser": "^8.67.0",+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.6.tgz",+ "integrity": "sha512-BAg6QkE8W+TuQLrrw0Ugr7HegXduRuuj8/ti2kSOc+jz1dmx8/WNcjr6XGnq5YpDWxFwwaavqD0+jIUOKelTsw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 4"+ }+ },+ "node_modules/@typescript-eslint/parser": {+ "version": "8.67.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.67.0.tgz",+ "integrity": "sha512-fUBfTuuEulWqX6V8+O3PtScV01tzYYRUDTAirHFKoRAt7nOzoGiPt0M/bB47wWNy0coOOcgEwAMUtBpykMxl6w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/scope-manager": "8.67.0",+ "@typescript-eslint/types": "8.67.0",+ "@typescript-eslint/typescript-estree": "8.67.0",+ "@typescript-eslint/visitor-keys": "8.67.0",+ "debug": "^4.4.3"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/project-service": {+ "version": "8.67.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.67.0.tgz",+ "integrity": "sha512-cvE8c7ulYeXN9fYuszhCeCsbzyVEXuhrRCybnBre7TUmqb5nRmBfQAwCj0O3WJFDeyAZt4VYv51vMCC9LHSdYw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/tsconfig-utils": "^8.67.0",+ "@typescript-eslint/types": "^8.67.0",+ "debug": "^4.4.3"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/scope-manager": {+ "version": "8.67.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.67.0.tgz",+ "integrity": "sha512-EgvsleTwS4E+WzzSvem8fAUubLwatMNF1B5hHSLQxcvs7q2dtRhGyujHwLJSYlG41niJ7GP24Aha2+0mb1b2kg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/types": "8.67.0",+ "@typescript-eslint/visitor-keys": "8.67.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ }+ },+ "node_modules/@typescript-eslint/tsconfig-utils": {+ "version": "8.67.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.67.0.tgz",+ "integrity": "sha512-vV+LUSv5njUWsknE71fqKTlXUva+R76SaeORd6Zojcunk/6DvKFXONU3BrAs2H49mbygUXt6gbYunzwqNwlhdg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/type-utils": {+ "version": "8.67.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.67.0.tgz",+ "integrity": "sha512-aVWDXbRmdXO9siTfX4ditQI1T9+zVcNazT48EJCD0v40/9RIFoUgZ05CmGEq9H2gixRpjUn/iplwvlcvutJW/Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/types": "8.67.0",+ "@typescript-eslint/typescript-estree": "8.67.0",+ "@typescript-eslint/utils": "8.67.0",+ "debug": "^4.4.3",+ "ts-api-utils": "^2.5.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/types": {+ "version": "8.67.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.67.0.tgz",+ "integrity": "sha512-sBtgslww8nsMYUjhdPBiSyUqSzT8uR6g93A2QXnQC8+cGdjz0CyaOdqHDRJb1AtORbZCNUJBBeFA/tNR2uQmww==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ }+ },+ "node_modules/@typescript-eslint/typescript-estree": {+ "version": "8.67.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.67.0.tgz",+ "integrity": "sha512-EKQBCE9yNlRJYm7jdTW5AhDacDUmSwQb0FAJAmK2EKYrNXIsa2vxcSZx6PvJ/dEdI6lS+Y9W+EXckLj0iPFGcw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/project-service": "8.67.0",+ "@typescript-eslint/tsconfig-utils": "8.67.0",+ "@typescript-eslint/types": "8.67.0",+ "@typescript-eslint/visitor-keys": "8.67.0",+ "debug": "^4.4.3",+ "minimatch": "^10.2.2",+ "semver": "^7.7.3",+ "tinyglobby": "^0.2.15",+ "ts-api-utils": "^2.5.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": {+ "version": "7.8.5",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@typescript-eslint/utils": {+ "version": "8.67.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.67.0.tgz",+ "integrity": "sha512-U9D1FdwEWBwok3hxxSdhclMb0twvt9QnjIQ0VfQ1AiX2epnpSgv2ubVDsayOFyY8K6FX+AQ7E0FKWVG3iKsj1A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@eslint-community/eslint-utils": "^4.9.1",+ "@typescript-eslint/scope-manager": "8.67.0",+ "@typescript-eslint/types": "8.67.0",+ "@typescript-eslint/typescript-estree": "8.67.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/@typescript-eslint/visitor-keys": {+ "version": "8.67.0",+ "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.67.0.tgz",+ "integrity": "sha512-fkv8dHRDqfGtTHuJeebdrQ7cX6Ad4WAS00rgHh9UGvMycF1mjBfsxry1XsLIFhWZ6Judlh6UdzK+TYlbpCXgnA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/types": "8.67.0",+ "eslint-visitor-keys": "^5.0.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ }+ },+ "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz",+ "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/@use-gesture/core": {+ "version": "10.3.1",+ "resolved": "https://registry.npmjs.org/@use-gesture/core/-/core-10.3.1.tgz",+ "integrity": "sha512-WcINiDt8WjqBdUXye25anHiNxPc0VOrlT8F6LLkU6cycrOGUDyY/yyFmsg3k8i5OLvv25llc0QC45GhR/C8llw=="+ },+ "node_modules/@use-gesture/react": {+ "version": "10.3.1",+ "resolved": "https://registry.npmjs.org/@use-gesture/react/-/react-10.3.1.tgz",+ "integrity": "sha512-Yy19y6O2GJq8f7CHf7L0nxL8bf4PZCPaVOCgJrusOeFHY1LvHgYXnmnXg6N5iwAnbgbZCDjo60SiM6IPJi9C5g==",+ "dependencies": {+ "@use-gesture/core": "10.3.1"+ },+ "peerDependencies": {+ "react": ">= 16.8.0"+ }+ },+ "node_modules/@vitejs/plugin-react": {+ "version": "4.7.0",+ "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz",+ "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==",+ "dev": true,+ "dependencies": {+ "@babel/core": "^7.28.0",+ "@babel/plugin-transform-react-jsx-self": "^7.27.1",+ "@babel/plugin-transform-react-jsx-source": "^7.27.1",+ "@rolldown/pluginutils": "1.0.0-beta.27",+ "@types/babel__core": "^7.20.5",+ "react-refresh": "^0.17.0"+ },+ "engines": {+ "node": "^14.18.0 || >=16.0.0"+ },+ "peerDependencies": {+ "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"+ }+ },+ "node_modules/@webgpu/types": {+ "version": "0.1.69",+ "resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.69.tgz",+ "integrity": "sha512-RPmm6kgRbI8e98zSD3RVACvnuktIja5+yLgDAkTmxLr90BEwdTXRQWNLF3ETTTyH/8mKhznZuN5AveXYFEsMGQ=="+ },+ "node_modules/@xmldom/xmldom": {+ "version": "0.8.14",+ "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.14.tgz",+ "integrity": "sha512-T4EDRUBVZYRldYApjEJiU0e1stYWaRAX7CuSnKzrpwdZKo53zGV8/pqfzV6FfwNl9YThD2OumQYvqtvjvgG7aQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ }+ },+ "node_modules/@xyflow/react": {+ "version": "12.10.2",+ "resolved": "https://registry.npmjs.org/@xyflow/react/-/react-12.10.2.tgz",+ "integrity": "sha512-CgIi6HwlcHXwlkTpr0fxLv/0sRVNZ8IdwKLzzeCscaYBwpvfcH1QFOCeaTCuEn1FQEs/B8CjnTSjhs8udgmBgQ==",+ "license": "MIT",+ "dependencies": {+ "@xyflow/system": "0.0.76",+ "classcat": "^5.0.3",+ "zustand": "^4.4.0"+ },+ "peerDependencies": {+ "react": ">=17",+ "react-dom": ">=17"+ }+ },+ "node_modules/@xyflow/react/node_modules/zustand": {+ "version": "4.5.7",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",+ "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",+ "license": "MIT",+ "dependencies": {+ "use-sync-external-store": "^1.2.2"+ },+ "engines": {+ "node": ">=12.7.0"+ },+ "peerDependencies": {+ "@types/react": ">=16.8",+ "immer": ">=9.0.6",+ "react": ">=16.8"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "immer": {+ "optional": true+ },+ "react": {+ "optional": true+ }+ }+ },+ "node_modules/@xyflow/system": {+ "version": "0.0.76",+ "resolved": "https://registry.npmjs.org/@xyflow/system/-/system-0.0.76.tgz",+ "integrity": "sha512-hvwvnRS1B3REwVDlWexsq7YQaPZeG3/mKo1jv38UmnpWmxihp14bW6VtEOuHEwJX2FvzFw8k77LyKSk/wiZVNA==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-drag": "^3.0.7",+ "@types/d3-interpolate": "^3.0.4",+ "@types/d3-selection": "^3.0.10",+ "@types/d3-transition": "^3.0.8",+ "@types/d3-zoom": "^3.0.8",+ "d3-drag": "^3.0.0",+ "d3-interpolate": "^3.0.1",+ "d3-selection": "^3.0.0",+ "d3-zoom": "^3.0.0"+ }+ },+ "node_modules/abbrev": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-4.0.0.tgz",+ "integrity": "sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==",+ "dev": true,+ "license": "ISC",+ "engines": {+ "node": "^20.17.0 || >=22.9.0"+ }+ },+ "node_modules/acorn": {+ "version": "8.16.0",+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",+ "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",+ "dev": true,+ "bin": {+ "acorn": "bin/acorn"+ },+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/acorn-jsx": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",+ "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",+ "dev": true,+ "peerDependencies": {+ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"+ }+ },+ "node_modules/agent-base": {+ "version": "7.1.4",+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",+ "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 14"+ }+ },+ "node_modules/ajv": {+ "version": "6.14.0",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz",+ "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==",+ "dev": true,+ "dependencies": {+ "fast-deep-equal": "^3.1.1",+ "fast-json-stable-stringify": "^2.0.0",+ "json-schema-traverse": "^0.4.1",+ "uri-js": "^4.2.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/ansi-regex": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/ansi-styles": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",+ "dev": true,+ "dependencies": {+ "color-convert": "^2.0.1"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/any-promise": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz",+ "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==",+ "dev": true+ },+ "node_modules/anymatch": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",+ "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==",+ "dev": true,+ "dependencies": {+ "normalize-path": "^3.0.0",+ "picomatch": "^2.0.4"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/app-builder-lib": {+ "version": "26.15.3",+ "resolved": "https://registry.npmjs.org/app-builder-lib/-/app-builder-lib-26.15.3.tgz",+ "integrity": "sha512-2VnyWkqsP5v5XbBhL3tD5Syx8iNPBYsoU7kY4S2fz7wg8Rj/nztWKCUzGKaFRTv0Xwf3/H058CR1Kvtd/3lRow==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@electron/asar": "3.4.1",+ "@electron/fuses": "^1.8.0",+ "@electron/get": "^3.0.0",+ "@electron/notarize": "2.5.0",+ "@electron/osx-sign": "1.3.3",+ "@electron/rebuild": "^4.0.4",+ "@electron/universal": "2.0.3",+ "@malept/flatpak-bundler": "^0.4.0",+ "@noble/hashes": "^2.2.0",+ "@peculiar/webcrypto": "^1.7.1",+ "@types/fs-extra": "9.0.13",+ "ajv": "^8.18.0",+ "asn1js": "^3.0.10",+ "async-exit-hook": "^2.0.1",+ "builder-util": "26.15.3",+ "builder-util-runtime": "9.7.0",+ "chromium-pickle-js": "^0.2.0",+ "ci-info": "4.3.1",+ "debug": "^4.3.4",+ "dotenv": "^16.4.5",+ "dotenv-expand": "^11.0.6",+ "ejs": "^3.1.8",+ "electron-publish": "26.15.3",+ "fs-extra": "^10.1.0",+ "hosted-git-info": "^4.1.0",+ "isbinaryfile": "^5.0.0",+ "jiti": "^2.4.2",+ "js-yaml": "^4.1.0",+ "json5": "^2.2.3",+ "lazy-val": "^1.0.5",+ "minimatch": "^10.2.5",+ "pkijs": "^3.4.0",+ "plist": "3.1.0",+ "proper-lockfile": "^4.1.2",+ "resedit": "^1.7.0",+ "semver": "~7.7.3",+ "tar": "^7.5.7",+ "temp-file": "^3.4.0",+ "tiny-async-pool": "1.3.0",+ "unzipper": "^0.12.3",+ "which": "^5.0.0"+ },+ "engines": {+ "node": ">=14.0.0"+ },+ "peerDependencies": {+ "dmg-builder": "26.15.3",+ "electron-builder-squirrel-windows": "26.15.3"+ }+ },+ "node_modules/app-builder-lib/node_modules/@electron/get": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/@electron/get/-/get-3.1.0.tgz",+ "integrity": "sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "debug": "^4.1.1",+ "env-paths": "^2.2.0",+ "fs-extra": "^8.1.0",+ "got": "^11.8.5",+ "progress": "^2.0.3",+ "semver": "^6.2.0",+ "sumchecker": "^3.0.1"+ },+ "engines": {+ "node": ">=14"+ },+ "optionalDependencies": {+ "global-agent": "^3.0.0"+ }+ },+ "node_modules/app-builder-lib/node_modules/@electron/get/node_modules/fs-extra": {+ "version": "8.1.0",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",+ "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.2.0",+ "jsonfile": "^4.0.0",+ "universalify": "^0.1.0"+ },+ "engines": {+ "node": ">=6 <7 || >=8"+ }+ },+ "node_modules/app-builder-lib/node_modules/@electron/get/node_modules/semver": {+ "version": "6.3.1",+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ }+ },+ "node_modules/app-builder-lib/node_modules/ajv": {+ "version": "8.20.0",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",+ "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "fast-uri": "^3.0.1",+ "json-schema-traverse": "^1.0.0",+ "require-from-string": "^2.0.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/app-builder-lib/node_modules/ci-info": {+ "version": "4.3.1",+ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.3.1.tgz",+ "integrity": "sha512-Wdy2Igu8OcBpI2pZePZ5oWjPC38tmDVx5WKUXKwlLYkA0ozo85sLsLvkBbBn/sZaSCMFOGZJ14fvW9t5/d7kdA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/sibiraj-s"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/app-builder-lib/node_modules/env-paths": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz",+ "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/app-builder-lib/node_modules/isexe": {+ "version": "3.1.5",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz",+ "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==",+ "dev": true,+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/app-builder-lib/node_modules/jiti": {+ "version": "2.7.0",+ "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",+ "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "jiti": "lib/jiti-cli.mjs"+ }+ },+ "node_modules/app-builder-lib/node_modules/json-schema-traverse": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/app-builder-lib/node_modules/jsonfile": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",+ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",+ "dev": true,+ "license": "MIT",+ "optionalDependencies": {+ "graceful-fs": "^4.1.6"+ }+ },+ "node_modules/app-builder-lib/node_modules/semver": {+ "version": "7.7.4",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/app-builder-lib/node_modules/universalify": {+ "version": "0.1.2",+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",+ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 4.0.0"+ }+ },+ "node_modules/app-builder-lib/node_modules/which": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz",+ "integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "isexe": "^3.1.1"+ },+ "bin": {+ "node-which": "bin/which.js"+ },+ "engines": {+ "node": "^18.17.0 || >=20.5.0"+ }+ },+ "node_modules/arg": {+ "version": "5.0.2",+ "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz",+ "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==",+ "dev": true+ },+ "node_modules/argparse": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",+ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="+ },+ "node_modules/asn1js": {+ "version": "3.0.10",+ "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.10.tgz",+ "integrity": "sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "pvtsutils": "^1.3.6",+ "pvutils": "^1.1.5",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=12.0.0"+ }+ },+ "node_modules/async": {+ "version": "3.2.6",+ "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz",+ "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/async-exit-hook": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/async-exit-hook/-/async-exit-hook-2.0.1.tgz",+ "integrity": "sha512-NW2cX8m1Q7KPA7a5M2ULQeZ2wR5qI5PAbw5L0UOMxdioVk9PMZ0h1TmyZEkPYrCvYjDlFICusOu1dlEKAAeXBw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.12.0"+ }+ },+ "node_modules/asynckit": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="+ },+ "node_modules/at-least-node": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz",+ "integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==",+ "dev": true,+ "license": "ISC",+ "engines": {+ "node": ">= 4.0.0"+ }+ },+ "node_modules/autoprefixer": {+ "version": "10.4.24",+ "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.24.tgz",+ "integrity": "sha512-uHZg7N9ULTVbutaIsDRoUkoS8/h3bdsmVJYZ5l3wv8Cp/6UIIoRDm90hZ+BwxUj/hGBEzLxdHNSKuFpn8WOyZw==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/autoprefixer"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "dependencies": {+ "browserslist": "^4.28.1",+ "caniuse-lite": "^1.0.30001766",+ "fraction.js": "^5.3.4",+ "picocolors": "^1.1.1",+ "postcss-value-parser": "^4.2.0"+ },+ "bin": {+ "autoprefixer": "bin/autoprefixer"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ },+ "peerDependencies": {+ "postcss": "^8.1.0"+ }+ },+ "node_modules/aws4": {+ "version": "1.13.2",+ "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.13.2.tgz",+ "integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/axios": {+ "version": "1.19.0",+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.19.0.tgz",+ "integrity": "sha512-ht/iuYZXEjFxLH/Hkezgd7m6JKlHHXEUSneaDz8uZe1Gj5QZtCnpyDsckvAiEnT89OEbCLmnte4R4sn7P0EKFw==",+ "license": "MIT",+ "dependencies": {+ "follow-redirects": "^1.16.0",+ "form-data": "^4.0.6",+ "https-proxy-agent": "^5.0.1",+ "proxy-from-env": "^2.1.0"+ }+ },+ "node_modules/axios/node_modules/agent-base": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",+ "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "4"+ },+ "engines": {+ "node": ">= 6.0.0"+ }+ },+ "node_modules/axios/node_modules/https-proxy-agent": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",+ "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",+ "license": "MIT",+ "dependencies": {+ "agent-base": "6",+ "debug": "4"+ },+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/balanced-match": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/base64-js": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ]+ },+ "node_modules/baseline-browser-mapping": {+ "version": "2.10.0",+ "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.0.tgz",+ "integrity": "sha512-lIyg0szRfYbiy67j9KN8IyeD7q7hcmqnJ1ddWmNt19ItGpNN64mnllmxUNFIOdOm6by97jlL6wfpTTJrmnjWAA==",+ "dev": true,+ "bin": {+ "baseline-browser-mapping": "dist/cli.cjs"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/bidi-js": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz",+ "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==",+ "dependencies": {+ "require-from-string": "^2.0.2"+ }+ },+ "node_modules/binary-extensions": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",+ "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==",+ "dev": true,+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/bluebird": {+ "version": "3.7.2",+ "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz",+ "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/boolean": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz",+ "integrity": "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==",+ "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.",+ "dev": true,+ "license": "MIT",+ "optional": true+ },+ "node_modules/brace-expansion": {+ "version": "5.0.9",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",+ "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^4.0.2"+ },+ "engines": {+ "node": "20 || >=22"+ }+ },+ "node_modules/brace-expansion/node_modules/balanced-match": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",+ "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "18 || 20 || >=22"+ }+ },+ "node_modules/braces": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",+ "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",+ "dev": true,+ "dependencies": {+ "fill-range": "^7.1.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/browserslist": {+ "version": "4.28.1",+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz",+ "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/browserslist"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/browserslist"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "dependencies": {+ "baseline-browser-mapping": "^2.9.0",+ "caniuse-lite": "^1.0.30001759",+ "electron-to-chromium": "^1.5.263",+ "node-releases": "^2.0.27",+ "update-browserslist-db": "^1.2.0"+ },+ "bin": {+ "browserslist": "cli.js"+ },+ "engines": {+ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"+ }+ },+ "node_modules/buffer": {+ "version": "6.0.3",+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",+ "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "dependencies": {+ "base64-js": "^1.3.1",+ "ieee754": "^1.2.1"+ }+ },+ "node_modules/buffer-from": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",+ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/builder-util": {+ "version": "26.15.3",+ "resolved": "https://registry.npmjs.org/builder-util/-/builder-util-26.15.3.tgz",+ "integrity": "sha512-q2hn7Mbo2nFNkVekPiHFx6Nfo3hURmES3tfBn+k5Pqxl2RkmP3QGqZUhH/q9Pch/4G05NRhPjDlVj1O8q4Txvw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/debug": "^4.1.6",+ "builder-util-runtime": "9.7.0",+ "chalk": "^4.1.2",+ "cross-spawn": "^7.0.6",+ "debug": "^4.3.4",+ "fs-extra": "^10.1.0",+ "http-proxy-agent": "^7.0.0",+ "https-proxy-agent": "^7.0.0",+ "js-yaml": "^4.1.0",+ "sanitize-filename": "^1.6.3",+ "source-map-support": "^0.5.19",+ "stat-mode": "^1.0.0",+ "temp-file": "^3.4.0",+ "tiny-async-pool": "1.3.0"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/builder-util-runtime": {+ "version": "9.7.0",+ "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.7.0.tgz",+ "integrity": "sha512-g/kR520giAFYkSXTzcmF3kqQq7wi8F6N6SzeDgZrqTBN+VHdmgWOyTdD1yD7AATDId/yXLvuP34CxW46/BwCdw==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.3.4",+ "sax": "^1.2.4"+ },+ "engines": {+ "node": ">=12.0.0"+ }+ },+ "node_modules/bytestreamjs": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/bytestreamjs/-/bytestreamjs-2.0.1.tgz",+ "integrity": "sha512-U1Z/ob71V/bXfVABvNr/Kumf5VyeQRBEm6Txb0PQ6S7V5GpBM3w4Cbqz/xPDicR5tN0uvDifng8C+5qECeGwyQ==",+ "dev": true,+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/cac": {+ "version": "6.7.14",+ "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",+ "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==",+ "dev": true,+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/cacheable-lookup": {+ "version": "5.0.4",+ "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz",+ "integrity": "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10.6.0"+ }+ },+ "node_modules/cacheable-request": {+ "version": "7.0.4",+ "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.4.tgz",+ "integrity": "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "clone-response": "^1.0.2",+ "get-stream": "^5.1.0",+ "http-cache-semantics": "^4.0.0",+ "keyv": "^4.0.0",+ "lowercase-keys": "^2.0.0",+ "normalize-url": "^6.0.1",+ "responselike": "^2.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "dependencies": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/callsites": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",+ "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==",+ "dev": true,+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/camelcase-css": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz",+ "integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==",+ "dev": true,+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/camera-controls": {+ "version": "2.10.1",+ "resolved": "https://registry.npmjs.org/camera-controls/-/camera-controls-2.10.1.tgz",+ "integrity": "sha512-KnaKdcvkBJ1Irbrzl8XD6WtZltkRjp869Jx8c0ujs9K+9WD+1D7ryBsCiVqJYUqt6i/HR5FxT7RLASieUD+Q5w==",+ "peerDependencies": {+ "three": ">=0.126.1"+ }+ },+ "node_modules/caniuse-lite": {+ "version": "1.0.30001774",+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001774.tgz",+ "integrity": "sha512-DDdwPGz99nmIEv216hKSgLD+D4ikHQHjBC/seF98N9CPqRX4M5mSxT9eTV6oyisnJcuzxtZy4n17yKKQYmYQOA==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/browserslist"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/caniuse-lite"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ]+ },+ "node_modules/chalk": {+ "version": "4.1.2",+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",+ "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",+ "dev": true,+ "dependencies": {+ "ansi-styles": "^4.1.0",+ "supports-color": "^7.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/chalk?sponsor=1"+ }+ },+ "node_modules/chokidar": {+ "version": "3.6.0",+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",+ "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",+ "dev": true,+ "dependencies": {+ "anymatch": "~3.1.2",+ "braces": "~3.0.2",+ "glob-parent": "~5.1.2",+ "is-binary-path": "~2.1.0",+ "is-glob": "~4.0.1",+ "normalize-path": "~3.0.0",+ "readdirp": "~3.6.0"+ },+ "engines": {+ "node": ">= 8.10.0"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.2"+ }+ },+ "node_modules/chokidar/node_modules/glob-parent": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",+ "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",+ "dev": true,+ "dependencies": {+ "is-glob": "^4.0.1"+ },+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/chromium-pickle-js": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/chromium-pickle-js/-/chromium-pickle-js-0.2.0.tgz",+ "integrity": "sha512-1R5Fho+jBq0DDydt+/vHWj5KJNJCKdARKOCwZUen84I5BreWoLqRLANH1U87eJy1tiASPtMnGqJJq0ZsLoRPOw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/ci-info": {+ "version": "4.4.0",+ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz",+ "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/sibiraj-s"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/classcat": {+ "version": "5.0.5",+ "resolved": "https://registry.npmjs.org/classcat/-/classcat-5.0.5.tgz",+ "integrity": "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==",+ "license": "MIT"+ },+ "node_modules/cliui": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",+ "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "string-width": "^4.2.0",+ "strip-ansi": "^6.0.1",+ "wrap-ansi": "^7.0.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/clone-response": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.3.tgz",+ "integrity": "sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "mimic-response": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/color-convert": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",+ "dev": true,+ "dependencies": {+ "color-name": "~1.1.4"+ },+ "engines": {+ "node": ">=7.0.0"+ }+ },+ "node_modules/color-name": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",+ "dev": true+ },+ "node_modules/combined-stream": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",+ "dependencies": {+ "delayed-stream": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/commander": {+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/commander/-/commander-5.1.0.tgz",+ "integrity": "sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/compare-version": {+ "version": "0.1.2",+ "resolved": "https://registry.npmjs.org/compare-version/-/compare-version-0.1.2.tgz",+ "integrity": "sha512-pJDh5/4wrEnXX/VWRZvruAGHkzKdr46z11OlTPN+VrATlWWhSKewNCJ1futCO5C7eJB3nPMFZA1LeYtcFboZ2A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/concat-map": {+ "version": "0.0.1",+ "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",+ "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",+ "dev": true+ },+ "node_modules/convert-source-map": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",+ "dev": true+ },+ "node_modules/core-util-is": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",+ "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/cross-dirname": {+ "version": "0.1.0",+ "resolved": "https://registry.npmjs.org/cross-dirname/-/cross-dirname-0.1.0.tgz",+ "integrity": "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "peer": true+ },+ "node_modules/cross-env": {+ "version": "10.1.0",+ "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-10.1.0.tgz",+ "integrity": "sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@epic-web/invariant": "^1.0.0",+ "cross-spawn": "^7.0.6"+ },+ "bin": {+ "cross-env": "dist/bin/cross-env.js",+ "cross-env-shell": "dist/bin/cross-env-shell.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/css-tree": {+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz",+ "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "mdn-data": "2.27.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0"+ }+ },+ "node_modules/cssesc": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz",+ "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==",+ "dev": true,+ "bin": {+ "cssesc": "bin/cssesc"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/csstype": {+ "version": "3.2.3",+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="+ },+ "node_modules/d3-color": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",+ "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-dispatch": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",+ "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-drag": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz",+ "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-selection": "3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-ease": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",+ "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-interpolate": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",+ "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",+ "license": "ISC",+ "dependencies": {+ "d3-color": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-selection": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",+ "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-timer": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",+ "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-transition": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz",+ "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==",+ "license": "ISC",+ "dependencies": {+ "d3-color": "1 - 3",+ "d3-dispatch": "1 - 3",+ "d3-ease": "1 - 3",+ "d3-interpolate": "1 - 3",+ "d3-timer": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ },+ "peerDependencies": {+ "d3-selection": "2 - 3"+ }+ },+ "node_modules/d3-zoom": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz",+ "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-drag": "2 - 3",+ "d3-interpolate": "1 - 3",+ "d3-selection": "2 - 3",+ "d3-transition": "2 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/data-urls": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz",+ "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "whatwg-mimetype": "^5.0.0",+ "whatwg-url": "^16.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/decimal.js": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",+ "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/decompress-response": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",+ "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "mimic-response": "^3.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/decompress-response/node_modules/mimic-response": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",+ "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/deep-is": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",+ "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==",+ "dev": true+ },+ "node_modules/defer-to-connect": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.1.tgz",+ "integrity": "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/define-data-property": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz",+ "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "es-define-property": "^1.0.0",+ "es-errors": "^1.3.0",+ "gopd": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/define-properties": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz",+ "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "define-data-property": "^1.0.1",+ "has-property-descriptors": "^1.0.0",+ "object-keys": "^1.1.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/delayed-stream": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/detect-gpu": {+ "version": "5.0.70",+ "resolved": "https://registry.npmjs.org/detect-gpu/-/detect-gpu-5.0.70.tgz",+ "integrity": "sha512-bqerEP1Ese6nt3rFkwPnGbsUF9a4q+gMmpTVVOEzoCyeCc+y7/RvJnQZJx1JwhgQI5Ntg0Kgat8Uu7XpBqnz1w==",+ "dependencies": {+ "webgl-constants": "^1.1.1"+ }+ },+ "node_modules/detect-node": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz",+ "integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==",+ "dev": true,+ "license": "MIT",+ "optional": true+ },+ "node_modules/didyoumean": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz",+ "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==",+ "dev": true+ },+ "node_modules/dir-compare": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/dir-compare/-/dir-compare-4.2.0.tgz",+ "integrity": "sha512-2xMCmOoMrdQIPHdsTawECdNPwlVFB9zGcz3kuhmBO6U3oU+UQjsue0i8ayLKpgBcm+hcXPMVSGUN9d+pvJ6+VQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "minimatch": "^3.0.5",+ "p-limit": "^3.1.0 "+ }+ },+ "node_modules/dir-compare/node_modules/brace-expansion": {+ "version": "1.1.18",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",+ "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0",+ "concat-map": "0.0.1"+ }+ },+ "node_modules/dir-compare/node_modules/minimatch": {+ "version": "3.1.5",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^1.1.7"+ },+ "engines": {+ "node": "*"+ }+ },+ "node_modules/dlv": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz",+ "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==",+ "dev": true+ },+ "node_modules/dmg-builder": {+ "version": "26.15.3",+ "resolved": "https://registry.npmjs.org/dmg-builder/-/dmg-builder-26.15.3.tgz",+ "integrity": "sha512-O3zJUFUYHJKgzPqioHxfxzBzlSC1eXCSr79gMSBKBP5AgjjpmrydMsMLotEg9fAJF36vdUncb+4ndRNxoPdlSQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "app-builder-lib": "26.15.3",+ "builder-util": "26.15.3",+ "fs-extra": "^10.1.0",+ "js-yaml": "^4.1.0"+ }+ },+ "node_modules/dotenv": {+ "version": "16.6.1",+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",+ "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://dotenvx.com"+ }+ },+ "node_modules/dotenv-expand": {+ "version": "11.0.7",+ "resolved": "https://registry.npmjs.org/dotenv-expand/-/dotenv-expand-11.0.7.tgz",+ "integrity": "sha512-zIHwmZPRshsCdpMDyVsqGmgyP0yT8GAgXUnkdAoJisxvf33k7yO6OuoKmcTGuXPWSsm8Oh88nZicRLA9Y0rUeA==",+ "dev": true,+ "license": "BSD-2-Clause",+ "dependencies": {+ "dotenv": "^16.4.5"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://dotenvx.com"+ }+ },+ "node_modules/draco3d": {+ "version": "1.5.7",+ "resolved": "https://registry.npmjs.org/draco3d/-/draco3d-1.5.7.tgz",+ "integrity": "sha512-m6WCKt/erDXcw+70IJXnG7M3awwQPAsZvJGX5zY7beBqpELw6RDGkYVU0W43AFxye4pDZ5i2Lbyc/NNGqwjUVQ=="+ },+ "node_modules/dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/duplexer2": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz",+ "integrity": "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "readable-stream": "^2.0.2"+ }+ },+ "node_modules/ejs": {+ "version": "3.1.10",+ "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz",+ "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "jake": "^10.8.5"+ },+ "bin": {+ "ejs": "bin/cli.js"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/electron": {+ "version": "42.11.1",+ "resolved": "https://registry.npmjs.org/electron/-/electron-42.11.1.tgz",+ "integrity": "sha512-mRYYjGDRWCyU+h4FU/0ruqxL/rXc+h2VCLhTb19KHu18HCUFWQAeFS/mFwnEKT/7GQCwlIHOhHie5ICLPXW6aw==",+ "license": "MIT",+ "dependencies": {+ "@electron-internal/extract-zip": "^1.0.1",+ "@electron/get": "^5.0.0",+ "@types/node": "^24.9.0"+ },+ "bin": {+ "electron": "cli.js",+ "install-electron": "install.js"+ },+ "engines": {+ "node": ">= 22.12.0"+ }+ },+ "node_modules/electron-builder": {+ "version": "26.15.3",+ "resolved": "https://registry.npmjs.org/electron-builder/-/electron-builder-26.15.3.tgz",+ "integrity": "sha512-a1KM5heqS3gQCZzizXEI8RjJy3QVogULPdeSknt76uLDpBIW/HDGsMg/XgP0riP6PI9COsRvFITKKGDqA8fJxA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "app-builder-lib": "26.15.3",+ "builder-util": "26.15.3",+ "builder-util-runtime": "9.7.0",+ "chalk": "^4.1.2",+ "ci-info": "^4.2.0",+ "dmg-builder": "26.15.3",+ "fs-extra": "^10.1.0",+ "lazy-val": "^1.0.5",+ "simple-update-notifier": "2.0.0",+ "yargs": "^17.6.2"+ },+ "bin": {+ "electron-builder": "cli.js",+ "install-app-deps": "install-app-deps.js"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/electron-builder-squirrel-windows": {+ "version": "26.15.3",+ "resolved": "https://registry.npmjs.org/electron-builder-squirrel-windows/-/electron-builder-squirrel-windows-26.15.3.tgz",+ "integrity": "sha512-Jc19XPV9y9+2bAdZPkXuVNGNIEFBq9poHC61l8Kv6FdK7DRG3+Ic0rerC0DXOaeHNz8yW0fg/JnF8GQROOF5MA==",+ "dev": true,+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "app-builder-lib": "26.15.3",+ "builder-util": "26.15.3",+ "electron-winstaller": "5.4.0"+ }+ },+ "node_modules/electron-publish": {+ "version": "26.15.3",+ "resolved": "https://registry.npmjs.org/electron-publish/-/electron-publish-26.15.3.tgz",+ "integrity": "sha512-g/2bn8YTavY4cuS5F+jOS7zmZbXXBV8KZ8yHKfJjFPoKtzBqrpCdNPxBd3tqdBwP7BVd0lGzf7Bk2s0KesWZ4Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/fs-extra": "^9.0.11",+ "aws4": "^1.13.2",+ "builder-util": "26.15.3",+ "builder-util-runtime": "9.7.0",+ "chalk": "^4.1.2",+ "form-data": "^4.0.5",+ "fs-extra": "^10.1.0",+ "lazy-val": "^1.0.5",+ "mime": "^2.5.2"+ }+ },+ "node_modules/electron-to-chromium": {+ "version": "1.5.302",+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.302.tgz",+ "integrity": "sha512-sM6HAN2LyK82IyPBpznDRqlTQAtuSaO+ShzFiWTvoMJLHyZ+Y39r8VMfHzwbU8MVBzQ4Wdn85+wlZl2TLGIlwg==",+ "dev": true+ },+ "node_modules/electron-updater": {+ "version": "6.8.9",+ "resolved": "https://registry.npmjs.org/electron-updater/-/electron-updater-6.8.9.tgz",+ "integrity": "sha512-ZhVxM9iGONUpZGI1FxdMRgJjUFXi7AYGVa5PwKlO1tV1/4zDxQmfKpXOHVztKrd6L9rLcFjERvi1Mf2vxyTkig==",+ "license": "MIT",+ "dependencies": {+ "builder-util-runtime": "9.7.0",+ "fs-extra": "^10.1.0",+ "js-yaml": "^4.1.0",+ "lazy-val": "^1.0.5",+ "lodash.escaperegexp": "^4.1.2",+ "lodash.isequal": "^4.5.0",+ "semver": "~7.7.3",+ "tiny-typed-emitter": "^2.1.0"+ }+ },+ "node_modules/electron-updater/node_modules/semver": {+ "version": "7.7.4",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/electron-vite": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/electron-vite/-/electron-vite-5.0.0.tgz",+ "integrity": "sha512-OHp/vjdlubNlhNkPkL/+3JD34ii5ov7M0GpuXEVdQeqdQ3ulvVR7Dg/rNBLfS5XPIFwgoBLDf9sjjrL+CuDyRQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/core": "^7.28.4",+ "@babel/plugin-transform-arrow-functions": "^7.27.1",+ "cac": "^6.7.14",+ "esbuild": "^0.25.11",+ "magic-string": "^0.30.19",+ "picocolors": "^1.1.1"+ },+ "bin": {+ "electron-vite": "bin/electron-vite.js"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "peerDependencies": {+ "@swc/core": "^1.0.0",+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0"+ },+ "peerDependenciesMeta": {+ "@swc/core": {+ "optional": true+ }+ }+ },+ "node_modules/electron-winstaller": {+ "version": "5.4.0",+ "resolved": "https://registry.npmjs.org/electron-winstaller/-/electron-winstaller-5.4.0.tgz",+ "integrity": "sha512-bO3y10YikuUwUuDUQRM4KfwNkKhnpVO7IPdbsrejwN9/AABJzzTQ4GeHwyzNSrVO+tEH3/Np255a3sVZpZDjvg==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@electron/asar": "^3.2.1",+ "debug": "^4.1.1",+ "fs-extra": "^7.0.1",+ "lodash": "^4.17.21",+ "temp": "^0.9.0"+ },+ "engines": {+ "node": ">=8.0.0"+ },+ "optionalDependencies": {+ "@electron/windows-sign": "^1.1.2"+ }+ },+ "node_modules/electron-winstaller/node_modules/fs-extra": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-7.0.1.tgz",+ "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==",+ "dev": true,+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "graceful-fs": "^4.1.2",+ "jsonfile": "^4.0.0",+ "universalify": "^0.1.0"+ },+ "engines": {+ "node": ">=6 <7 || >=8"+ }+ },+ "node_modules/electron-winstaller/node_modules/jsonfile": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",+ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",+ "dev": true,+ "license": "MIT",+ "peer": true,+ "optionalDependencies": {+ "graceful-fs": "^4.1.6"+ }+ },+ "node_modules/electron-winstaller/node_modules/universalify": {+ "version": "0.1.2",+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",+ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",+ "dev": true,+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">= 4.0.0"+ }+ },+ "node_modules/electron/node_modules/@types/node": {+ "version": "24.13.3",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz",+ "integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==",+ "license": "MIT",+ "dependencies": {+ "undici-types": "~7.18.0"+ }+ },+ "node_modules/electron/node_modules/undici-types": {+ "version": "7.18.2",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",+ "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",+ "license": "MIT"+ },+ "node_modules/emoji-regex": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/end-of-stream": {+ "version": "1.4.5",+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",+ "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "once": "^1.4.0"+ }+ },+ "node_modules/entities": {+ "version": "8.1.0",+ "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz",+ "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=20.19.0"+ },+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },+ "node_modules/env-paths": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz",+ "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==",+ "license": "MIT",+ "engines": {+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/err-code": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/err-code/-/err-code-2.0.3.tgz",+ "integrity": "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-object-atoms": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",+ "dependencies": {+ "es-errors": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-set-tostringtag": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",+ "dependencies": {+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.6",+ "has-tostringtag": "^1.0.2",+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es6-error": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz",+ "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==",+ "dev": true,+ "license": "MIT",+ "optional": true+ },+ "node_modules/esbuild": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",+ "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.28.2",+ "@esbuild/android-arm": "0.28.2",+ "@esbuild/android-arm64": "0.28.2",+ "@esbuild/android-x64": "0.28.2",+ "@esbuild/darwin-arm64": "0.28.2",+ "@esbuild/darwin-x64": "0.28.2",+ "@esbuild/freebsd-arm64": "0.28.2",+ "@esbuild/freebsd-x64": "0.28.2",+ "@esbuild/linux-arm": "0.28.2",+ "@esbuild/linux-arm64": "0.28.2",+ "@esbuild/linux-ia32": "0.28.2",+ "@esbuild/linux-loong64": "0.28.2",+ "@esbuild/linux-mips64el": "0.28.2",+ "@esbuild/linux-ppc64": "0.28.2",+ "@esbuild/linux-riscv64": "0.28.2",+ "@esbuild/linux-s390x": "0.28.2",+ "@esbuild/linux-x64": "0.28.2",+ "@esbuild/netbsd-arm64": "0.28.2",+ "@esbuild/netbsd-x64": "0.28.2",+ "@esbuild/openbsd-arm64": "0.28.2",+ "@esbuild/openbsd-x64": "0.28.2",+ "@esbuild/openharmony-arm64": "0.28.2",+ "@esbuild/sunos-x64": "0.28.2",+ "@esbuild/win32-arm64": "0.28.2",+ "@esbuild/win32-ia32": "0.28.2",+ "@esbuild/win32-x64": "0.28.2"+ }+ },+ "node_modules/escalade": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",+ "dev": true,+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/escape-string-regexp": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",+ "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",+ "dev": true,+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/eslint": {+ "version": "9.39.3",+ "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.3.tgz",+ "integrity": "sha512-VmQ+sifHUbI/IcSopBCF/HO3YiHQx/AVd3UVyYL6weuwW+HvON9VYn5l6Zl1WZzPWXPNZrSQpxwkkZ/VuvJZzg==",+ "dev": true,+ "dependencies": {+ "@eslint-community/eslint-utils": "^4.8.0",+ "@eslint-community/regexpp": "^4.12.1",+ "@eslint/config-array": "^0.21.1",+ "@eslint/config-helpers": "^0.4.2",+ "@eslint/core": "^0.17.0",+ "@eslint/eslintrc": "^3.3.1",+ "@eslint/js": "9.39.3",+ "@eslint/plugin-kit": "^0.4.1",+ "@humanfs/node": "^0.16.6",+ "@humanwhocodes/module-importer": "^1.0.1",+ "@humanwhocodes/retry": "^0.4.2",+ "@types/estree": "^1.0.6",+ "ajv": "^6.12.4",+ "chalk": "^4.0.0",+ "cross-spawn": "^7.0.6",+ "debug": "^4.3.2",+ "escape-string-regexp": "^4.0.0",+ "eslint-scope": "^8.4.0",+ "eslint-visitor-keys": "^4.2.1",+ "espree": "^10.4.0",+ "esquery": "^1.5.0",+ "esutils": "^2.0.2",+ "fast-deep-equal": "^3.1.3",+ "file-entry-cache": "^8.0.0",+ "find-up": "^5.0.0",+ "glob-parent": "^6.0.2",+ "ignore": "^5.2.0",+ "imurmurhash": "^0.1.4",+ "is-glob": "^4.0.0",+ "json-stable-stringify-without-jsonify": "^1.0.1",+ "lodash.merge": "^4.6.2",+ "minimatch": "^3.1.2",+ "natural-compare": "^1.4.0",+ "optionator": "^0.9.3"+ },+ "bin": {+ "eslint": "bin/eslint.js"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://eslint.org/donate"+ },+ "peerDependencies": {+ "jiti": "*"+ },+ "peerDependenciesMeta": {+ "jiti": {+ "optional": true+ }+ }+ },+ "node_modules/eslint-plugin-react-hooks": {+ "version": "7.1.1",+ "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.1.1.tgz",+ "integrity": "sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@babel/core": "^7.24.4",+ "@babel/parser": "^7.24.4",+ "hermes-parser": "^0.25.1",+ "zod": "^3.25.0 || ^4.0.0",+ "zod-validation-error": "^3.5.0 || ^4.0.0"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0"+ }+ },+ "node_modules/eslint-scope": {+ "version": "8.4.0",+ "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz",+ "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==",+ "dev": true,+ "dependencies": {+ "esrecurse": "^4.3.0",+ "estraverse": "^5.2.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/eslint-visitor-keys": {+ "version": "4.2.1",+ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz",+ "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==",+ "dev": true,+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/eslint/node_modules/@eslint/js": {+ "version": "9.39.3",+ "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.3.tgz",+ "integrity": "sha512-1B1VkCq6FuUNlQvlBYb+1jDu/gV297TIs/OeiaSR9l1H27SVW55ONE1e1Vp16NqP683+xEGzxYtv4XCiDPaQiw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://eslint.org/donate"+ }+ },+ "node_modules/eslint/node_modules/brace-expansion": {+ "version": "1.1.18",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",+ "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0",+ "concat-map": "0.0.1"+ }+ },+ "node_modules/eslint/node_modules/minimatch": {+ "version": "3.1.5",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^1.1.7"+ },+ "engines": {+ "node": "*"+ }+ },+ "node_modules/espree": {+ "version": "10.4.0",+ "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz",+ "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==",+ "dev": true,+ "dependencies": {+ "acorn": "^8.15.0",+ "acorn-jsx": "^5.3.2",+ "eslint-visitor-keys": "^4.2.1"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/eslint"+ }+ },+ "node_modules/esquery": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz",+ "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==",+ "dev": true,+ "dependencies": {+ "estraverse": "^5.1.0"+ },+ "engines": {+ "node": ">=0.10"+ }+ },+ "node_modules/esrecurse": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz",+ "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==",+ "dev": true,+ "dependencies": {+ "estraverse": "^5.2.0"+ },+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/estraverse": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",+ "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",+ "dev": true,+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/esutils": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",+ "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",+ "dev": true,+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/exponential-backoff": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz",+ "integrity": "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==",+ "dev": true,+ "license": "Apache-2.0"+ },+ "node_modules/fast-deep-equal": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",+ "dev": true+ },+ "node_modules/fast-glob": {+ "version": "3.3.3",+ "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",+ "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==",+ "dev": true,+ "dependencies": {+ "@nodelib/fs.stat": "^2.0.2",+ "@nodelib/fs.walk": "^1.2.3",+ "glob-parent": "^5.1.2",+ "merge2": "^1.3.0",+ "micromatch": "^4.0.8"+ },+ "engines": {+ "node": ">=8.6.0"+ }+ },+ "node_modules/fast-glob/node_modules/glob-parent": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",+ "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",+ "dev": true,+ "dependencies": {+ "is-glob": "^4.0.1"+ },+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/fast-json-stable-stringify": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",+ "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",+ "dev": true+ },+ "node_modules/fast-levenshtein": {+ "version": "2.0.6",+ "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz",+ "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==",+ "dev": true+ },+ "node_modules/fast-uri": {+ "version": "3.1.5",+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz",+ "integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fastify"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fastify"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/fastq": {+ "version": "1.20.1",+ "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz",+ "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==",+ "dev": true,+ "dependencies": {+ "reusify": "^1.0.4"+ }+ },+ "node_modules/fflate": {+ "version": "0.8.2",+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz",+ "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A=="+ },+ "node_modules/file-entry-cache": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",+ "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==",+ "dev": true,+ "dependencies": {+ "flat-cache": "^4.0.0"+ },+ "engines": {+ "node": ">=16.0.0"+ }+ },+ "node_modules/filelist": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.6.tgz",+ "integrity": "sha512-5giy2PkLYY1cP39p17Ech+2xlpTRL9HLspOfEgm0L6CwBXBTgsK5ou0JtzYuepxkaQ/tvhCFIJ5uXo0OrM2DxA==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "minimatch": "^5.0.1"+ }+ },+ "node_modules/filelist/node_modules/brace-expansion": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",+ "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0"+ }+ },+ "node_modules/filelist/node_modules/minimatch": {+ "version": "5.1.9",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz",+ "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^2.0.1"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/fill-range": {+ "version": "7.1.1",+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",+ "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",+ "dev": true,+ "dependencies": {+ "to-regex-range": "^5.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/find-up": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",+ "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==",+ "dev": true,+ "dependencies": {+ "locate-path": "^6.0.0",+ "path-exists": "^4.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/flat-cache": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz",+ "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==",+ "dev": true,+ "dependencies": {+ "flatted": "^3.2.9",+ "keyv": "^4.5.4"+ },+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/flatted": {+ "version": "3.4.4",+ "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz",+ "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/follow-redirects": {+ "version": "1.16.0",+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz",+ "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==",+ "funding": [+ {+ "type": "individual",+ "url": "https://github.com/sponsors/RubenVerborgh"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=4.0"+ },+ "peerDependenciesMeta": {+ "debug": {+ "optional": true+ }+ }+ },+ "node_modules/form-data": {+ "version": "4.0.6",+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",+ "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==",+ "license": "MIT",+ "dependencies": {+ "asynckit": "^0.4.0",+ "combined-stream": "^1.0.8",+ "es-set-tostringtag": "^2.1.0",+ "hasown": "^2.0.4",+ "mime-types": "^2.1.35"+ },+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/fraction.js": {+ "version": "5.3.4",+ "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz",+ "integrity": "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==",+ "dev": true,+ "engines": {+ "node": "*"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/rawify"+ }+ },+ "node_modules/fs-extra": {+ "version": "10.1.0",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",+ "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.2.0",+ "jsonfile": "^6.0.1",+ "universalify": "^2.0.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/fs.realpath": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",+ "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/function-bind": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/gensync": {+ "version": "1.0.0-beta.2",+ "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",+ "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",+ "dev": true,+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/get-caller-file": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",+ "dev": true,+ "license": "ISC",+ "engines": {+ "node": "6.* || 8.* || >= 10.*"+ }+ },+ "node_modules/get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/get-stream": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",+ "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "pump": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/glob": {+ "version": "7.2.3",+ "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",+ "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",+ "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "fs.realpath": "^1.0.0",+ "inflight": "^1.0.4",+ "inherits": "2",+ "minimatch": "^3.1.1",+ "once": "^1.3.0",+ "path-is-absolute": "^1.0.0"+ },+ "engines": {+ "node": "*"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },+ "node_modules/glob-parent": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",+ "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==",+ "dev": true,+ "dependencies": {+ "is-glob": "^4.0.3"+ },+ "engines": {+ "node": ">=10.13.0"+ }+ },+ "node_modules/glob/node_modules/brace-expansion": {+ "version": "1.1.18",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",+ "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0",+ "concat-map": "0.0.1"+ }+ },+ "node_modules/glob/node_modules/minimatch": {+ "version": "3.1.5",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^1.1.7"+ },+ "engines": {+ "node": "*"+ }+ },+ "node_modules/global-agent": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-3.0.0.tgz",+ "integrity": "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==",+ "dev": true,+ "license": "BSD-3-Clause",+ "optional": true,+ "dependencies": {+ "boolean": "^3.0.1",+ "es6-error": "^4.1.1",+ "matcher": "^3.0.0",+ "roarr": "^2.15.3",+ "semver": "^7.3.2",+ "serialize-error": "^7.0.1"+ },+ "engines": {+ "node": ">=10.0"+ }+ },+ "node_modules/global-agent/node_modules/semver": {+ "version": "7.8.5",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",+ "dev": true,+ "license": "ISC",+ "optional": true,+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/globals": {+ "version": "17.11.0",+ "resolved": "https://registry.npmjs.org/globals/-/globals-17.11.0.tgz",+ "integrity": "sha512-Z2I8hM+PbJDXQDq3Icgpzv+mPdwr68iZUU9d5WW4FuXfDUQfkZaZuvjMv42/5crNyw154+9+VWXbYrUgDXbxNw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/globalthis": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz",+ "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "define-properties": "^1.2.1",+ "gopd": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/glsl-noise": {+ "version": "0.0.0",+ "resolved": "https://registry.npmjs.org/glsl-noise/-/glsl-noise-0.0.0.tgz",+ "integrity": "sha512-b/ZCF6amfAUb7dJM/MxRs7AetQEahYzJ8PtgfrmEdtw6uyGOr+ZSGtgjFm6mfsBkxJ4d2W7kg+Nlqzqvn3Bc0w=="+ },+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/got": {+ "version": "11.8.6",+ "resolved": "https://registry.npmjs.org/got/-/got-11.8.6.tgz",+ "integrity": "sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@sindresorhus/is": "^4.0.0",+ "@szmarczak/http-timer": "^4.0.5",+ "@types/cacheable-request": "^6.0.1",+ "@types/responselike": "^1.0.0",+ "cacheable-lookup": "^5.0.3",+ "cacheable-request": "^7.0.2",+ "decompress-response": "^6.0.0",+ "http2-wrapper": "^1.0.0-beta.5.2",+ "lowercase-keys": "^2.0.0",+ "p-cancelable": "^2.0.0",+ "responselike": "^2.0.0"+ },+ "engines": {+ "node": ">=10.19.0"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/got?sponsor=1"+ }+ },+ "node_modules/graceful-fs": {+ "version": "4.2.11",+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="+ },+ "node_modules/has-flag": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",+ "dev": true,+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/has-property-descriptors": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz",+ "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "es-define-property": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-tostringtag": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",+ "dependencies": {+ "has-symbols": "^1.0.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/hasown": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",+ "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",+ "license": "MIT",+ "dependencies": {+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/hermes-estree": {+ "version": "0.25.1",+ "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz",+ "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/hermes-parser": {+ "version": "0.25.1",+ "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz",+ "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "hermes-estree": "0.25.1"+ }+ },+ "node_modules/hls.js": {+ "version": "1.6.15",+ "resolved": "https://registry.npmjs.org/hls.js/-/hls.js-1.6.15.tgz",+ "integrity": "sha512-E3a5VwgXimGHwpRGV+WxRTKeSp2DW5DI5MWv34ulL3t5UNmyJWCQ1KmLEHbYzcfThfXG8amBL+fCYPneGHC4VA=="+ },+ "node_modules/hosted-git-info": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-4.1.0.tgz",+ "integrity": "sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "lru-cache": "^6.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/hosted-git-info/node_modules/lru-cache": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",+ "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "yallist": "^4.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/hosted-git-info/node_modules/yallist": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",+ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/html-encoding-sniffer": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz",+ "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@exodus/bytes": "^1.6.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/http-cache-semantics": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",+ "integrity": "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==",+ "dev": true,+ "license": "BSD-2-Clause"+ },+ "node_modules/http-proxy-agent": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",+ "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "agent-base": "^7.1.0",+ "debug": "^4.3.4"+ },+ "engines": {+ "node": ">= 14"+ }+ },+ "node_modules/http2-wrapper": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-1.0.3.tgz",+ "integrity": "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "quick-lru": "^5.1.1",+ "resolve-alpn": "^1.0.0"+ },+ "engines": {+ "node": ">=10.19.0"+ }+ },+ "node_modules/https-proxy-agent": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",+ "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "agent-base": "^7.1.2",+ "debug": "4"+ },+ "engines": {+ "node": ">= 14"+ }+ },+ "node_modules/ieee754": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ]+ },+ "node_modules/ignore": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",+ "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",+ "dev": true,+ "engines": {+ "node": ">= 4"+ }+ },+ "node_modules/immediate": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",+ "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ=="+ },+ "node_modules/import-fresh": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",+ "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==",+ "dev": true,+ "dependencies": {+ "parent-module": "^1.0.0",+ "resolve-from": "^4.0.0"+ },+ "engines": {+ "node": ">=6"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/imurmurhash": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",+ "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",+ "dev": true,+ "engines": {+ "node": ">=0.8.19"+ }+ },+ "node_modules/inflight": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",+ "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",+ "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "once": "^1.3.0",+ "wrappy": "1"+ }+ },+ "node_modules/inherits": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/is-binary-path": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",+ "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==",+ "dev": true,+ "dependencies": {+ "binary-extensions": "^2.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/is-core-module": {+ "version": "2.16.1",+ "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz",+ "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==",+ "dev": true,+ "dependencies": {+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/is-extglob": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",+ "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",+ "dev": true,+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/is-fullwidth-code-point": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/is-glob": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",+ "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",+ "dev": true,+ "dependencies": {+ "is-extglob": "^2.1.1"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/is-number": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",+ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",+ "dev": true,+ "engines": {+ "node": ">=0.12.0"+ }+ },+ "node_modules/is-potential-custom-element-name": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",+ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/is-promise": {+ "version": "2.2.2",+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.2.2.tgz",+ "integrity": "sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ=="+ },+ "node_modules/isarray": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",+ "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/isbinaryfile": {+ "version": "5.0.7",+ "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-5.0.7.tgz",+ "integrity": "sha512-gnWD14Jh3FzS3CPhF0AxNOJ8CxqeblPTADzI38r0wt8ZyQl5edpy75myt08EG2oKvpyiqSqsx+Wkz9vtkbTqYQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 18.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/gjtorikian/"+ }+ },+ "node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="+ },+ "node_modules/its-fine": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/its-fine/-/its-fine-1.2.5.tgz",+ "integrity": "sha512-fXtDA0X0t0eBYAGLVM5YsgJGsJ5jEmqZEPrGbzdf5awjv0xE7nqv3TVnvtUF060Tkes15DbDAKW/I48vsb6SyA==",+ "dependencies": {+ "@types/react-reconciler": "^0.28.0"+ },+ "peerDependencies": {+ "react": ">=18.0"+ }+ },+ "node_modules/its-fine/node_modules/@types/react-reconciler": {+ "version": "0.28.9",+ "resolved": "https://registry.npmjs.org/@types/react-reconciler/-/react-reconciler-0.28.9.tgz",+ "integrity": "sha512-HHM3nxyUZ3zAylX8ZEyrDNd2XZOnQ0D5XfunJF5FLQnZbHHYq4UWvW1QfelQNXv1ICNkwYhfxjwfnqivYB6bFg==",+ "peerDependencies": {+ "@types/react": "*"+ }+ },+ "node_modules/jake": {+ "version": "10.9.4",+ "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.4.tgz",+ "integrity": "sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "async": "^3.2.6",+ "filelist": "^1.0.4",+ "picocolors": "^1.1.1"+ },+ "bin": {+ "jake": "bin/cli.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/jiti": {+ "version": "1.21.7",+ "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.7.tgz",+ "integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==",+ "dev": true,+ "bin": {+ "jiti": "bin/jiti.js"+ }+ },+ "node_modules/js-tokens": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="+ },+ "node_modules/js-yaml": {+ "version": "4.3.1",+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz",+ "integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/puzrin"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/nodeca"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "argparse": "^2.0.1"+ },+ "bin": {+ "js-yaml": "bin/js-yaml.js"+ }+ },+ "node_modules/jsdom": {+ "version": "29.1.1",+ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-29.1.1.tgz",+ "integrity": "sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/css-color": "^5.1.11",+ "@asamuzakjp/dom-selector": "^7.1.1",+ "@bramus/specificity": "^2.4.2",+ "@csstools/css-syntax-patches-for-csstree": "^1.1.3",+ "@exodus/bytes": "^1.15.0",+ "css-tree": "^3.2.1",+ "data-urls": "^7.0.0",+ "decimal.js": "^10.6.0",+ "html-encoding-sniffer": "^6.0.0",+ "is-potential-custom-element-name": "^1.0.1",+ "lru-cache": "^11.3.5",+ "parse5": "^8.0.1",+ "saxes": "^6.0.0",+ "symbol-tree": "^3.2.4",+ "tough-cookie": "^6.0.1",+ "undici": "^7.25.0",+ "w3c-xmlserializer": "^5.0.0",+ "webidl-conversions": "^8.0.1",+ "whatwg-mimetype": "^5.0.0",+ "whatwg-url": "^16.0.1",+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24.0.0"+ },+ "peerDependencies": {+ "canvas": "^3.0.0"+ },+ "peerDependenciesMeta": {+ "canvas": {+ "optional": true+ }+ }+ },+ "node_modules/jsdom/node_modules/lru-cache": {+ "version": "11.5.3",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",+ "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",+ "dev": true,+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": "20 || >=22"+ }+ },+ "node_modules/jsesc": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",+ "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "jsesc": "bin/jsesc"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/json-buffer": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",+ "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==",+ "dev": true+ },+ "node_modules/json-schema-traverse": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",+ "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",+ "dev": true+ },+ "node_modules/json-stable-stringify-without-jsonify": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz",+ "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==",+ "dev": true+ },+ "node_modules/json-stringify-safe": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz",+ "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==",+ "dev": true,+ "license": "ISC",+ "optional": true+ },+ "node_modules/json5": {+ "version": "2.2.3",+ "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",+ "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",+ "dev": true,+ "bin": {+ "json5": "lib/cli.js"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/jsonfile": {+ "version": "6.2.1",+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",+ "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",+ "license": "MIT",+ "dependencies": {+ "universalify": "^2.0.0"+ },+ "optionalDependencies": {+ "graceful-fs": "^4.1.6"+ }+ },+ "node_modules/keyv": {+ "version": "4.5.4",+ "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",+ "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==",+ "dev": true,+ "dependencies": {+ "json-buffer": "3.0.1"+ }+ },+ "node_modules/lazy-val": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/lazy-val/-/lazy-val-1.0.5.tgz",+ "integrity": "sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q==",+ "license": "MIT"+ },+ "node_modules/levn": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",+ "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==",+ "dev": true,+ "dependencies": {+ "prelude-ls": "^1.2.1",+ "type-check": "~0.4.0"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/lie": {+ "version": "3.3.0",+ "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz",+ "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==",+ "dependencies": {+ "immediate": "~3.0.5"+ }+ },+ "node_modules/lilconfig": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",+ "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==",+ "dev": true,+ "engines": {+ "node": ">=14"+ },+ "funding": {+ "url": "https://github.com/sponsors/antonk52"+ }+ },+ "node_modules/lines-and-columns": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz",+ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",+ "dev": true+ },+ "node_modules/locate-path": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",+ "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==",+ "dev": true,+ "dependencies": {+ "p-locate": "^5.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/lodash": {+ "version": "4.18.1",+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",+ "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/lodash.escaperegexp": {+ "version": "4.1.2",+ "resolved": "https://registry.npmjs.org/lodash.escaperegexp/-/lodash.escaperegexp-4.1.2.tgz",+ "integrity": "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==",+ "license": "MIT"+ },+ "node_modules/lodash.isequal": {+ "version": "4.5.0",+ "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz",+ "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==",+ "deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.",+ "license": "MIT"+ },+ "node_modules/lodash.merge": {+ "version": "4.6.2",+ "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",+ "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==",+ "dev": true+ },+ "node_modules/loose-envify": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",+ "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",+ "dependencies": {+ "js-tokens": "^3.0.0 || ^4.0.0"+ },+ "bin": {+ "loose-envify": "cli.js"+ }+ },+ "node_modules/lowercase-keys": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz",+ "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/lru-cache": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",+ "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "yallist": "^3.0.2"+ }+ },+ "node_modules/maath": {+ "version": "0.10.8",+ "resolved": "https://registry.npmjs.org/maath/-/maath-0.10.8.tgz",+ "integrity": "sha512-tRvbDF0Pgqz+9XUa4jjfgAQ8/aPKmQdWXilFu2tMy4GWj4NOsx99HlULO4IeREfbO3a0sA145DZYyvXPkybm0g==",+ "peerDependencies": {+ "@types/three": ">=0.134.0",+ "three": ">=0.134.0"+ }+ },+ "node_modules/magic-string": {+ "version": "0.30.21",+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",+ "dev": true,+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.5"+ }+ },+ "node_modules/matcher": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz",+ "integrity": "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "escape-string-regexp": "^4.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/mdn-data": {+ "version": "2.27.1",+ "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",+ "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",+ "dev": true,+ "license": "CC0-1.0"+ },+ "node_modules/merge2": {+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",+ "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",+ "dev": true,+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/meshline": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/meshline/-/meshline-3.3.1.tgz",+ "integrity": "sha512-/TQj+JdZkeSUOl5Mk2J7eLcYTLiQm2IDzmlSvYm7ov15anEcDJ92GHqqazxTSreeNgfnYu24kiEvvv0WlbCdFQ==",+ "peerDependencies": {+ "three": ">=0.137"+ }+ },+ "node_modules/meshoptimizer": {+ "version": "0.18.1",+ "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-0.18.1.tgz",+ "integrity": "sha512-ZhoIoL7TNV4s5B6+rx5mC//fw8/POGyNxS/DZyCJeiZ12ScLfVwRE/GfsxwiTkMYYD5DmK2/JXnEVXqL4rF+Sw=="+ },+ "node_modules/micromatch": {+ "version": "4.0.8",+ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",+ "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",+ "dev": true,+ "dependencies": {+ "braces": "^3.0.3",+ "picomatch": "^2.3.1"+ },+ "engines": {+ "node": ">=8.6"+ }+ },+ "node_modules/mime": {+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz",+ "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "mime": "cli.js"+ },+ "engines": {+ "node": ">=4.0.0"+ }+ },+ "node_modules/mime-db": {+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime-types": {+ "version": "2.1.35",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "dependencies": {+ "mime-db": "1.52.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mimic-response": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz",+ "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/minimatch": {+ "version": "10.2.6",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",+ "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",+ "dev": true,+ "license": "BlueOak-1.0.0",+ "dependencies": {+ "brace-expansion": "^5.0.8"+ },+ "engines": {+ "node": "18 || 20 || >=22"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },+ "node_modules/minimist": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/mkdirp": {+ "version": "0.5.6",+ "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",+ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",+ "dev": true,+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "minimist": "^1.2.6"+ },+ "bin": {+ "mkdirp": "bin/cmd.js"+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="+ },+ "node_modules/mz": {+ "version": "2.7.0",+ "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz",+ "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==",+ "dev": true,+ "dependencies": {+ "any-promise": "^1.0.0",+ "object-assign": "^4.0.1",+ "thenify-all": "^1.0.0"+ }+ },+ "node_modules/n8ao": {+ "version": "1.10.1",+ "resolved": "https://registry.npmjs.org/n8ao/-/n8ao-1.10.1.tgz",+ "integrity": "sha512-hhI1pC+BfOZBV1KMwynBrVlIm8wqLxj/abAWhF2nZ0qQKyzTSQa1QtLVS2veRiuoBQXojxobcnp0oe+PUoxf/w==",+ "license": "ISC",+ "peerDependencies": {+ "postprocessing": ">=6.30.0",+ "three": ">=0.137"+ }+ },+ "node_modules/nanoid": {+ "version": "3.3.18",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",+ "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.cjs"+ },+ "engines": {+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ }+ },+ "node_modules/natural-compare": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",+ "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==",+ "dev": true+ },+ "node_modules/node-abi": {+ "version": "4.33.0",+ "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-4.33.0.tgz",+ "integrity": "sha512-vLBWCKb+7LWsX+TbfzWOkw0W81m377tyx3hOweBTjO43CXZnRGS1/JPWs20fr0PgZyDXk6ROYrylsEycK8raDA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "semver": "^7.6.3"+ },+ "engines": {+ "node": ">=22.12.0"+ }+ },+ "node_modules/node-abi/node_modules/semver": {+ "version": "7.8.5",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/node-api-version": {+ "version": "0.2.1",+ "resolved": "https://registry.npmjs.org/node-api-version/-/node-api-version-0.2.1.tgz",+ "integrity": "sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "semver": "^7.3.5"+ }+ },+ "node_modules/node-api-version/node_modules/semver": {+ "version": "7.8.5",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/node-gyp": {+ "version": "12.4.0",+ "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-12.4.0.tgz",+ "integrity": "sha512-OMcPNvqTCFUnNaBlmdgq+lfNqY7gTiSmNRDjY3uAXRyudeKZEZxu3CLtjMQrx4zZxCX2b/mpNqTtwuCJgXhHkw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "env-paths": "^2.2.0",+ "exponential-backoff": "^3.1.1",+ "graceful-fs": "^4.2.6",+ "nopt": "^9.0.0",+ "proc-log": "^6.0.0",+ "semver": "^7.3.5",+ "tar": "^7.5.4",+ "tinyglobby": "^0.2.12",+ "undici": "^6.25.0",+ "which": "^6.0.0"+ },+ "bin": {+ "node-gyp": "bin/node-gyp.js"+ },+ "engines": {+ "node": "^20.17.0 || >=22.9.0"+ }+ },+ "node_modules/node-gyp/node_modules/env-paths": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz",+ "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/node-gyp/node_modules/isexe": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-4.0.0.tgz",+ "integrity": "sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==",+ "dev": true,+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/node-gyp/node_modules/semver": {+ "version": "7.8.5",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/node-gyp/node_modules/undici": {+ "version": "6.28.0",+ "resolved": "https://registry.npmjs.org/undici/-/undici-6.28.0.tgz",+ "integrity": "sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18.17"+ }+ },+ "node_modules/node-gyp/node_modules/which": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/which/-/which-6.0.1.tgz",+ "integrity": "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "isexe": "^4.0.0"+ },+ "bin": {+ "node-which": "bin/which.js"+ },+ "engines": {+ "node": "^20.17.0 || >=22.9.0"+ }+ },+ "node_modules/node-int64": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz",+ "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/node-releases": {+ "version": "2.0.27",+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz",+ "integrity": "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==",+ "dev": true+ },+ "node_modules/nopt": {+ "version": "9.0.0",+ "resolved": "https://registry.npmjs.org/nopt/-/nopt-9.0.0.tgz",+ "integrity": "sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "abbrev": "^4.0.0"+ },+ "bin": {+ "nopt": "bin/nopt.js"+ },+ "engines": {+ "node": "^20.17.0 || >=22.9.0"+ }+ },+ "node_modules/normalize-path": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",+ "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",+ "dev": true,+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/normalize-url": {+ "version": "6.1.0",+ "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz",+ "integrity": "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/object-assign": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/object-hash": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz",+ "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==",+ "dev": true,+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/object-keys": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",+ "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/once": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "wrappy": "1"+ }+ },+ "node_modules/optionator": {+ "version": "0.9.4",+ "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",+ "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==",+ "dev": true,+ "dependencies": {+ "deep-is": "^0.1.3",+ "fast-levenshtein": "^2.0.6",+ "levn": "^0.4.1",+ "prelude-ls": "^1.2.1",+ "type-check": "^0.4.0",+ "word-wrap": "^1.2.5"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/p-cancelable": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz",+ "integrity": "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/p-limit": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",+ "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",+ "dev": true,+ "dependencies": {+ "yocto-queue": "^0.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/p-locate": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz",+ "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==",+ "dev": true,+ "dependencies": {+ "p-limit": "^3.0.2"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/parent-module": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",+ "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==",+ "dev": true,+ "dependencies": {+ "callsites": "^3.0.0"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/parse5": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",+ "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "entities": "^8.0.0"+ },+ "funding": {+ "url": "https://github.com/inikulin/parse5?sponsor=1"+ }+ },+ "node_modules/path-exists": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",+ "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",+ "dev": true,+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/path-is-absolute": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",+ "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/path-parse": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",+ "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",+ "dev": true+ },+ "node_modules/pe-library": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/pe-library/-/pe-library-0.4.1.tgz",+ "integrity": "sha512-eRWB5LBz7PpDu4PUlwT0PhnQfTQJlDDdPa35urV4Osrm0t0AqQFGn+UIkU3klZvwJ8KPO3VbBFsXquA6p6kqZw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12",+ "npm": ">=6"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/jet2jet"+ }+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "dev": true+ },+ "node_modules/picomatch": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",+ "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/pify": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz",+ "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==",+ "dev": true,+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/pirates": {+ "version": "4.0.7",+ "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz",+ "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==",+ "dev": true,+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/pkijs": {+ "version": "3.4.0",+ "resolved": "https://registry.npmjs.org/pkijs/-/pkijs-3.4.0.tgz",+ "integrity": "sha512-emEcLuomt2j03vxD54giVB4SxTjnsqkU692xZOZXHDVoYyypEm+b3jpiTcc+Cf+myooc+/Ly0z01jqeNHVgJGw==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "@noble/hashes": "1.4.0",+ "asn1js": "^3.0.6",+ "bytestreamjs": "^2.0.1",+ "pvtsutils": "^1.3.6",+ "pvutils": "^1.1.3",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=16.0.0"+ }+ },+ "node_modules/pkijs/node_modules/@noble/hashes": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.4.0.tgz",+ "integrity": "sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 16"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/plist": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.0.tgz",+ "integrity": "sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@xmldom/xmldom": "^0.8.8",+ "base64-js": "^1.5.1",+ "xmlbuilder": "^15.1.1"+ },+ "engines": {+ "node": ">=10.4.0"+ }+ },+ "node_modules/postcss": {+ "version": "8.5.26",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",+ "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.17",+ "picocolors": "^1.1.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/postcss-import": {+ "version": "15.1.0",+ "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-15.1.0.tgz",+ "integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==",+ "dev": true,+ "dependencies": {+ "postcss-value-parser": "^4.0.0",+ "read-cache": "^1.0.0",+ "resolve": "^1.1.7"+ },+ "engines": {+ "node": ">=14.0.0"+ },+ "peerDependencies": {+ "postcss": "^8.0.0"+ }+ },+ "node_modules/postcss-js": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-4.1.0.tgz",+ "integrity": "sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "dependencies": {+ "camelcase-css": "^2.0.1"+ },+ "engines": {+ "node": "^12 || ^14 || >= 16"+ },+ "peerDependencies": {+ "postcss": "^8.4.21"+ }+ },+ "node_modules/postcss-load-config": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz",+ "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "dependencies": {+ "lilconfig": "^3.1.1"+ },+ "engines": {+ "node": ">= 18"+ },+ "peerDependencies": {+ "jiti": ">=1.21.0",+ "postcss": ">=8.0.9",+ "tsx": "^4.8.1",+ "yaml": "^2.4.2"+ },+ "peerDependenciesMeta": {+ "jiti": {+ "optional": true+ },+ "postcss": {+ "optional": true+ },+ "tsx": {+ "optional": true+ },+ "yaml": {+ "optional": true+ }+ }+ },+ "node_modules/postcss-nested": {+ "version": "6.2.0",+ "resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz",+ "integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "dependencies": {+ "postcss-selector-parser": "^6.1.1"+ },+ "engines": {+ "node": ">=12.0"+ },+ "peerDependencies": {+ "postcss": "^8.2.14"+ }+ },+ "node_modules/postcss-selector-parser": {+ "version": "6.1.2",+ "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz",+ "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==",+ "dev": true,+ "dependencies": {+ "cssesc": "^3.0.0",+ "util-deprecate": "^1.0.2"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/postcss-value-parser": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",+ "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",+ "dev": true+ },+ "node_modules/postject": {+ "version": "1.0.0-alpha.6",+ "resolved": "https://registry.npmjs.org/postject/-/postject-1.0.0-alpha.6.tgz",+ "integrity": "sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "peer": true,+ "dependencies": {+ "commander": "^9.4.0"+ },+ "bin": {+ "postject": "dist/cli.js"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/postject/node_modules/commander": {+ "version": "9.5.0",+ "resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz",+ "integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "peer": true,+ "engines": {+ "node": "^12.20.0 || >=14"+ }+ },+ "node_modules/postprocessing": {+ "version": "6.39.0",+ "resolved": "https://registry.npmjs.org/postprocessing/-/postprocessing-6.39.0.tgz",+ "integrity": "sha512-/G6JY8hs426lcto/pBZlnFSkyEo1fHsh4gy7FPJtq1SaSUOzJgDW6f6f1K/+aMOYzK/eQEefyOb3++jPPIUeDA==",+ "license": "Zlib",+ "peerDependencies": {+ "three": ">= 0.168.0 < 0.184.0"+ }+ },+ "node_modules/potpack": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/potpack/-/potpack-1.0.2.tgz",+ "integrity": "sha512-choctRBIV9EMT9WGAZHn3V7t0Z2pMQyl0EZE6pFc/6ml3ssw7Dlf/oAOvFwjm1HVsqfQN8GfeFyJ+d8tRzqueQ=="+ },+ "node_modules/prelude-ls": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",+ "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==",+ "dev": true,+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/proc-log": {+ "version": "6.1.0",+ "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz",+ "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==",+ "dev": true,+ "license": "ISC",+ "engines": {+ "node": "^20.17.0 || >=22.9.0"+ }+ },+ "node_modules/process-nextick-args": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",+ "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/progress": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",+ "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/promise-retry": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/promise-retry/-/promise-retry-2.0.1.tgz",+ "integrity": "sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "err-code": "^2.0.2",+ "retry": "^0.12.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/promise-worker-transferable": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/promise-worker-transferable/-/promise-worker-transferable-1.0.4.tgz",+ "integrity": "sha512-bN+0ehEnrXfxV2ZQvU2PetO0n4gqBD4ulq3MI1WOPLgr7/Mg9yRQkX5+0v1vagr74ZTsl7XtzlaYDo2EuCeYJw==",+ "dependencies": {+ "is-promise": "^2.1.0",+ "lie": "^3.0.2"+ }+ },+ "node_modules/prop-types": {+ "version": "15.8.1",+ "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",+ "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",+ "dependencies": {+ "loose-envify": "^1.4.0",+ "object-assign": "^4.1.1",+ "react-is": "^16.13.1"+ }+ },+ "node_modules/proper-lockfile": {+ "version": "4.1.2",+ "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz",+ "integrity": "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.2.4",+ "retry": "^0.12.0",+ "signal-exit": "^3.0.2"+ }+ },+ "node_modules/proxy-from-env": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz",+ "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/pump": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",+ "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "end-of-stream": "^1.1.0",+ "once": "^1.3.1"+ }+ },+ "node_modules/punycode": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",+ "dev": true,+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/pvtsutils": {+ "version": "1.3.6",+ "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",+ "integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.8.1"+ }+ },+ "node_modules/pvutils": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz",+ "integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=16.0.0"+ }+ },+ "node_modules/queue-microtask": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",+ "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ]+ },+ "node_modules/quick-lru": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz",+ "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/react": {+ "version": "18.3.1",+ "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",+ "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",+ "dependencies": {+ "loose-envify": "^1.1.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/react-composer": {+ "version": "5.0.3",+ "resolved": "https://registry.npmjs.org/react-composer/-/react-composer-5.0.3.tgz",+ "integrity": "sha512-1uWd07EME6XZvMfapwZmc7NgCZqDemcvicRi3wMJzXsQLvZ3L7fTHVyPy1bZdnWXM4iPjYuNE+uJ41MLKeTtnA==",+ "dependencies": {+ "prop-types": "^15.6.0"+ },+ "peerDependencies": {+ "react": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0"+ }+ },+ "node_modules/react-dom": {+ "version": "18.3.1",+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",+ "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",+ "dependencies": {+ "loose-envify": "^1.1.0",+ "scheduler": "^0.23.2"+ },+ "peerDependencies": {+ "react": "^18.3.1"+ }+ },+ "node_modules/react-dom/node_modules/scheduler": {+ "version": "0.23.2",+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",+ "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",+ "dependencies": {+ "loose-envify": "^1.1.0"+ }+ },+ "node_modules/react-is": {+ "version": "16.13.1",+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",+ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="+ },+ "node_modules/react-reconciler": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.27.0.tgz",+ "integrity": "sha512-HmMDKciQjYmBRGuuhIaKA1ba/7a+UsM5FzOZsMO2JYHt9Jh8reCb7j1eDC95NOyUlKM9KRyvdx0flBuDvYSBoA==",+ "dependencies": {+ "loose-envify": "^1.1.0",+ "scheduler": "^0.21.0"+ },+ "engines": {+ "node": ">=0.10.0"+ },+ "peerDependencies": {+ "react": "^18.0.0"+ }+ },+ "node_modules/react-refresh": {+ "version": "0.17.0",+ "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz",+ "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==",+ "dev": true,+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/react-use-measure": {+ "version": "2.1.7",+ "resolved": "https://registry.npmjs.org/react-use-measure/-/react-use-measure-2.1.7.tgz",+ "integrity": "sha512-KrvcAo13I/60HpwGO5jpW7E9DfusKyLPLvuHlUyP5zqnmAPhNc6qTRjUQrdTADl0lpPpDVU2/Gg51UlOGHXbdg==",+ "peerDependencies": {+ "react": ">=16.13",+ "react-dom": ">=16.13"+ },+ "peerDependenciesMeta": {+ "react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/read-binary-file-arch": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/read-binary-file-arch/-/read-binary-file-arch-1.0.6.tgz",+ "integrity": "sha512-BNg9EN3DD3GsDXX7Aa8O4p92sryjkmzYYgmgTAc6CA4uGLEDzFfxOxugu21akOxpcXHiEgsYkC6nPsQvLLLmEg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "debug": "^4.3.4"+ },+ "bin": {+ "read-binary-file-arch": "cli.js"+ }+ },+ "node_modules/read-cache": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz",+ "integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==",+ "dev": true,+ "dependencies": {+ "pify": "^2.3.0"+ }+ },+ "node_modules/readable-stream": {+ "version": "2.3.8",+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",+ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "core-util-is": "~1.0.0",+ "inherits": "~2.0.3",+ "isarray": "~1.0.0",+ "process-nextick-args": "~2.0.0",+ "safe-buffer": "~5.1.1",+ "string_decoder": "~1.1.1",+ "util-deprecate": "~1.0.1"+ }+ },+ "node_modules/readdirp": {+ "version": "3.6.0",+ "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",+ "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",+ "dev": true,+ "dependencies": {+ "picomatch": "^2.2.1"+ },+ "engines": {+ "node": ">=8.10.0"+ }+ },+ "node_modules/require-directory": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",+ "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/require-from-string": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/resedit": {+ "version": "1.7.2",+ "resolved": "https://registry.npmjs.org/resedit/-/resedit-1.7.2.tgz",+ "integrity": "sha512-vHjcY2MlAITJhC0eRD/Vv8Vlgmu9Sd3LX9zZvtGzU5ZImdTN3+d6e/4mnTyV8vEbyf1sgNIrWxhWlrys52OkEA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "pe-library": "^0.4.1"+ },+ "engines": {+ "node": ">=12",+ "npm": ">=6"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/jet2jet"+ }+ },+ "node_modules/resolve": {+ "version": "1.22.11",+ "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz",+ "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==",+ "dev": true,+ "dependencies": {+ "is-core-module": "^2.16.1",+ "path-parse": "^1.0.7",+ "supports-preserve-symlinks-flag": "^1.0.0"+ },+ "bin": {+ "resolve": "bin/resolve"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/resolve-alpn": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.2.1.tgz",+ "integrity": "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/resolve-from": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",+ "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==",+ "dev": true,+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/responselike": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.1.tgz",+ "integrity": "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "lowercase-keys": "^2.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/retry": {+ "version": "0.12.0",+ "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",+ "integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 4"+ }+ },+ "node_modules/reusify": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",+ "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==",+ "dev": true,+ "engines": {+ "iojs": ">=1.0.0",+ "node": ">=0.10.0"+ }+ },+ "node_modules/rimraf": {+ "version": "2.6.3",+ "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz",+ "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==",+ "deprecated": "Rimraf versions prior to v4 are no longer supported",+ "dev": true,+ "license": "ISC",+ "peer": true,+ "dependencies": {+ "glob": "^7.1.3"+ },+ "bin": {+ "rimraf": "bin.js"+ }+ },+ "node_modules/roarr": {+ "version": "2.15.4",+ "resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz",+ "integrity": "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==",+ "dev": true,+ "license": "BSD-3-Clause",+ "optional": true,+ "dependencies": {+ "boolean": "^3.0.1",+ "detect-node": "^2.0.4",+ "globalthis": "^1.0.1",+ "json-stringify-safe": "^5.0.1",+ "semver-compare": "^1.0.0",+ "sprintf-js": "^1.1.2"+ },+ "engines": {+ "node": ">=8.0"+ }+ },+ "node_modules/rollup": {+ "version": "4.59.0",+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz",+ "integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==",+ "dev": true,+ "dependencies": {+ "@types/estree": "1.0.8"+ },+ "bin": {+ "rollup": "dist/bin/rollup"+ },+ "engines": {+ "node": ">=18.0.0",+ "npm": ">=8.0.0"+ },+ "optionalDependencies": {+ "@rollup/rollup-android-arm-eabi": "4.59.0",+ "@rollup/rollup-android-arm64": "4.59.0",+ "@rollup/rollup-darwin-arm64": "4.59.0",+ "@rollup/rollup-darwin-x64": "4.59.0",+ "@rollup/rollup-freebsd-arm64": "4.59.0",+ "@rollup/rollup-freebsd-x64": "4.59.0",+ "@rollup/rollup-linux-arm-gnueabihf": "4.59.0",+ "@rollup/rollup-linux-arm-musleabihf": "4.59.0",+ "@rollup/rollup-linux-arm64-gnu": "4.59.0",+ "@rollup/rollup-linux-arm64-musl": "4.59.0",+ "@rollup/rollup-linux-loong64-gnu": "4.59.0",+ "@rollup/rollup-linux-loong64-musl": "4.59.0",+ "@rollup/rollup-linux-ppc64-gnu": "4.59.0",+ "@rollup/rollup-linux-ppc64-musl": "4.59.0",+ "@rollup/rollup-linux-riscv64-gnu": "4.59.0",+ "@rollup/rollup-linux-riscv64-musl": "4.59.0",+ "@rollup/rollup-linux-s390x-gnu": "4.59.0",+ "@rollup/rollup-linux-x64-gnu": "4.59.0",+ "@rollup/rollup-linux-x64-musl": "4.59.0",+ "@rollup/rollup-openbsd-x64": "4.59.0",+ "@rollup/rollup-openharmony-arm64": "4.59.0",+ "@rollup/rollup-win32-arm64-msvc": "4.59.0",+ "@rollup/rollup-win32-ia32-msvc": "4.59.0",+ "@rollup/rollup-win32-x64-gnu": "4.59.0",+ "@rollup/rollup-win32-x64-msvc": "4.59.0",+ "fsevents": "~2.3.2"+ }+ },+ "node_modules/run-parallel": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",+ "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "dependencies": {+ "queue-microtask": "^1.2.2"+ }+ },+ "node_modules/safe-buffer": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",+ "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/sanitize-filename": {+ "version": "1.6.4",+ "resolved": "https://registry.npmjs.org/sanitize-filename/-/sanitize-filename-1.6.4.tgz",+ "integrity": "sha512-9ZyI08PsvdQl2r/bBIGubpVdR3RR9sY6RDiWFPreA21C/EFlQhmgo20UZlNjZMMZNubusLhAQozkA0Od5J21Eg==",+ "dev": true,+ "license": "WTFPL OR ISC",+ "dependencies": {+ "truncate-utf8-bytes": "^1.0.0"+ }+ },+ "node_modules/sax": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.0.tgz",+ "integrity": "sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==",+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": ">=11.0.0"+ }+ },+ "node_modules/saxes": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",+ "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "xmlchars": "^2.2.0"+ },+ "engines": {+ "node": ">=v12.22.7"+ }+ },+ "node_modules/scheduler": {+ "version": "0.21.0",+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.21.0.tgz",+ "integrity": "sha512-1r87x5fz9MXqswA2ERLo0EbOAU74DpIUO090gIasYTqlVoJeMcl+Z1Rg7WHz+qtPujhS/hGIt9kxZOYBV3faRQ==",+ "dependencies": {+ "loose-envify": "^1.1.0"+ }+ },+ "node_modules/semver": {+ "version": "6.3.1",+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ }+ },+ "node_modules/semver-compare": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz",+ "integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==",+ "dev": true,+ "license": "MIT",+ "optional": true+ },+ "node_modules/serialize-error": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz",+ "integrity": "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "type-fest": "^0.13.1"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/signal-exit": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",+ "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/simple-update-notifier": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz",+ "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==",+ "dev": true,+ "dependencies": {+ "semver": "^7.5.3"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/simple-update-notifier/node_modules/semver": {+ "version": "7.7.4",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",+ "dev": true,+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/source-map": {+ "version": "0.6.1",+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",+ "dev": true,+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/source-map-js": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",+ "dev": true,+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/source-map-support": {+ "version": "0.5.21",+ "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",+ "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "buffer-from": "^1.0.0",+ "source-map": "^0.6.0"+ }+ },+ "node_modules/sprintf-js": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",+ "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "optional": true+ },+ "node_modules/stat-mode": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/stat-mode/-/stat-mode-1.0.0.tgz",+ "integrity": "sha512-jH9EhtKIjuXZ2cWxmXS8ZP80XyC3iasQxMDV8jzhNJpfDb7VbQLVW4Wvsxz9QZvzV+G4YoSfBUVKDOyxLzi/sg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/stats-gl": {+ "version": "2.4.2",+ "resolved": "https://registry.npmjs.org/stats-gl/-/stats-gl-2.4.2.tgz",+ "integrity": "sha512-g5O9B0hm9CvnM36+v7SFl39T7hmAlv541tU81ME8YeSb3i1CIP5/QdDeSB3A0la0bKNHpxpwxOVRo2wFTYEosQ==",+ "dependencies": {+ "@types/three": "*",+ "three": "^0.170.0"+ },+ "peerDependencies": {+ "@types/three": "*",+ "three": "*"+ }+ },+ "node_modules/stats-gl/node_modules/three": {+ "version": "0.170.0",+ "resolved": "https://registry.npmjs.org/three/-/three-0.170.0.tgz",+ "integrity": "sha512-FQK+LEpYc0fBD+J8g6oSEyyNzjp+Q7Ks1C568WWaoMRLW+TkNNWmenWeGgJjV105Gd+p/2ql1ZcjYvNiPZBhuQ=="+ },+ "node_modules/stats.js": {+ "version": "0.17.0",+ "resolved": "https://registry.npmjs.org/stats.js/-/stats.js-0.17.0.tgz",+ "integrity": "sha512-hNKz8phvYLPEcRkeG1rsGmV5ChMjKDAWU7/OJJdDErPBNChQXxCo3WZurGpnWc6gZhAzEPFad1aVgyOANH1sMw=="+ },+ "node_modules/string_decoder": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",+ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "safe-buffer": "~5.1.0"+ }+ },+ "node_modules/string-width": {+ "version": "4.2.3",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^8.0.0",+ "is-fullwidth-code-point": "^3.0.0",+ "strip-ansi": "^6.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/strip-ansi": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^5.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/strip-json-comments": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",+ "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==",+ "dev": true,+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/sucrase": {+ "version": "3.35.1",+ "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz",+ "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==",+ "dev": true,+ "dependencies": {+ "@jridgewell/gen-mapping": "^0.3.2",+ "commander": "^4.0.0",+ "lines-and-columns": "^1.1.6",+ "mz": "^2.7.0",+ "pirates": "^4.0.1",+ "tinyglobby": "^0.2.11",+ "ts-interface-checker": "^0.1.9"+ },+ "bin": {+ "sucrase": "bin/sucrase",+ "sucrase-node": "bin/sucrase-node"+ },+ "engines": {+ "node": ">=16 || 14 >=14.17"+ }+ },+ "node_modules/sucrase/node_modules/commander": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",+ "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==",+ "dev": true,+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/sumchecker": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",+ "integrity": "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==",+ "license": "Apache-2.0",+ "dependencies": {+ "debug": "^4.1.0"+ },+ "engines": {+ "node": ">= 8.0"+ }+ },+ "node_modules/supports-color": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",+ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",+ "dev": true,+ "dependencies": {+ "has-flag": "^4.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/supports-preserve-symlinks-flag": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",+ "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",+ "dev": true,+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/suspend-react": {+ "version": "0.1.3",+ "resolved": "https://registry.npmjs.org/suspend-react/-/suspend-react-0.1.3.tgz",+ "integrity": "sha512-aqldKgX9aZqpoDp3e8/BZ8Dm7x1pJl+qI3ZKxDN0i/IQTWUwBx/ManmlVJ3wowqbno6c2bmiIfs+Um6LbsjJyQ==",+ "peerDependencies": {+ "react": ">=17.0"+ }+ },+ "node_modules/symbol-tree": {+ "version": "3.2.4",+ "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",+ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tailwindcss": {+ "version": "3.4.19",+ "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.19.tgz",+ "integrity": "sha512-3ofp+LL8E+pK/JuPLPggVAIaEuhvIz4qNcf3nA1Xn2o/7fb7s/TYpHhwGDv1ZU3PkBluUVaF8PyCHcm48cKLWQ==",+ "dev": true,+ "dependencies": {+ "@alloc/quick-lru": "^5.2.0",+ "arg": "^5.0.2",+ "chokidar": "^3.6.0",+ "didyoumean": "^1.2.2",+ "dlv": "^1.1.3",+ "fast-glob": "^3.3.2",+ "glob-parent": "^6.0.2",+ "is-glob": "^4.0.3",+ "jiti": "^1.21.7",+ "lilconfig": "^3.1.3",+ "micromatch": "^4.0.8",+ "normalize-path": "^3.0.0",+ "object-hash": "^3.0.0",+ "picocolors": "^1.1.1",+ "postcss": "^8.4.47",+ "postcss-import": "^15.1.0",+ "postcss-js": "^4.0.1",+ "postcss-load-config": "^4.0.2 || ^5.0 || ^6.0",+ "postcss-nested": "^6.2.0",+ "postcss-selector-parser": "^6.1.2",+ "resolve": "^1.22.8",+ "sucrase": "^3.35.0"+ },+ "bin": {+ "tailwind": "lib/cli.js",+ "tailwindcss": "lib/cli.js"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/tar": {+ "version": "7.5.22",+ "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz",+ "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==",+ "license": "BlueOak-1.0.0",+ "dependencies": {+ "@isaacs/fs-minipass": "^4.0.0",+ "chownr": "^3.0.0",+ "minipass": "^7.1.2",+ "minizlib": "^3.1.0",+ "yallist": "^5.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tar/node_modules/chownr": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz",+ "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tar/node_modules/minipass": {+ "version": "7.1.3",+ "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",+ "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",+ "engines": {+ "node": ">=16 || 14 >=14.17"+ }+ },+ "node_modules/tar/node_modules/minizlib": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz",+ "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==",+ "dependencies": {+ "minipass": "^7.1.2"+ },+ "engines": {+ "node": ">= 18"+ }+ },+ "node_modules/tar/node_modules/yallist": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz",+ "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/temp": {+ "version": "0.9.4",+ "resolved": "https://registry.npmjs.org/temp/-/temp-0.9.4.tgz",+ "integrity": "sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==",+ "dev": true,+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "mkdirp": "^0.5.1",+ "rimraf": "~2.6.2"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/temp-file": {+ "version": "3.4.0",+ "resolved": "https://registry.npmjs.org/temp-file/-/temp-file-3.4.0.tgz",+ "integrity": "sha512-C5tjlC/HCtVUOi3KWVokd4vHVViOmGjtLwIh4MuzPo/nMYTV/p1urt3RnMz2IWXDdKEGJH3k5+KPxtqRsUYGtg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "async-exit-hook": "^2.0.1",+ "fs-extra": "^10.0.0"+ }+ },+ "node_modules/thenify": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz",+ "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==",+ "dev": true,+ "dependencies": {+ "any-promise": "^1.0.0"+ }+ },+ "node_modules/thenify-all": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz",+ "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==",+ "dev": true,+ "dependencies": {+ "thenify": ">= 3.1.0 < 4"+ },+ "engines": {+ "node": ">=0.8"+ }+ },+ "node_modules/three": {+ "version": "0.171.0",+ "resolved": "https://registry.npmjs.org/three/-/three-0.171.0.tgz",+ "integrity": "sha512-Y/lAXPaKZPcEdkKjh0JOAHVv8OOnv/NDJqm0wjfCzyQmfKxV7zvkwsnBgPBKTzJHToSOhRGQAGbPJObT59B/PQ=="+ },+ "node_modules/three-mesh-bvh": {+ "version": "0.9.9",+ "resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.9.9.tgz",+ "integrity": "sha512-FJKitcjvbALmeQRK+Sc+nLGorCpkrZBrbgJZFzhdyWboak37DZikn46hvQkNqSbJPm227ahYmS6k3N/GXaAyXw==",+ "license": "MIT",+ "peerDependencies": {+ "three": ">= 0.159.0"+ }+ },+ "node_modules/three-stdlib": {+ "version": "2.36.1",+ "resolved": "https://registry.npmjs.org/three-stdlib/-/three-stdlib-2.36.1.tgz",+ "integrity": "sha512-XyGQrFmNQ5O/IoKm556ftwKsBg11TIb301MB5dWNicziQBEs2g3gtOYIf7pFiLa0zI2gUwhtCjv9fmjnxKZ1Cg==",+ "dependencies": {+ "@types/draco3d": "^1.4.0",+ "@types/offscreencanvas": "^2019.6.4",+ "@types/webxr": "^0.5.2",+ "draco3d": "^1.4.1",+ "fflate": "^0.6.9",+ "potpack": "^1.0.1"+ },+ "peerDependencies": {+ "three": ">=0.128.0"+ }+ },+ "node_modules/three-stdlib/node_modules/fflate": {+ "version": "0.6.10",+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.6.10.tgz",+ "integrity": "sha512-IQrh3lEPM93wVCEczc9SaAOvkmcoQn/G8Bo1e8ZPlY3X3bnAxWaBdvTdvM1hP62iZp0BXWDy4vTAy4fF0+Dlpg=="+ },+ "node_modules/tiny-async-pool": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/tiny-async-pool/-/tiny-async-pool-1.3.0.tgz",+ "integrity": "sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "semver": "^5.5.0"+ }+ },+ "node_modules/tiny-async-pool/node_modules/semver": {+ "version": "5.7.2",+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",+ "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver"+ }+ },+ "node_modules/tiny-typed-emitter": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/tiny-typed-emitter/-/tiny-typed-emitter-2.1.0.tgz",+ "integrity": "sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA==",+ "license": "MIT"+ },+ "node_modules/tinyglobby": {+ "version": "0.2.15",+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",+ "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",+ "dev": true,+ "dependencies": {+ "fdir": "^6.5.0",+ "picomatch": "^4.0.3"+ },+ "engines": {+ "node": ">=12.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/SuperchupuDev"+ }+ },+ "node_modules/tinyglobby/node_modules/fdir": {+ "version": "6.5.0",+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",+ "dev": true,+ "engines": {+ "node": ">=12.0.0"+ },+ "peerDependencies": {+ "picomatch": "^3 || ^4"+ },+ "peerDependenciesMeta": {+ "picomatch": {+ "optional": true+ }+ }+ },+ "node_modules/tinyglobby/node_modules/picomatch": {+ "version": "4.0.5",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",+ "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/tldts": {+ "version": "7.4.16",+ "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.16.tgz",+ "integrity": "sha512-QwBER5KMR86IIjpIiO7H/Z3IMJPsZ1A6RKPAqzTTgOyUQUSt9FdnKcqhTaJmkY6HVrgouZHZR0ncK5QxvmnQeg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tldts-core": "^7.4.16"+ },+ "bin": {+ "tldts": "bin/cli.js"+ }+ },+ "node_modules/tldts-core": {+ "version": "7.4.16",+ "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.16.tgz",+ "integrity": "sha512-MDolfaSJtlSK5Y0A1xl3277ekubZwobpBjugknDizI9O5Rm60a1m8k4ICK+MRsCDzPygT81mp3BBf5RKDlFRfA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tmp": {+ "version": "0.2.7",+ "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz",+ "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=14.14"+ }+ },+ "node_modules/tmp-promise": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/tmp-promise/-/tmp-promise-3.0.3.tgz",+ "integrity": "sha512-RwM7MoPojPxsOBYnyd2hy0bxtIlVrihNs9pj5SUvY8Zz1sQcQG2tG1hSr8PDxfgEB8RNKDhqbIlroIarSNDNsQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tmp": "^0.2.0"+ }+ },+ "node_modules/to-regex-range": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",+ "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",+ "dev": true,+ "dependencies": {+ "is-number": "^7.0.0"+ },+ "engines": {+ "node": ">=8.0"+ }+ },+ "node_modules/tough-cookie": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz",+ "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "tldts": "^7.0.5"+ },+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/tr46": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz",+ "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "punycode": "^2.3.1"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/troika-three-text": {+ "version": "0.52.4",+ "resolved": "https://registry.npmjs.org/troika-three-text/-/troika-three-text-0.52.4.tgz",+ "integrity": "sha512-V50EwcYGruV5rUZ9F4aNsrytGdKcXKALjEtQXIOBfhVoZU9VAqZNIoGQ3TMiooVqFAbR1w15T+f+8gkzoFzawg==",+ "dependencies": {+ "bidi-js": "^1.0.2",+ "troika-three-utils": "^0.52.4",+ "troika-worker-utils": "^0.52.0",+ "webgl-sdf-generator": "1.1.1"+ },+ "peerDependencies": {+ "three": ">=0.125.0"+ }+ },+ "node_modules/troika-three-utils": {+ "version": "0.52.4",+ "resolved": "https://registry.npmjs.org/troika-three-utils/-/troika-three-utils-0.52.4.tgz",+ "integrity": "sha512-NORAStSVa/BDiG52Mfudk4j1FG4jC4ILutB3foPnfGbOeIs9+G5vZLa0pnmnaftZUGm4UwSoqEpWdqvC7zms3A==",+ "peerDependencies": {+ "three": ">=0.125.0"+ }+ },+ "node_modules/troika-worker-utils": {+ "version": "0.52.0",+ "resolved": "https://registry.npmjs.org/troika-worker-utils/-/troika-worker-utils-0.52.0.tgz",+ "integrity": "sha512-W1CpvTHykaPH5brv5VHLfQo9D1OYuo0cSBEUQFFT/nBUzM8iD6Lq2/tgG/f1OelbAS1WtaTPQzE5uM49egnngw=="+ },+ "node_modules/truncate-utf8-bytes": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/truncate-utf8-bytes/-/truncate-utf8-bytes-1.0.2.tgz",+ "integrity": "sha512-95Pu1QXQvruGEhv62XCMO3Mm90GscOCClvrIUwCM0PYOXK3kaF3l3sIHxx71ThJfcbM2O5Au6SO3AWCSEfW4mQ==",+ "dev": true,+ "license": "WTFPL",+ "dependencies": {+ "utf8-byte-length": "^1.0.1"+ }+ },+ "node_modules/ts-api-utils": {+ "version": "2.5.0",+ "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz",+ "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18.12"+ },+ "peerDependencies": {+ "typescript": ">=4.8.4"+ }+ },+ "node_modules/ts-interface-checker": {+ "version": "0.1.13",+ "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz",+ "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==",+ "dev": true+ },+ "node_modules/tslib": {+ "version": "2.8.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",+ "dev": true,+ "license": "0BSD"+ },+ "node_modules/tunnel-rat": {+ "version": "0.1.2",+ "resolved": "https://registry.npmjs.org/tunnel-rat/-/tunnel-rat-0.1.2.tgz",+ "integrity": "sha512-lR5VHmkPhzdhrM092lI2nACsLO4QubF0/yoOhzX7c+wIpbN1GjHNzCc91QlpxBi+cnx8vVJ+Ur6vL5cEoQPFpQ==",+ "dependencies": {+ "zustand": "^4.3.2"+ }+ },+ "node_modules/tunnel-rat/node_modules/zustand": {+ "version": "4.5.7",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",+ "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",+ "dependencies": {+ "use-sync-external-store": "^1.2.2"+ },+ "engines": {+ "node": ">=12.7.0"+ },+ "peerDependencies": {+ "@types/react": ">=16.8",+ "immer": ">=9.0.6",+ "react": ">=16.8"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "immer": {+ "optional": true+ },+ "react": {+ "optional": true+ }+ }+ },+ "node_modules/type-check": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",+ "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==",+ "dev": true,+ "dependencies": {+ "prelude-ls": "^1.2.1"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/type-fest": {+ "version": "0.13.1",+ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz",+ "integrity": "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==",+ "dev": true,+ "license": "(MIT OR CC0-1.0)",+ "optional": true,+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/typescript-eslint": {+ "version": "8.67.0",+ "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.67.0.tgz",+ "integrity": "sha512-S2udFs8tCKEKffuJ4TB1idGUZiXdCPGi3IPBGWXarbLQ5UPXORV8QEVzJ4gCRduURMb5EkpNCdjbk0eDIuI8Yg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@typescript-eslint/eslint-plugin": "8.67.0",+ "@typescript-eslint/parser": "8.67.0",+ "@typescript-eslint/typescript-estree": "8.67.0",+ "@typescript-eslint/utils": "8.67.0"+ },+ "engines": {+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/typescript-eslint"+ },+ "peerDependencies": {+ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",+ "typescript": ">=4.8.4 <6.1.0"+ }+ },+ "node_modules/undici": {+ "version": "7.29.0",+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz",+ "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==",+ "devOptional": true,+ "license": "MIT",+ "engines": {+ "node": ">=20.18.1"+ }+ },+ "node_modules/undici-types": {+ "version": "6.21.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",+ "dev": true+ },+ "node_modules/universalify": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",+ "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",+ "license": "MIT",+ "engines": {+ "node": ">= 10.0.0"+ }+ },+ "node_modules/unzipper": {+ "version": "0.12.5",+ "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.12.5.tgz",+ "integrity": "sha512-tXYOi9R57Uj/2Z25SOs5RRSzq886MBQj2gY8dPL+xl/kv6s6SvByoKfAtvfVeEuhntWDgjd2o9p2lb4TVPAz0A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "bluebird": "~3.7.2",+ "duplexer2": "~0.1.4",+ "fs-extra": "11.3.1",+ "graceful-fs": "^4.2.2",+ "node-int64": "^0.4.0"+ }+ },+ "node_modules/unzipper/node_modules/fs-extra": {+ "version": "11.3.1",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.1.tgz",+ "integrity": "sha512-eXvGGwZ5CL17ZSwHWd3bbgk7UUpF6IFHtP57NYYakPvHOs8GDgDe5KJI36jIJzDkJ6eJjuzRA8eBQb6SkKue0g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.2.0",+ "jsonfile": "^6.0.1",+ "universalify": "^2.0.0"+ },+ "engines": {+ "node": ">=14.14"+ }+ },+ "node_modules/update-browserslist-db": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",+ "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/browserslist"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/browserslist"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "dependencies": {+ "escalade": "^3.2.0",+ "picocolors": "^1.1.1"+ },+ "bin": {+ "update-browserslist-db": "cli.js"+ },+ "peerDependencies": {+ "browserslist": ">= 4.21.0"+ }+ },+ "node_modules/uri-js": {+ "version": "4.4.1",+ "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",+ "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",+ "dev": true,+ "dependencies": {+ "punycode": "^2.1.0"+ }+ },+ "node_modules/use-sync-external-store": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",+ "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/utf8-byte-length": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/utf8-byte-length/-/utf8-byte-length-1.0.5.tgz",+ "integrity": "sha512-Xn0w3MtiQ6zoz2vFyUVruaCL53O/DwUvkEeOvj+uulMm0BkUGYWmBYVyElqZaSLhY6ZD0ulfU3aBra2aVT4xfA==",+ "dev": true,+ "license": "(WTFPL OR MIT)"+ },+ "node_modules/util-deprecate": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",+ "dev": true+ },+ "node_modules/utility-types": {+ "version": "3.11.0",+ "resolved": "https://registry.npmjs.org/utility-types/-/utility-types-3.11.0.tgz",+ "integrity": "sha512-6Z7Ma2aVEWisaL6TvBCy7P8rm2LQoPv6dJ7ecIaIixHcwfbJ0x7mWdbcwlIM5IGQxPZSFYeqRCqlOOeKoJYMkw==",+ "engines": {+ "node": ">= 4"+ }+ },+ "node_modules/vite": {+ "version": "7.3.6",+ "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.6.tgz",+ "integrity": "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "esbuild": "^0.27.0 || ^0.28.0",+ "fdir": "^6.5.0",+ "picomatch": "^4.0.3",+ "postcss": "^8.5.6",+ "rollup": "^4.43.0",+ "tinyglobby": "^0.2.15"+ },+ "bin": {+ "vite": "bin/vite.js"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "funding": {+ "url": "https://github.com/vitejs/vite?sponsor=1"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ },+ "peerDependencies": {+ "@types/node": "^20.19.0 || >=22.12.0",+ "jiti": ">=1.21.0",+ "less": "^4.0.0",+ "lightningcss": "^1.21.0",+ "sass": "^1.70.0",+ "sass-embedded": "^1.70.0",+ "stylus": ">=0.54.8",+ "sugarss": "^5.0.0",+ "terser": "^5.16.0",+ "tsx": "^4.8.1",+ "yaml": "^2.4.2"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ },+ "jiti": {+ "optional": true+ },+ "less": {+ "optional": true+ },+ "lightningcss": {+ "optional": true+ },+ "sass": {+ "optional": true+ },+ "sass-embedded": {+ "optional": true+ },+ "stylus": {+ "optional": true+ },+ "sugarss": {+ "optional": true+ },+ "terser": {+ "optional": true+ },+ "tsx": {+ "optional": true+ },+ "yaml": {+ "optional": true+ }+ }+ },+ "node_modules/vite/node_modules/fdir": {+ "version": "6.5.0",+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12.0.0"+ },+ "peerDependencies": {+ "picomatch": "^3 || ^4"+ },+ "peerDependenciesMeta": {+ "picomatch": {+ "optional": true+ }+ }+ },+ "node_modules/vite/node_modules/picomatch": {+ "version": "4.0.5",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",+ "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/w3c-xmlserializer": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",+ "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/webcrypto-core": {+ "version": "1.9.2",+ "resolved": "https://registry.npmjs.org/webcrypto-core/-/webcrypto-core-1.9.2.tgz",+ "integrity": "sha512-gsXecm82UQNlTBURJGuqOWy1Ww08S3kZUcr3aOJS02Pk0xLtkfeUAVC0u0xhgdonFme80edSJUIJyuvL/7250Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@peculiar/asn1-schema": "^2.7.0",+ "@peculiar/json-schema": "^1.1.12",+ "@peculiar/utils": "^2.0.2",+ "asn1js": "^3.0.10",+ "tslib": "^2.8.1"+ }+ },+ "node_modules/webgl-constants": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/webgl-constants/-/webgl-constants-1.1.1.tgz",+ "integrity": "sha512-LkBXKjU5r9vAW7Gcu3T5u+5cvSvh5WwINdr0C+9jpzVB41cjQAP5ePArDtk/WHYdVj0GefCgM73BA7FlIiNtdg=="+ },+ "node_modules/webgl-sdf-generator": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/webgl-sdf-generator/-/webgl-sdf-generator-1.1.1.tgz",+ "integrity": "sha512-9Z0JcMTFxeE+b2x1LJTdnaT8rT8aEp7MVxkNwoycNmJWwPdzoXzMh0BjJSh/AEFP+KPYZUli814h8bJZFIZ2jA=="+ },+ "node_modules/webidl-conversions": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz",+ "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/whatwg-mimetype": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz",+ "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/whatwg-url": {+ "version": "16.0.1",+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz",+ "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@exodus/bytes": "^1.11.0",+ "tr46": "^6.0.0",+ "webidl-conversions": "^8.0.1"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/word-wrap": {+ "version": "1.2.5",+ "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",+ "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==",+ "dev": true,+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/wrap-ansi": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",+ "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^4.0.0",+ "string-width": "^4.1.0",+ "strip-ansi": "^6.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"+ }+ },+ "node_modules/wrappy": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/xml-name-validator": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",+ "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/xmlbuilder": {+ "version": "15.1.1",+ "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",+ "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8.0"+ }+ },+ "node_modules/xmlchars": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",+ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/y18n": {+ "version": "5.0.8",+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",+ "dev": true,+ "license": "ISC",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/yallist": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",+ "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/yargs": {+ "version": "17.7.2",+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",+ "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "cliui": "^8.0.1",+ "escalade": "^3.1.1",+ "get-caller-file": "^2.0.5",+ "require-directory": "^2.1.1",+ "string-width": "^4.2.3",+ "y18n": "^5.0.5",+ "yargs-parser": "^21.1.1"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/yargs-parser": {+ "version": "21.1.1",+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",+ "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",+ "dev": true,+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/yocto-queue": {+ "version": "0.1.0",+ "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",+ "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",+ "dev": true,+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/zod": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",+ "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },+ "node_modules/zod-validation-error": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/zod-validation-error/-/zod-validation-error-4.0.2.tgz",+ "integrity": "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ },+ "peerDependencies": {+ "zod": "^3.25.0 || ^4.0.0"+ }+ },+ "node_modules/zustand": {+ "version": "5.0.11",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.11.tgz",+ "integrity": "sha512-fdZY+dk7zn/vbWNCYmzZULHRrss0jx5pPFiOuMZ/5HJN6Yv3u+1Wswy/4MpZEkEGhtNH+pwxZB8OKgUBPzYAGg==",+ "engines": {+ "node": ">=12.20.0"+ },+ "peerDependencies": {+ "@types/react": ">=18.0.0",+ "immer": ">=9.0.6",+ "react": ">=18.0.0",+ "use-sync-external-store": ">=1.2.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "immer": {+ "optional": true+ },+ "react": {+ "optional": true+ },+ "use-sync-external-store": {+ "optional": true+ }+ }+ }+ }+}diff --git a/apps/forge-desktop/package.json b/apps/forge-desktop/package.jsonnew file mode 100644index 000000000..8c3a985b6--- /dev/null+++ b/apps/forge-desktop/package.json@@ -0,0 +1,136 @@+{+ "name": "modly",+ "version": "0.4.3",+ "description": "Local AI-powered 3D mesh generation from images",+ "main": "./out/main/index.js",+ "author": "Modly",+ "private": true,+ "scripts": {+ "dev": "node scripts/build-builtins.mjs && electron-vite dev",+ "build": "node scripts/build-builtins.mjs && electron-vite build",+ "preview": "electron-vite preview",+ "prepare": "node scripts/setup-hooks.mjs",+ "prepare-resources": "node scripts/download-python-embed.js",+ "test": "npm run test:py && npm run test:node",+ "test:py": "node scripts/run-pytests.mjs",+ "test:node": "node --test --experimental-strip-types --experimental-loader ./scripts/node-ts-extensionless-loader.mjs src/shared/types/assetLibrary.test.ts src/areas/generate/assetLibraryProjection.test.ts src/areas/generate/assetLibraryService.test.ts src/areas/generate/assetLibraryUi.test.ts src/areas/generate/orcaSlicerLink.test.ts electron/main/artifact-registry-service.test.ts electron/main/extension-path-guard.test.ts electron/preload/artifact-registry-preload.test.ts && node --test electron/main/*.test.mjs src/**/*.test.mjs",+ "package": "cross-env CSC_IDENTITY_AUTO_DISCOVERY=false npm run build && npm run prepare-resources && electron-builder",+ "package:mac": "cross-env CSC_IDENTITY_AUTO_DISCOVERY=false npm run build && npm run prepare-resources && electron-builder --mac --arm64",+ "lint": "eslint ."+ },+ "dependencies": {+ "@electron-toolkit/utils": "^4.0.0",+ "@mkkellogg/gaussian-splats-3d": "^0.4.7",+ "@react-three/drei": "^9.120.0",+ "@react-three/fiber": "^8.17.10",+ "@react-three/postprocessing": "^2.19.1",+ "@xyflow/react": "^12.10.2",+ "axios": "^1.7.9",+ "electron-updater": "^6.8.3",+ "esbuild": "^0.28.0",+ "react": "^18.3.1",+ "react-dom": "^18.3.1",+ "tar": "^7.5.9",+ "three": "^0.171.0",+ "three-mesh-bvh": "^0.9.9",+ "zustand": "^5.0.3"+ },+ "devDependencies": {+ "@eslint/js": "^9.39.4",+ "@types/node": "^22.10.1",+ "@types/react": "^18.3.17",+ "@types/react-dom": "^18.3.5",+ "@types/tar": "^7.0.87",+ "@types/three": "^0.171.0",+ "@vitejs/plugin-react": "^4.3.4",+ "autoprefixer": "^10.4.20",+ "cross-env": "^10.1.0",+ "electron": "^42.11.1",+ "electron-builder": "^26.15.3",+ "electron-vite": "^5.0.0",+ "eslint": "^9.17.0",+ "eslint-plugin-react-hooks": "^7.1.1",+ "globals": "^17.6.0",+ "jsdom": "^29.1.1",+ "postcss": "^8.4.49",+ "tailwindcss": "^3.4.17",+ "typescript": "^5.7.2",+ "typescript-eslint": "^8.61.1",+ "vite": "^7.0.0"+ },+ "overrides": {+ "esbuild": "^0.28.0"+ },+ "build": {+ "appId": "com.modly.app",+ "productName": "Modly",+ "directories": {+ "output": "dist"+ },+ "afterPack": "scripts/after-pack.js",+ "files": [+ "out/**/*"+ ],+ "extraResources": [+ {+ "from": "api",+ "to": "api",+ "filter": [+ "**/*",+ "!.venv/**/*",+ "!__pycache__/**/*",+ "!**/build/**/*",+ "!**/*.pyd",+ "!**/*.egg-info/**/*"+ ]+ },+ {+ "from": "out/builtin-extensions",+ "to": "builtin-extensions"+ }+ ],+ "publish": {+ "provider": "github",+ "owner": "lightningpixel",+ "repo": "modly"+ },+ "nsis": {+ "oneClick": false,+ "allowToChangeInstallationDirectory": true+ },+ "win": {+ "target": "nsis",+ "artifactName": "${productName}-Setup-${version}.${ext}",+ "icon": "resources/icons/icon.ico",+ "extraResources": [+ {+ "from": "resources/python-embed",+ "to": "python-embed"+ }+ ]+ },+ "mac": {+ "target": "dmg",+ "icon": "resources/icons/icon.icns",+ "artifactName": "${productName}-${version}-arm64.${ext}",+ "identity": null,+ "category": "public.app-category.graphics-design",+ "extraResources": [+ {+ "from": "resources/python-embed",+ "to": "python-embed"+ }+ ]+ },+ "linux": {+ "target": "AppImage",+ "icon": "resources/icons/icon.png",+ "extraResources": [+ {+ "from": "resources/python-embed",+ "to": "python-embed"+ }+ ]+ }+ }+}diff --git a/apps/forge-desktop/postcss.config.js b/apps/forge-desktop/postcss.config.jsnew file mode 100644index 000000000..85f717cc0--- /dev/null+++ b/apps/forge-desktop/postcss.config.js@@ -0,0 +1,6 @@+module.exports = {+ plugins: {+ tailwindcss: {},+ autoprefixer: {}+ }+}diff --git a/apps/forge-desktop/resources/icons/icon.icns b/apps/forge-desktop/resources/icons/icon.icnsnew file mode 100644index 000000000..05dc19f06Binary files /dev/null and b/apps/forge-desktop/resources/icons/icon.icns differdiff --git a/apps/forge-desktop/resources/icons/icon.ico b/apps/forge-desktop/resources/icons/icon.iconew file mode 100644index 000000000..701edb593Binary files /dev/null and b/apps/forge-desktop/resources/icons/icon.ico differdiff --git a/apps/forge-desktop/resources/icons/icon.png b/apps/forge-desktop/resources/icons/icon.pngnew file mode 100644index 000000000..601d84f05Binary files /dev/null and b/apps/forge-desktop/resources/icons/icon.png differdiff --git a/apps/forge-desktop/resources/screenshots/helper.png b/apps/forge-desktop/resources/screenshots/helper.pngnew file mode 100644index 000000000..599fc28b3Binary files /dev/null and b/apps/forge-desktop/resources/screenshots/helper.png differdiff --git a/apps/forge-desktop/scripts/after-pack.js b/apps/forge-desktop/scripts/after-pack.jsnew file mode 100644index 000000000..37faeca02--- /dev/null+++ b/apps/forge-desktop/scripts/after-pack.js@@ -0,0 +1,41 @@+// @ts-check+// Signature ad-hoc du bundle macOS.+//+// Sans licence Apple Developer (99 $/an) on ne peut ni signer avec un Developer+// ID ni notariser. Mais sur Apple Silicon, un binaire SANS AUCUNE signature+// refuse de se lancer (ce n'est pas un simple avertissement Gatekeeper).+// La signature ad-hoc (`--sign -`) est gratuite et lève ce blocage.+//+// Ce hook tourne APRÈS le packaging et AVANT la fabrication du DMG, donc la+// signature est bien embarquée dans l'app distribuée. Comme `identity: null`+// désactive la signature interne d'electron-builder, rien ne l'écrase ensuite.+//+// L'utilisateur verra quand même Gatekeeper au premier lancement+// ("développeur non vérifié") : clic droit > Ouvrir, ou `xattr -cr` sur l'app.++const path = require('path')+const { execFileSync } = require('child_process')++exports.default = async function afterPack(context) {+ if (context.electronPlatformName !== 'darwin') return++ const appPath = path.join(+ context.appOutDir,+ `${context.packager.appInfo.productFilename}.app`+ )++ // --deep est déprécié par Apple pour la signature réelle, mais reste la façon+ // standard d'ad-hoc signer récursivement les binaires imbriqués (Electron+ // Framework, helpers). Échouer ici doit casser le build : un DMG arm64 non+ // signé ne se lance pas, autant le savoir en CI plutôt que chez l'utilisateur.+ execFileSync('codesign', ['--force', '--deep', '--sign', '-', appPath], {+ stdio: 'inherit'+ })++ // Vérifie que la signature est bien posée et que l'app est jugée valide.+ execFileSync('codesign', ['--verify', '--verbose=2', appPath], {+ stdio: 'inherit'+ })++ console.log(`[after-pack] Signature ad-hoc appliquée : ${appPath}`)+}diff --git a/apps/forge-desktop/scripts/build-builtins.mjs b/apps/forge-desktop/scripts/build-builtins.mjsnew file mode 100644index 000000000..2e9048854--- /dev/null+++ b/apps/forge-desktop/scripts/build-builtins.mjs@@ -0,0 +1,62 @@+/**+ * Compile built-in extensions (TypeScript → CommonJS JS) and copy manifests.+ * Output: out/builtin-extensions/{id}/processor.js + manifest.json+ */++import { execSync } from 'child_process'+import { readdirSync, existsSync, cpSync, mkdirSync, statSync } from 'fs'+import { join, dirname } from 'path'+import { fileURLToPath } from 'url'++const root = join(dirname(fileURLToPath(import.meta.url)), '..')+const srcDir = join(root, 'src', 'areas', 'workflows', 'nodes')+const outDir = join(root, 'out', 'builtin-extensions')++if (!existsSync(srcDir)) {+ console.log('[build-builtins] No builtin-extensions directory found, skipping.')+ process.exit(0)+}++// 1. Compile TypeScript+console.log('[build-builtins] Compiling TypeScript…')+execSync('npx tsc -p tsconfig.builtins.json', { cwd: root, stdio: 'inherit' })++// 2. Copy manifest.json, and optionally package.json + npm install+for (const id of readdirSync(srcDir)) {+ const extSrcDir = join(srcDir, id)+ if (!statSync(extSrcDir).isDirectory()) continue+ // Only process extension folders (those with a manifest.json)+ if (!existsSync(join(extSrcDir, 'manifest.json'))) continue++ const extOutDir = join(outDir, id)+ mkdirSync(extOutDir, { recursive: true })++ const manifestSrc = join(extSrcDir, 'manifest.json')+ if (existsSync(manifestSrc)) {+ cpSync(manifestSrc, join(extOutDir, 'manifest.json'))+ console.log(`[build-builtins] ${id}: manifest.json copied`)+ } else {+ console.warn(`[build-builtins] ${id}: manifest.json missing — skipping`)+ }++ const pkgSrc = join(extSrcDir, 'package.json')+ if (existsSync(pkgSrc)) {+ cpSync(pkgSrc, join(extOutDir, 'package.json'))+ console.log(`[build-builtins] ${id}: Installing npm dependencies…`)+ execSync('npm install --omit=dev --no-audit --no-fund --ignore-scripts=false', {+ cwd: extOutDir,+ stdio: 'inherit',+ })+ console.log(`[build-builtins] ${id}: npm install done`)+ }++ // Copy any Python processor files+ for (const file of readdirSync(extSrcDir)) {+ if (file.endsWith('.py')) {+ cpSync(join(extSrcDir, file), join(extOutDir, file))+ console.log(`[build-builtins] ${id}: ${file} copied`)+ }+ }+}++console.log('[build-builtins] Done.')diff --git a/apps/forge-desktop/scripts/download-python-embed.js b/apps/forge-desktop/scripts/download-python-embed.jsnew file mode 100644index 000000000..25cbd011b--- /dev/null+++ b/apps/forge-desktop/scripts/download-python-embed.js@@ -0,0 +1,100 @@+// @ts-check+const https = require('https')+const fs = require('fs')+const path = require('path')+const { execSync } = require('child_process')++const RESOURCES_DIR = path.join(__dirname, '..', 'resources')+const EMBED_DIR = path.join(RESOURCES_DIR, 'python-embed')++// python-build-standalone provides a full Python installation (includes venv + pip)+// Used for ALL platforms — consistent behavior, no stripped-down embed issues.+const PBS_VERSION = '3.11.9'+const PBS_RELEASE = '20240726'++function getPbsUrl() {+ const arch = process.arch === 'arm64' ? 'aarch64' : 'x86_64'+ const triple = process.platform === 'win32'+ ? `${arch}-pc-windows-msvc`+ : process.platform === 'darwin'+ ? `${arch}-apple-darwin`+ : `${arch}-unknown-linux-gnu`+ return (+ `https://github.com/indygreg/python-build-standalone/releases/download/` ++ `${PBS_RELEASE}/cpython-${PBS_VERSION}+${PBS_RELEASE}-${triple}-install_only.tar.gz`+ )+}++// ── Helpers ───────────────────────────────────────────────────────────────────++function download(url, dest) {+ return new Promise((resolve, reject) => {+ console.log(`Downloading ${url} → ${dest}`)+ const file = fs.createWriteStream(dest)+ const request = (u) => {+ https.get(u, { headers: { 'User-Agent': 'modly-build' } }, (res) => {+ if (res.statusCode === 301 || res.statusCode === 302) {+ request(res.headers.location)+ return+ }+ if (res.statusCode !== 200) {+ reject(new Error(`HTTP ${res.statusCode} for ${u}`))+ return+ }+ const total = parseInt(res.headers['content-length'] || '0', 10)+ let received = 0+ res.on('data', (chunk) => {+ received += chunk.length+ if (total > 0) {+ const pct = Math.round((received / total) * 100)+ process.stdout.write(`\r ${pct}% (${Math.round(received / 1024 / 1024)} MB)`)+ }+ })+ res.pipe(file)+ res.on('end', () => {+ process.stdout.write('\n')+ file.close(() => resolve())+ })+ }).on('error', reject)+ }+ request(url)+ file.on('error', reject)+ })+}++function extractTar(tarPath, destDir) {+ console.log(`Extracting ${tarPath} → ${destDir}`)+ fs.mkdirSync(destDir, { recursive: true })+ // --strip-components=1 removes the top-level "python/" directory from the archive+ execSync(`tar -xzf "${tarPath}" --strip-components=1 -C "${destDir}"`, { stdio: 'inherit' })+ if (process.platform === 'darwin') {+ try { execSync(`xattr -cr "${destDir}"`) } catch {}+ }+}++// ── Main ──────────────────────────────────────────────────────────────────────++async function main() {+ fs.mkdirSync(RESOURCES_DIR, { recursive: true })++ const pythonExe = process.platform === 'win32'+ ? path.join(EMBED_DIR, 'python.exe')+ : path.join(EMBED_DIR, 'bin', 'python3')++ if (fs.existsSync(pythonExe)) {+ console.log('python-embed already present, skipping.')+ return+ }++ const tarUrl = getPbsUrl()+ const tarTmp = path.join(RESOURCES_DIR, 'python-embed.tar.gz')+ await download(tarUrl, tarTmp)+ extractTar(tarTmp, EMBED_DIR)+ fs.unlinkSync(tarTmp)+ console.log('Done. Python standalone extracted.')+}++main().catch((err) => {+ console.error('ERROR:', err.message)+ process.exit(1)+})diff --git a/apps/forge-desktop/scripts/node-ts-extensionless-loader.mjs b/apps/forge-desktop/scripts/node-ts-extensionless-loader.mjsnew file mode 100644index 000000000..b91649003--- /dev/null+++ b/apps/forge-desktop/scripts/node-ts-extensionless-loader.mjs@@ -0,0 +1,14 @@+export async function resolve(specifier, context, nextResolve) {+ try {+ return await nextResolve(specifier, context)+ } catch (error) {+ if (!shouldRetryWithTypeScriptExtension(specifier, error)) throw error+ return nextResolve(`${specifier}.ts`, context)+ }+}++function shouldRetryWithTypeScriptExtension(specifier, error) {+ return error?.code === 'ERR_MODULE_NOT_FOUND'+ && (specifier.startsWith('./') || specifier.startsWith('../'))+ && !specifier.endsWith('.ts')+}diff --git a/apps/forge-desktop/scripts/react-test-env.mjs b/apps/forge-desktop/scripts/react-test-env.mjsnew file mode 100644index 000000000..d2bd8d2e9--- /dev/null+++ b/apps/forge-desktop/scripts/react-test-env.mjs@@ -0,0 +1,103 @@+/**+ * Minimal React test environment for `node --test`.+ *+ * The repo tests everything except the UI layer, which is exactly where the+ * bugs the user actually sees have come from: a hook returning a fresh callback+ * on every render made a modal re-run its effect forever, flickering and+ * hammering the API. That class of bug is invisible to a type-checker and to+ * store-level tests — it only exists once a component renders more than once.+ *+ * Deliberately built on jsdom + react-dom directly rather than a testing+ * library: what we need is "render, re-render, count the effects", not queries+ * and user events.+ */+import { JSDOM } from 'jsdom'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'+import { join, resolve } from 'node:path'++/** Install a DOM into the globals React expects. Call once, at module scope. */+export function setupDom() {+ const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/' })+ const { window } = dom++ // Node 24 defines some of these (`navigator`) as getter-only on globalThis,+ // so a plain assignment throws — go through defineProperty for all of them.+ const define = (name, value) =>+ Object.defineProperty(globalThis, name, { value, writable: true, configurable: true })++ define('window', window)+ define('document', window.document)+ define('navigator', window.navigator)+ define('localStorage', window.localStorage)+ define('requestAnimationFrame', (cb) => setTimeout(() => cb(Date.now()), 0))+ define('cancelAnimationFrame', (id) => clearTimeout(id))+ // React 18 refuses to run `act` without it, and warns on every update.+ define('IS_REACT_ACT_ENVIRONMENT', true)+ for (const name of ['HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'getComputedStyle']) {+ define(name, window[name])+ }+ return dom+}++/**+ * Bundle a source module and load it as CommonJS.+ *+ * `react` and `react-dom` stay external so the module under test and the test+ * file share one React instance — two copies produce "invalid hook call",+ * which reads as a bug in the code under test and is not one.+ */+export function loadModule(entryPath) {+ // Inside the project, not the system temp dir: the bundle keeps `react` as a+ // bare require, and that only resolves from a path under this node_modules.+ const cacheRoot = resolve('node_modules/.cache/modly-react-tests')+ mkdirSync(cacheRoot, { recursive: true })+ const outfile = join(mkdtempSync(join(cacheRoot, 'm-')), 'module.cjs')+ const result = buildSync({+ entryPoints: [resolve(entryPath)],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ jsx: 'automatic',+ external: ['react', 'react-dom', 'react-dom/client', 'react/jsx-runtime'],+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return createRequire(import.meta.url)(outfile)+}++/**+ * Render `element`, and hand back a way to re-render it with the same root —+ * which is the whole point: a hook that misbehaves does so on the SECOND render.+ */+export async function mount(element) {+ const require = createRequire(import.meta.url)+ const { createRoot } = require('react-dom/client')+ const { act } = require('react-dom/test-utils')+ const { cloneElement } = require('react')++ // Through globalThis: these are globals this module installed itself in+ // setupDom(), not ambient browser ones.+ const container = globalThis.document.createElement('div')+ globalThis.document.body.appendChild(container)+ const root = createRoot(container)++ await act(async () => { root.render(element) })++ return {+ container,+ /** Re-render. The element is cloned by default: handed the very same+ * element object, React bails out and nothing re-renders — which silently+ * turns a re-render test into a no-op. */+ rerender: async (next) => {+ await act(async () => { root.render(next ?? cloneElement(element)) })+ },+ /** Let effects, promises and state updates settle. */+ flush: async () => { await act(async () => { await Promise.resolve() }) },+ unmount: async () => {+ await act(async () => { root.unmount() })+ container.remove()+ },+ }+}diff --git a/apps/forge-desktop/scripts/run-pytests.mjs b/apps/forge-desktop/scripts/run-pytests.mjsnew file mode 100644index 000000000..acb1e72f5--- /dev/null+++ b/apps/forge-desktop/scripts/run-pytests.mjs@@ -0,0 +1,37 @@+// Portable Python test runner.+// `python3` is the macOS/Linux name but does not exist on Windows (where the+// interpreter is `python` or the `py` launcher). Try each candidate until one+// actually runs, then forward unittest's exit code.+import { spawnSync } from 'node:child_process'+import { fileURLToPath } from 'node:url'+import { dirname, join } from 'node:path'++const apiDir = join(dirname(fileURLToPath(import.meta.url)), '..', 'api')++const candidates = [+ ['python3', []],+ ['python', []],+ ['py', ['-3']],+]++function works(cmd, prefix) {+ try {+ const r = spawnSync(cmd, [...prefix, '--version'], { stdio: 'ignore' })+ return r.status === 0+ } catch {+ return false+ }+}++const found = candidates.find(([cmd, prefix]) => works(cmd, prefix))+if (!found) {+ console.error('[run-pytests] No Python interpreter found (tried python3, python, py -3).')+ process.exit(1)+}++const [cmd, prefix] = found+const result = spawnSync(cmd, [...prefix, '-m', 'unittest', 'discover', '-s', 'tests'], {+ cwd: apiDir,+ stdio: 'inherit',+})+process.exit(result.status ?? 1)diff --git a/apps/forge-desktop/src/App.tsx b/apps/forge-desktop/src/App.tsxnew file mode 100644index 000000000..2de172243--- /dev/null+++ b/apps/forge-desktop/src/App.tsx@@ -0,0 +1,71 @@+import { useEffect, useLayoutEffect, useState } from 'react'+import { useAppStore, type UiScale } from '@shared/stores/appStore'+import FirstRunSetup from '@areas/setup/FirstRunSetup'+import MainLayout from '@shared/components/layout/MainLayout'+import { UpdateModal } from '@shared/components/ui/UpdateModal'+import { ErrorModal } from '@shared/components/ui/ErrorModal'+import { Toast } from '@shared/components/ui/Toast'++const UI_SCALE_FACTORS: Record<UiScale, number> = { small: 0.875, medium: 1, large: 1.25, 'very-large': 1.5 }++export default function App(): JSX.Element {+ const { checkSetup, setupStatus, initApp, backendStatus, showError, useAtkinsonFont, uiScale } = useAppStore()+ const [updateVersion, setUpdateVersion] = useState<string | null>(null)+ const [currentVersion, setCurrentVersion] = useState<string>('')++ useEffect(() => {+ checkSetup()+ window.electron.app.onError((message) => showError(message))+ window.electron.updater.onMajorMinorAvailable(({ version }) => {+ setUpdateVersion(`v${version}`)+ })+ return () => {+ window.electron.app.offError()+ window.electron.updater.offMajorMinorAvailable()+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps -- run once on mount; store actions are stable+ }, [])++ // Apply before paint to avoid a flash of default font/size on launch.+ useLayoutEffect(() => {+ document.documentElement.style.setProperty(+ '--app-font',+ useAtkinsonFont+ ? "'Atkinson Hyperlegible', system-ui, sans-serif"+ : "'Inter', system-ui, sans-serif"+ )+ window.electron.ui.setZoomFactor(UI_SCALE_FACTORS[uiScale])+ }, [useAtkinsonFont, uiScale])++ useEffect(() => {+ if (setupStatus === 'done') initApp()+ // eslint-disable-next-line react-hooks/exhaustive-deps -- react to setup transition only; initApp is stable+ }, [setupStatus])++ useEffect(() => {+ if (backendStatus !== 'ready') return+ window.electron.app.info().then(({ version }) => setCurrentVersion(version))+ }, [backendStatus])++ if (backendStatus === 'ready') return (+ <>+ <MainLayout />+ {updateVersion && (+ <UpdateModal+ currentVersion={currentVersion}+ latestVersion={updateVersion}+ onDismiss={() => setUpdateVersion(null)}+ />+ )}+ <Toast />+ <ErrorModal />+ </>+ )+ return (+ <>+ <FirstRunSetup />+ <Toast />+ <ErrorModal />+ </>+ )+}diff --git a/apps/forge-desktop/src/areas/generate/GeneratePage.tsx b/apps/forge-desktop/src/areas/generate/GeneratePage.tsxnew file mode 100644index 000000000..76a131199--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/GeneratePage.tsx@@ -0,0 +1,1278 @@+import { useState, useRef, useCallback, useEffect, useMemo } from 'react'+import type { ReactNode } from 'react'+import { useAppStore, DEFAULT_LIGHT_SETTINGS } from '@shared/stores/appStore'+import type { GenerationJob, LightSettings, PointLight } from '@shared/stores/appStore'+import { useApi } from '@shared/hooks/useApi'+import { ColorPicker } from '@shared/components/ui'+import GenerationHUD from './components/GenerationHUD'+import Viewer3D from './components/Viewer3D'+import WorkflowPanel from './components/WorkflowPanel'+import { getDefaultAssetLibraryService } from './assetLibraryService'+import { buildOrcaSlicerDeepLink, canOpenInOrcaSlicer } from './orcaSlicerLink'+import { resolveAssetLibraryOpenTarget, type ProjectedAssetLibraryEntry } from './assetLibraryProjection'+import {+ ASSET_LIBRARY_SORT_OPTIONS,+ buildAssetLibraryOpenRequest,+ createAssetLibraryOpenJob,+ describeAssetLibraryOpenability,+ filterAssetLibraryScopeGroups,+ getDefaultAssetLibraryCollapsedSectionKeys,+ isAssetLibraryEntryOpenable,+ resolveOpenPanelAfterLibrarySelection,+ toggleAssetLibrarySectionKey,+ type AssetLibrarySortMode,+ type GenerateOpenPanel,+} from './assetLibraryUi'++const MIN_WIDTH = 220+const MAX_WIDTH = 520+const DEFAULT_WIDTH = 320++const MAX_POINT_LIGHTS = 6++function createPointLight(): PointLight {+ const angle = Math.random() * Math.PI * 2+ return {+ id: crypto.randomUUID(),+ position: [Math.cos(angle) * 1.5, 0.5, Math.sin(angle) * 1.5],+ color: '#ffffff',+ intensity: 1,+ }+}++// ---------------------------------------------------------------------------+// Export dropdown+// ---------------------------------------------------------------------------++const EXPORT_FORMATS = [+ { fmt: 'glb' as const, desc: 'Binary glTF' },+ { fmt: 'obj' as const, desc: 'Wavefront' },+ { fmt: 'stl' as const, desc: '3D Print' },+ { fmt: 'ply' as const, desc: 'Polygon File' },+]++function ExportDropdown({+ onExport,+ onClose,+ onOpenInSlicer,+ canOpenInSlicer,+}: {+ onExport: (f: 'glb' | 'obj' | 'stl' | 'ply') => void+ onClose: () => void+ onOpenInSlicer: () => void+ canOpenInSlicer: boolean+}) {+ return (+ <div className="absolute top-full left-0 mt-1 z-50 bg-zinc-900 border border-zinc-700/60 rounded-xl p-1 flex flex-col gap-0.5 min-w-[150px] shadow-xl">+ {EXPORT_FORMATS.map(({ fmt, desc }) => (+ <button+ key={fmt}+ onClick={() => { onExport(fmt); onClose() }}+ className="px-3 py-2 text-left hover:bg-zinc-800 rounded-lg transition-colors flex items-center gap-2.5"+ >+ <span className="text-xs font-mono font-semibold text-zinc-200">.{fmt}</span>+ <span className="text-[10px] text-zinc-500">{desc}</span>+ </button>+ ))}+ {canOpenInSlicer && (+ <>+ <div className="my-1 h-px bg-zinc-700/60" />+ <button+ onClick={() => { onOpenInSlicer(); onClose() }}+ title="Convert to STL and open in OrcaSlicer"+ className="px-3 py-2 text-left hover:bg-zinc-800 rounded-lg transition-colors flex items-center gap-2.5"+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" className="text-zinc-400 shrink-0">+ <path d="M15 3h6v6" />+ <path d="M10 14 21 3" />+ <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />+ </svg>+ <span className="text-xs text-zinc-200 whitespace-nowrap">Open in OrcaSlicer</span>+ </button>+ </>+ )}+ </div>+ )+}++// ---------------------------------------------------------------------------+// ToolButton — icon-only toolbar button with tooltip + active state+// ---------------------------------------------------------------------------++function ToolButton({+ label,+ active,+ onClick,+ children,+}: {+ label: string+ active: boolean+ onClick: () => void+ children: ReactNode+}) {+ return (+ <button+ onClick={onClick}+ title={label}+ aria-label={label}+ aria-pressed={active}+ className={`flex items-center justify-center w-7 h-7 rounded-lg border transition-colors+ ${active+ ? 'bg-zinc-700 border-zinc-600 text-zinc-200'+ : 'bg-zinc-800 border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600'+ }`}+ >+ {children}+ </button>+ )+}++// ---------------------------------------------------------------------------+// Decimate popover+// ---------------------------------------------------------------------------++function DecimatePopover({+ currentTriangles,+ decimating,+ onDecimate,+ onClose,+}: {+ currentTriangles: number | null+ decimating: boolean+ onDecimate: (targetFaces: number) => void+ onClose: () => void+}) {+ const defaultTarget = currentTriangles ? Math.round(currentTriangles * 0.5) : 5000+ const [inputValue, setInputValue] = useState(String(defaultTarget))++ const parsed = parseInt(inputValue, 10)+ const validTarget = !isNaN(parsed) && parsed >= 100 ? parsed : null+ const reduction =+ currentTriangles && validTarget+ ? Math.round((1 - Math.min(validTarget, currentTriangles) / currentTriangles) * 100)+ : null++ return (+ <div className="absolute top-full left-0 mt-1 z-50 bg-zinc-900 border border-zinc-700/60 rounded-xl p-3 flex flex-col gap-3 min-w-[200px] shadow-xl">+ <p className="text-[10px] text-zinc-500 uppercase tracking-wider">Decimate mesh</p>++ {currentTriangles && (+ <p className="text-[10px] text-zinc-500">+ Current: <span className="text-zinc-300">{currentTriangles.toLocaleString()} tri</span>+ </p>+ )}++ <div className="flex flex-col gap-1.5">+ <label className="text-[10px] text-zinc-500">Target faces</label>+ <input+ type="number"+ value={inputValue}+ onChange={(e) => setInputValue(e.target.value)}+ min={100}+ step={500}+ className="bg-zinc-800 border border-zinc-700 rounded-lg px-2.5 py-1.5 text-xs text-zinc-200 w-full focus:outline-none focus:border-violet-500 transition-colors"+ />+ {reduction !== null && (+ <p className="text-[10px] text-zinc-500">+ Reduction: <span className="text-violet-400">{reduction}%</span>+ </p>+ )}+ </div>++ <div className="flex gap-2">+ <button+ onClick={onClose}+ className="flex-1 px-3 py-1.5 text-xs text-zinc-400 hover:text-zinc-200 bg-zinc-800 hover:bg-zinc-700 rounded-lg transition-colors"+ >+ Cancel+ </button>+ <button+ onClick={() => validTarget && onDecimate(validTarget)}+ disabled={decimating || !validTarget}+ className="flex-1 px-3 py-1.5 bg-violet-600 hover:bg-violet-500 disabled:bg-zinc-700 disabled:text-zinc-500 text-white text-xs rounded-lg transition-colors flex items-center justify-center gap-1.5 font-medium"+ >+ {decimating ? (+ <>+ <svg className="animate-spin" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <path d="M21 12a9 9 0 1 1-6.219-8.56" />+ </svg>+ Processing…+ </>+ ) : 'Apply'}+ </button>+ </div>+ </div>+ )+}++// ---------------------------------------------------------------------------+// Light popover+// ---------------------------------------------------------------------------++function LightPopover({+ settings,+ onChange,+ onClose,+ pointLights,+ onPointLightsChange,+ selectedPointLightId,+ onSelectPointLight,+}: {+ settings: LightSettings+ onChange: (s: LightSettings) => void+ onClose: () => void+ pointLights: PointLight[]+ onPointLightsChange: (lights: PointLight[]) => void+ selectedPointLightId: string | null+ onSelectPointLight: (id: string | null) => void+}) {+ function lightRow(+ label: string,+ colorKey: keyof LightSettings,+ intensityKey: keyof LightSettings,+ max: number,+ ) {+ const intensity = settings[intensityKey] as number+ const color = settings[colorKey] as string+ return (+ <div className="flex flex-col gap-1.5">+ <div className="flex items-center gap-2">+ <ColorPicker+ value={color}+ onChange={(c) => onChange({ ...settings, [colorKey]: c })}+ />+ <span className="text-[10px] text-zinc-400 flex-1">{label}</span>+ <span className="text-[10px] text-zinc-500 font-mono">{intensity.toFixed(1)}</span>+ </div>+ <input+ type="range"+ min={0}+ max={max}+ step={0.1}+ value={intensity}+ onChange={(e) => onChange({ ...settings, [intensityKey]: parseFloat(e.target.value) })}+ className="w-full h-1.5 accent-violet-500 cursor-pointer"+ />+ </div>+ )+ }++ function plainRow(label: string, intensityKey: keyof LightSettings, max: number) {+ const value = (settings[intensityKey] as number) ?? (DEFAULT_LIGHT_SETTINGS[intensityKey] as number)+ return (+ <div className="flex flex-col gap-1.5">+ <div className="flex items-center gap-2">+ <span className="text-[10px] text-zinc-400 flex-1">{label}</span>+ <span className="text-[10px] text-zinc-500 font-mono">{value.toFixed(2)}</span>+ </div>+ <input+ type="range"+ min={0}+ max={max}+ step={0.05}+ value={value}+ onChange={(e) => onChange({ ...settings, [intensityKey]: parseFloat(e.target.value) })}+ className="w-full h-1.5 accent-violet-500 cursor-pointer"+ />+ </div>+ )+ }++ return (+ <div className="absolute top-full right-0 mt-1 z-50 bg-zinc-900 border border-zinc-700/60 rounded-xl p-3 flex flex-col gap-3 min-w-[220px] shadow-xl">+ <div className="flex items-center justify-between">+ <p className="text-[10px] text-zinc-500 uppercase tracking-wider">Lighting</p>+ <button+ onClick={() => onChange(DEFAULT_LIGHT_SETTINGS)}+ className="text-[10px] text-zinc-600 hover:text-zinc-400 transition-colors"+ >+ Reset+ </button>+ </div>+ {lightRow('Sun', 'mainColor', 'mainIntensity', 4)}+ {lightRow('Fill', 'fillColor', 'fillIntensity', 2)}+ {plainRow('Ambient', 'ambientIntensity', 1.5)}+ {plainRow('Environment', 'envIntensity', 2)}++ {/* ── Point lights ── */}+ <div className="border-t border-zinc-800 pt-2 mt-1 flex flex-col gap-2">+ <div className="flex items-center justify-between">+ <p className="text-[10px] text-zinc-500 uppercase tracking-wider">Point lights</p>+ {pointLights.length < MAX_POINT_LIGHTS && (+ <button+ onClick={() => onPointLightsChange([...pointLights, createPointLight()])}+ className="flex items-center gap-1 py-0.5 px-1.5 rounded text-[10px] text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800 transition-colors"+ >+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>+ </svg>+ Add+ </button>+ )}+ </div>++ {pointLights.length === 0 && (+ <p className="text-[10px] text-zinc-600 italic">No point lights yet.</p>+ )}++ {pointLights.map((pl) => (+ <div+ key={pl.id}+ onClick={() => onSelectPointLight(pl.id)}+ className={`flex flex-col gap-1.5 p-2 rounded-lg bg-zinc-800/40 border cursor-pointer transition-colors ${+ pl.id === selectedPointLightId+ ? 'border-violet-500'+ : 'border-zinc-700/40 hover:border-zinc-600'+ }`}+ >+ <div className="flex items-center gap-2">+ <ColorPicker+ value={pl.color}+ onChange={(c) => onPointLightsChange(pointLights.map((p) => p.id === pl.id ? { ...p, color: c } : p))}+ />+ <span className="text-[10px] text-zinc-400 flex-1">Point</span>+ <span className="text-[10px] text-zinc-500 font-mono">{pl.intensity.toFixed(1)}</span>+ <button+ onClick={(e) => {+ e.stopPropagation()+ onPointLightsChange(pointLights.filter((p) => p.id !== pl.id))+ }}+ className="p-0.5 rounded text-zinc-600 hover:text-red-400 transition-colors"+ >+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>+ </svg>+ </button>+ </div>+ <input type="range" min={0} max={16} step={0.1} value={pl.intensity}+ onChange={(e) => onPointLightsChange(pointLights.map((p) => p.id === pl.id ? { ...p, intensity: parseFloat(e.target.value) } : p))}+ className="w-full h-1.5 accent-violet-500 cursor-pointer" />+ </div>+ ))}+ </div>++ <button+ onClick={onClose}+ className="mt-1 px-3 py-1.5 text-xs text-zinc-400 hover:text-zinc-200 bg-zinc-800 hover:bg-zinc-700 rounded-lg transition-colors"+ >+ Close+ </button>+ </div>+ )+}++// ---------------------------------------------------------------------------+// Smooth popover+// ---------------------------------------------------------------------------++function SmoothPopover({+ smoothing,+ onSmooth,+ onClose,+}: {+ smoothing: boolean+ onSmooth: (iterations: number) => void+ onClose: () => void+}) {+ const [inputValue, setInputValue] = useState('3')++ const parsed = parseInt(inputValue, 10)+ const valid = !isNaN(parsed) && parsed >= 1 && parsed <= 20++ return (+ <div className="absolute top-full left-0 mt-1 z-50 bg-zinc-900 border border-zinc-700/60 rounded-xl p-3 flex flex-col gap-3 min-w-[190px] shadow-xl">+ <p className="text-[10px] text-zinc-500 uppercase tracking-wider">Smooth mesh</p>++ <div className="flex flex-col gap-1.5">+ <label className="text-[10px] text-zinc-500">Iterations <span className="text-zinc-600">(1–20)</span></label>+ <input+ type="number"+ value={inputValue}+ onChange={(e) => setInputValue(e.target.value)}+ min={1}+ max={20}+ step={1}+ className="bg-zinc-800 border border-zinc-700 rounded-lg px-2.5 py-1.5 text-xs text-zinc-200 w-full focus:outline-none focus:border-violet-500 transition-colors"+ />+ <p className="text-[10px] text-zinc-600">More iterations = smoother, but loses detail</p>+ </div>++ <div className="flex gap-2">+ <button+ onClick={onClose}+ className="flex-1 px-3 py-1.5 text-xs text-zinc-400 hover:text-zinc-200 bg-zinc-800 hover:bg-zinc-700 rounded-lg transition-colors"+ >+ Cancel+ </button>+ <button+ onClick={() => valid && onSmooth(parsed)}+ disabled={smoothing || !valid}+ className="flex-1 px-3 py-1.5 bg-violet-600 hover:bg-violet-500 disabled:bg-zinc-700 disabled:text-zinc-500 text-white text-xs rounded-lg transition-colors flex items-center justify-center gap-1.5 font-medium"+ >+ {smoothing ? (+ <>+ <svg className="animate-spin" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <path d="M21 12a9 9 0 1 1-6.219-8.56" />+ </svg>+ Processing…+ </>+ ) : 'Apply'}+ </button>+ </div>+ </div>+ )+}++// ---------------------------------------------------------------------------+// Workspace library popover+// ---------------------------------------------------------------------------++function AssetLibraryToggleButton({+ open,+ disabled,+ onToggle,+}: {+ open: boolean+ disabled: boolean+ onToggle: () => void+}) {+ return (+ <button+ type="button"+ onClick={onToggle}+ disabled={disabled}+ aria-haspopup="dialog"+ aria-expanded={open}+ className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-medium border transition-colors disabled:opacity-50 disabled:pointer-events-none+ ${open+ ? 'bg-zinc-700 border-zinc-600 text-zinc-200'+ : 'bg-zinc-800 border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600'+ }`}+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden="true">+ <path d="M4 6h16" />+ <path d="M4 12h16" />+ <path d="M4 18h10" />+ </svg>+ Library+ </button>+ )+}++function AssetLibraryPopover({+ entries,+ selectedEntryId,+ loading,+ opening,+ error,+ searchQuery,+ sortMode,+ collapsedSectionKeys,+ onSelectEntry,+ onSearchQueryChange,+ onSortModeChange,+ onToggleSection,+ onOpenSelected,+ onRefresh,+ onClose,+}: {+ entries: ProjectedAssetLibraryEntry[]+ selectedEntryId: string | null+ loading: boolean+ opening: boolean+ error: string | null+ searchQuery: string+ sortMode: AssetLibrarySortMode+ collapsedSectionKeys: string[]+ onSelectEntry: (entryId: string) => void+ onSearchQueryChange: (value: string) => void+ onSortModeChange: (value: AssetLibrarySortMode) => void+ onToggleSection: (sectionKey: string) => void+ onOpenSelected: () => void+ onRefresh: () => void+ onClose: () => void+}) {+ const scopeGroups = filterAssetLibraryScopeGroups(entries, searchQuery, sortMode)+ const visibleEntryIds = new Set(scopeGroups.flatMap((scopeGroup) => scopeGroup.entryGroups.flatMap((group) => group.entries.map((entry) => entry.id))))+ const selectedEntry = selectedEntryId && visibleEntryIds.has(selectedEntryId)+ ? entries.find((entry) => entry.id === selectedEntryId) ?? null+ : null+ const normalizedSearchQuery = searchQuery.trim()+ const openDisabled = !selectedEntry || !isAssetLibraryEntryOpenable(selectedEntry) || loading || opening+ const selectedMessage = selectedEntry+ ? describeAssetLibraryOpenability(selectedEntry)+ : scopeGroups.length === 0 && normalizedSearchQuery+ ? `No workspace assets match “${normalizedSearchQuery}”.`+ : 'Select an asset to open it in Generate.'++ return (+ <div+ role="dialog"+ aria-label="Workspace library"+ className="absolute top-full left-0 mt-1 z-50 w-[320px] max-w-[calc(100vw-2rem)] bg-zinc-900 border border-zinc-700/60 rounded-xl p-3 flex flex-col gap-3 shadow-xl"+ >+ <div className="flex items-center justify-between gap-2">+ <div>+ <p className="text-[10px] text-zinc-500 uppercase tracking-wider">Workspace library</p>+ <p className="text-xs text-zinc-300">Select a workspace asset and open the supported source in Generate.</p>+ </div>+ <button+ type="button"+ onClick={onClose}+ className="px-2 py-1 text-[11px] text-zinc-400 hover:text-zinc-200 bg-zinc-800 hover:bg-zinc-700 rounded-lg transition-colors"+ >+ Close library+ </button>+ </div>++ <button+ type="button"+ onClick={onRefresh}+ disabled={loading || opening}+ className="self-start px-2.5 py-1.5 text-[11px] text-zinc-300 bg-zinc-800 hover:bg-zinc-700 disabled:opacity-50 disabled:pointer-events-none rounded-lg transition-colors"+ >+ Refresh assets+ </button>++ <div className="flex items-end gap-2">+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">+ <label htmlFor="asset-library-search" className="text-[11px] text-zinc-300">Search workspace assets</label>+ <input+ id="asset-library-search"+ type="search"+ value={searchQuery}+ onChange={(event) => onSearchQueryChange(event.target.value)}+ placeholder="Search by name, path, scope, or capability"+ className="bg-zinc-800 border border-zinc-700 rounded-lg px-2.5 py-1.5 text-xs text-zinc-200 w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-400"+ />+ </div>+ <div className="flex w-24 shrink-0 flex-col gap-1.5">+ <label htmlFor="asset-library-sort" className="text-[11px] text-zinc-300">Sort</label>+ <select+ id="asset-library-sort"+ value={sortMode}+ onChange={(event) => onSortModeChange(event.target.value as AssetLibrarySortMode)}+ className="bg-zinc-800 border border-zinc-700 rounded-lg px-2 py-1.5 text-xs text-zinc-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-400"+ >+ {ASSET_LIBRARY_SORT_OPTIONS.map((option) => (+ <option key={option.value} value={option.value}>{option.label}</option>+ ))}+ </select>+ </div>+ </div>++ {loading ? (+ <p role="status" className="text-xs text-zinc-400">Loading workspace assets…</p>+ ) : scopeGroups.length === 0 && !normalizedSearchQuery ? (+ <p role="status" className="text-xs text-zinc-500">No workspace assets are indexed yet.</p>+ ) : scopeGroups.length === 0 ? (+ <p role="status" className="text-xs text-zinc-500">{`No workspace assets match “${normalizedSearchQuery}”.`}</p>+ ) : (+ <div role="list" aria-label="Workspace library assets" className="max-h-64 overflow-y-auto rounded-lg border border-zinc-800 bg-zinc-950/40">+ {scopeGroups.map((scopeGroup) => {+ const scopeExpanded = !collapsedSectionKeys.includes(scopeGroup.sectionKey)+ const scopeRegionId = `asset-library-${scopeGroup.sectionKey.replace(/[^a-z0-9-]+/gi, '-')}`+ return (+ <section key={scopeGroup.sectionKey} role="group" aria-label={`Source scope ${scopeGroup.sourceScopeLabel}`} className="border-b border-zinc-800 last:border-b-0">+ <button+ type="button"+ aria-expanded={scopeExpanded}+ aria-controls={scopeRegionId}+ onClick={() => onToggleSection(scopeGroup.sectionKey)}+ className="flex w-full items-center justify-between gap-2 px-3 py-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-400"+ >+ <span className="text-[10px] font-semibold uppercase tracking-[0.18em] text-zinc-300">{scopeGroup.sourceScopeLabel}</span>+ <span className="text-[10px] text-zinc-500">{scopeExpanded ? 'Hide' : 'Show'}</span>+ </button>+ {scopeExpanded && (+ <div id={scopeRegionId}>+ {scopeGroup.entryGroups.map((group) => {+ const capabilityExpanded = !collapsedSectionKeys.includes(group.sectionKey)+ const capabilityRegionId = `asset-library-${group.sectionKey.replace(/[^a-z0-9-]+/gi, '-')}`+ return (+ <section key={group.sectionKey} role="group" aria-label={`Capability category ${group.capabilityLabel}`} className="border-t border-zinc-800 first:border-t-0">+ <button+ type="button"+ aria-expanded={capabilityExpanded}+ aria-controls={capabilityRegionId}+ onClick={() => onToggleSection(group.sectionKey)}+ className="flex w-full items-center justify-between gap-2 px-4 py-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-400"+ >+ <span className="text-[10px] font-semibold uppercase tracking-[0.18em] text-zinc-400">{group.capabilityLabel}</span>+ <span className="text-[10px] text-zinc-500">{capabilityExpanded ? 'Hide' : 'Show'}</span>+ </button>+ {capabilityExpanded && (+ <div id={capabilityRegionId}>+ {group.entries.map((entry) => {+ const selected = entry.id === selectedEntryId+ return (+ <button+ key={entry.id}+ type="button"+ role="listitem"+ aria-pressed={selected}+ aria-label={`Select library asset ${entry.displayName}`}+ onClick={() => onSelectEntry(entry.id)}+ className={`w-full text-left px-4 py-2 border-t border-zinc-800 first:border-t-0 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-400+ ${selected ? 'bg-violet-500/10 text-zinc-100' : 'text-zinc-300 hover:bg-zinc-800/80'}`}+ >+ <div className="flex items-center justify-between gap-2">+ <span className="text-xs font-medium">{entry.displayName}</span>+ <span className="text-[10px] uppercase tracking-wider text-zinc-500">{entry.capability ?? entry.state.replace(/-/g, ' ')}</span>+ </div>+ <p className="mt-1 truncate text-[10px] text-zinc-500">{entry.workspacePath}</p>+ </button>+ )+ })}+ </div>+ )}+ </section>+ )+ })}+ </div>+ )}+ </section>+ )+ })}+ </div>+ )}++ <div className="rounded-lg border border-zinc-800 bg-zinc-950/40 px-3 py-2">+ <p className="text-[11px] text-zinc-400">{selectedMessage}</p>+ {error && <p role="alert" className="mt-2 text-[11px] text-amber-300">{error}</p>}+ </div>++ <button+ type="button"+ onClick={onOpenSelected}+ disabled={openDisabled}+ aria-label="Open selected asset"+ className="px-3 py-2 bg-violet-600 hover:bg-violet-500 disabled:bg-zinc-700 disabled:text-zinc-500 text-white text-xs rounded-lg transition-colors font-medium"+ >+ {opening ? 'Opening…' : 'Open selected asset'}+ </button>+ </div>+ )+}++// ---------------------------------------------------------------------------+// GeneratePage+// ---------------------------------------------------------------------------++export default function GeneratePage(): JSX.Element {+ const [unloadStatus, setUnloadStatus] = useState<'idle' | 'done'>('idle')+ const [panelWidth, setPanelWidth] = useState(DEFAULT_WIDTH)+ const [openPanel, setOpenPanel] = useState<GenerateOpenPanel>(null)+ const [decimating, setDecimating] = useState(false)+ const [smoothing, setSmoothing] = useState(false)+ const [importing, setImporting] = useState(false)+ const [libraryEntries, setLibraryEntries] = useState<ProjectedAssetLibraryEntry[]>([])+ const [librarySelectedEntryId, setLibrarySelectedEntryId] = useState<string | null>(null)+ const [libraryLoaded, setLibraryLoaded] = useState(false)+ const [libraryLoading, setLibraryLoading] = useState(false)+ const [libraryOpening, setLibraryOpening] = useState(false)+ const [libraryError, setLibraryError] = useState<string | null>(null)+ const [librarySearchQuery, setLibrarySearchQuery] = useState('')+ const [librarySortMode, setLibrarySortMode] = useState<AssetLibrarySortMode>('type')+ const [libraryCollapsedSectionKeys, setLibraryCollapsedSectionKeys] = useState<string[]>(() => getDefaultAssetLibraryCollapsedSectionKeys())+ const [gizmoMode, setGizmoMode] = useState<'translate' | 'rotate' | 'scale' | null>(null)+ const dragging = useRef(false)+ const [selectedPointLightId, setSelectedPointLightId] = useState<string | null>(null)+ // Populated by Viewer3D — undoes the latest live gizmo transform, if any.+ const gizmoUndoRef = useRef<(() => boolean) | null>(null)++ const lightSettings = useAppStore((s) => s.lightSettings)+ const setLightSettings = useAppStore((s) => s.setLightSettings)+ const pointLights = useAppStore((s) => s.pointLights)+ const setPointLights = useAppStore((s) => s.setPointLights)+ const isGenerating = useAppStore((s) =>+ s.currentJob?.status === 'uploading' || s.currentJob?.status === 'generating'+ )+ const currentJob = useAppStore((s) => s.currentJob)+ const apiUrl = useAppStore((s) => s.apiUrl)+ const showError = useAppStore((s) => s.showError)+ const updateCurrentJob = useAppStore((s) => s.updateCurrentJob)+ const setCurrentJob = useAppStore((s) => s.setCurrentJob)+ const meshStats = useAppStore((s) => s.meshStats)+ const meshSelected = useAppStore((s) => s.meshSelected)+ const pushMeshUrl = useAppStore((s) => s.pushMeshUrl)+ const undoMesh = useAppStore((s) => s.undoMesh)+ const redoMesh = useAppStore((s) => s.redoMesh)+ const canUndo = useAppStore((s) => s.historyIndex > 0)+ const canRedo = useAppStore((s) => s.historyIndex < s.meshHistory.length - 1)+ const { optimizeMesh, smoothMesh, importMesh } = useApi()+ const assetLibraryService = useMemo(() => getDefaultAssetLibraryService(), [])++ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ if (!e.ctrlKey && !e.metaKey) return+ if (e.key === 'z') { e.preventDefault(); if (gizmoUndoRef.current?.()) return; undoMesh() }+ if (e.key === 'y') { e.preventDefault(); redoMesh() }+ }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ }, [undoMesh, redoMesh])++ const hasModel = currentJob?.status === 'done' && !!currentJob.outputUrl+ const showOpenInSlicer = hasModel && canOpenInOrcaSlicer(currentJob?.outputUrl)++ // Selecting a point light (from the 3D marker or the light panel list) —+ // also drops the active gizmo tool so it doesn't silently carry over from+ // whatever was selected before. Switching selection directly (mesh →+ // point light, or point light → point light) never passes through a+ // fully-deselected state, so an effect keyed on the selection alone can't+ // catch this; clearing it here, at the one place all of those paths go+ // through, does.+ const handleSelectPointLight = useCallback((id: string | null) => {+ setSelectedPointLightId(id)+ setGizmoMode(null)+ }, [])++ // Drop the active transform tool when nothing is selected, so it doesn't+ // silently re-activate on the next selection.+ useEffect(() => {+ if (!meshSelected && !selectedPointLightId) setGizmoMode(null)+ }, [meshSelected, selectedPointLightId])++ // Gizmo hotkeys: W move, R rotate, S scale, Esc exits. Ignored while typing.+ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ const el = document.activeElement as HTMLElement | null+ if (el && (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el.isContentEditable)) return+ if (e.key === 'Escape') { setGizmoMode((m) => (m ? null : m)); return }+ if (!meshSelected && !selectedPointLightId) return+ const k = e.key.toLowerCase()+ if (k === 'w') setGizmoMode('translate')+ else if (k === 'r') setGizmoMode('rotate')+ else if (k === 's') setGizmoMode('scale')+ }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ }, [hasModel, meshSelected, selectedPointLightId])++ useEffect(() => {+ if (openPanel !== 'library' || libraryLoaded || libraryLoading) return+ void loadLibraryEntries()+ // eslint-disable-next-line react-hooks/exhaustive-deps -- lazy-load guarded by loaded/loading flags+ }, [openPanel, libraryLoaded, libraryLoading])++ async function handleUnloadAll() {+ await window.electron.model.unloadAll()+ setUnloadStatus('done')+ setTimeout(() => setUnloadStatus('idle'), 2000)+ }++ function handleExport(format: 'glb' | 'obj' | 'stl' | 'ply') {+ if (!currentJob?.outputUrl) return+ const stem = `modly-${Date.now()}`+ const link = document.createElement('a')+ if (format === 'glb') {+ link.href = `${apiUrl}${currentJob.outputUrl}`+ } else {+ const path = encodeURIComponent(currentJob.outputUrl.replace('/workspace/', ''))+ link.href = `${apiUrl}/optimize/export?path=${path}&format=${format}`+ }+ link.download = `${stem}.${format}`+ link.click()+ }++ async function handleOpenInOrcaSlicer() {+ if (!currentJob?.outputUrl) return+ try {+ const link = buildOrcaSlicerDeepLink(apiUrl, currentJob.outputUrl)+ const result = await window.electron.slicer.open(link)+ if (!result.success) {+ // Deliberately not "make sure it is installed": the main process cannot+ // tell a missing OrcaSlicer from a working one (see slicer:open).+ showError(result.error ?? 'Could not open OrcaSlicer.')+ }+ } catch (err) {+ showError(err instanceof Error ? err.message : 'Could not open OrcaSlicer.')+ }+ }++ function getOptimizePath(url: string): string {+ if (url.startsWith('/workspace/')) {+ return url.slice('/workspace/'.length)+ }+ if (url.startsWith('/optimize/serve-file?path=')) {+ return decodeURIComponent(url.split('path=')[1] ?? '')+ }+ return url+ }++ async function handleImportMesh() {+ const filePath = await window.electron.fs.selectMeshFile()+ if (!filePath) return+ setOpenPanel(null)+ setImporting(true)+ try {+ const { url } = await importMesh(filePath)+ const job: GenerationJob = {+ id: `import-${Date.now()}`,+ imageFile: '',+ status: 'done',+ progress: 100,+ outputUrl: url,+ originalOutputUrl: url,+ createdAt: Date.now(),+ }+ setCurrentJob(job)+ pushMeshUrl(url)+ } finally {+ setImporting(false)+ }+ }++ async function loadLibraryEntries() {+ setLibraryLoading(true)+ setLibraryError(null)+ try {+ const result = await assetLibraryService.list()+ if (!result.success) {+ setLibraryLoaded(false)+ setLibraryEntries([])+ setLibrarySelectedEntryId(null)+ setLibraryError(result.error.message)+ return+ }+ setLibraryEntries(result.entries)+ setLibrarySelectedEntryId((current) => current && result.entries.some((entry) => entry.id === current)+ ? current+ : result.entries.find(isAssetLibraryEntryOpenable)?.id ?? result.entries[0]?.id ?? null)+ setLibraryLoaded(true)+ } catch (err) {+ setLibraryLoaded(false)+ setLibraryEntries([])+ setLibrarySelectedEntryId(null)+ setLibraryError(err instanceof Error ? err.message : String(err))+ } finally {+ setLibraryLoading(false)+ }+ }++ async function handleOpenSelectedLibraryEntry() {+ const selectedEntry = libraryEntries.find((entry) => entry.id === librarySelectedEntryId) ?? null+ if (!selectedEntry) {+ setLibraryError('Select an asset before opening it in Generate.')+ return+ }+ if (!isAssetLibraryEntryOpenable(selectedEntry)) {+ setLibraryError(describeAssetLibraryOpenability(selectedEntry))+ return+ }++ setLibraryOpening(true)+ setLibraryError(null)+ try {+ const result = await assetLibraryService.open(buildAssetLibraryOpenRequest(selectedEntry))+ if (!result.success) {+ setLibraryError(result.error.message)+ return+ }+ const target = resolveAssetLibraryOpenTarget(result.entry)+ const selection = createAssetLibraryOpenJob(result.entry, target)+ if (!selection) {+ setLibraryError(describeAssetLibraryOpenability(result.entry))+ return+ }+ setLibraryEntries((currentEntries) => currentEntries.map((entry) => entry.id === result.entry.id ? result.entry : entry))+ setLibrarySelectedEntryId(result.entry.id)+ setCurrentJob(selection.job)+ pushMeshUrl(selection.historyUrl)+ setOpenPanel((currentPanel) => resolveOpenPanelAfterLibrarySelection(currentPanel))+ } catch (err) {+ setLibraryError(err instanceof Error ? err.message : String(err))+ } finally {+ setLibraryOpening(false)+ }+ }++ async function handleSmooth(iterations: number) {+ if (!currentJob?.outputUrl) return+ setSmoothing(true)+ try {+ const path = getOptimizePath(currentJob.outputUrl)+ const { url } = await smoothMesh(path, iterations)+ updateCurrentJob({ outputUrl: url })+ pushMeshUrl(url)+ setOpenPanel(null)+ } catch (err) {+ showError(err instanceof Error ? err.message : String(err))+ } finally {+ setSmoothing(false)+ }+ }++ async function handleDecimate(targetFaces: number) {+ if (!currentJob?.outputUrl) return+ setDecimating(true)+ try {+ const path = getOptimizePath(currentJob.outputUrl)+ const { url } = await optimizeMesh(path, targetFaces)+ updateCurrentJob({ outputUrl: url })+ pushMeshUrl(url)+ setOpenPanel(null)+ } catch (err) {+ showError(err instanceof Error ? err.message : String(err))+ } finally {+ setDecimating(false)+ }+ }++ const onMouseDown = useCallback((e: React.MouseEvent) => {+ e.preventDefault()+ dragging.current = true++ const onMouseMove = (ev: MouseEvent) => {+ if (!dragging.current) return+ setPanelWidth((w) => Math.min(MAX_WIDTH, Math.max(MIN_WIDTH, w + ev.movementX)))+ }+ const onMouseUp = () => {+ dragging.current = false+ window.removeEventListener('mousemove', onMouseMove)+ window.removeEventListener('mouseup', onMouseUp)+ }+ window.addEventListener('mousemove', onMouseMove)+ window.addEventListener('mouseup', onMouseUp)+ }, [])++ return (+ <>+ <div className="flex flex-col border-r border-zinc-800 bg-surface-400 overflow-hidden shrink-0" style={{ width: panelWidth }}>+ <WorkflowPanel />+ </div>++ {/* Resize handle */}+ <div+ onMouseDown={onMouseDown}+ className="w-1 shrink-0 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"+ />++ <div className="flex-1 flex flex-col overflow-hidden">+ {/* Header bar */}+ <div className="flex items-center gap-2 px-3 py-2 border-b border-zinc-800 bg-surface-400 shrink-0">++ {/* Free memory */}+ <button+ onClick={handleUnloadAll}+ disabled={isGenerating}+ title="Free model from memory"+ className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-medium border bg-zinc-800 border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600 transition-colors disabled:opacity-30 disabled:pointer-events-none"+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6" />+ </svg>+ {unloadStatus === 'done' ? 'Freed' : 'Free memory'}+ </button>++ <div className="w-px h-4 bg-zinc-700/60" />++ {/* Undo / Redo */}+ <button+ onClick={undoMesh}+ disabled={!canUndo}+ title="Undo (Ctrl+Z)"+ className="flex items-center justify-center w-7 h-7 rounded-lg text-[11px] font-medium bg-zinc-800 border border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600 transition-colors disabled:opacity-30 disabled:pointer-events-none"+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <path d="M3 7v6h6" />+ <path d="M3 13a9 9 0 1 0 2.28-5.93" />+ </svg>+ </button>+ <button+ onClick={redoMesh}+ disabled={!canRedo}+ title="Redo (Ctrl+Y)"+ className="flex items-center justify-center w-7 h-7 rounded-lg text-[11px] font-medium bg-zinc-800 border border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600 transition-colors disabled:opacity-30 disabled:pointer-events-none"+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <path d="M21 7v6h-6" />+ <path d="M21 13a9 9 0 1 1-2.28-5.93" />+ </svg>+ </button>++ <div className="w-px h-4 bg-zinc-700/60" />++ {/* Import */}+ <div className="relative">+ <button+ onClick={() => setOpenPanel((p) => (p === 'import' ? null : 'import'))}+ disabled={importing}+ className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-medium border transition-colors disabled:opacity-50 disabled:pointer-events-none+ ${openPanel === 'import'+ ? 'bg-zinc-700 border-zinc-600 text-zinc-200'+ : 'bg-zinc-800 border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600'+ }`}+ >+ {importing ? (+ <svg className="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M21 12a9 9 0 1 1-6.219-8.56" />+ </svg>+ ) : (+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />+ <polyline points="7 10 12 15 17 10" />+ <line x1="12" y1="15" x2="12" y2="3" />+ </svg>+ )}+ {importing ? 'Importing…' : 'Import'}+ {!importing && (+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <polyline points="6 9 12 15 18 9" />+ </svg>+ )}+ </button>+ {openPanel === 'import' && (+ <div className="absolute top-full left-0 mt-1 z-50 bg-zinc-900 border border-zinc-700/60 rounded-xl p-1 flex flex-col gap-0.5 min-w-[140px] shadow-xl">+ <button+ onClick={handleImportMesh}+ className="px-3 py-2 text-left hover:bg-zinc-800 rounded-lg transition-colors flex items-center gap-2.5"+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" className="text-zinc-400">+ <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" />+ </svg>+ <div>+ <p className="text-xs text-zinc-200">Mesh</p>+ <p className="text-[10px] text-zinc-500">.glb .obj .stl .ply .splat</p>+ </div>+ </button>+ </div>+ )}+ </div>++ <div className="relative">+ <AssetLibraryToggleButton+ open={openPanel === 'library'}+ disabled={importing || libraryOpening}+ onToggle={() => {+ setLibraryError(null)+ setOpenPanel((panel) => (panel === 'library' ? null : 'library'))+ }}+ />+ {openPanel === 'library' && (+ <AssetLibraryPopover+ entries={libraryEntries}+ selectedEntryId={librarySelectedEntryId}+ loading={libraryLoading}+ opening={libraryOpening}+ error={libraryError}+ searchQuery={librarySearchQuery}+ sortMode={librarySortMode}+ collapsedSectionKeys={libraryCollapsedSectionKeys}+ onSelectEntry={(entryId) => {+ setLibraryError(null)+ setLibrarySelectedEntryId(entryId)+ }}+ onSearchQueryChange={setLibrarySearchQuery}+ onSortModeChange={setLibrarySortMode}+ onToggleSection={(sectionKey) => setLibraryCollapsedSectionKeys((current) => toggleAssetLibrarySectionKey(current, sectionKey))}+ onOpenSelected={() => { void handleOpenSelectedLibraryEntry() }}+ onRefresh={() => { void loadLibraryEntries() }}+ onClose={() => setOpenPanel(null)}+ />+ )}+ </div>++ {hasModel && (+ <>+ <div className="w-px h-4 bg-zinc-700/60" />++ {/* Export */}+ <div className="relative">+ <button+ onClick={() => setOpenPanel((p) => (p === 'export' ? null : 'export'))}+ className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-medium border transition-colors+ ${openPanel === 'export'+ ? 'bg-zinc-700 border-zinc-600 text-zinc-200'+ : 'bg-zinc-800 border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600'+ }`}+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />+ <polyline points="7 10 12 5 17 10" />+ <line x1="12" y1="5" x2="12" y2="15" />+ </svg>+ Export+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <polyline points="6 9 12 15 18 9" />+ </svg>+ </button>+ {openPanel === 'export' && (+ <ExportDropdown+ onExport={handleExport as (f: 'glb' | 'obj' | 'stl' | 'ply') => void}+ onClose={() => setOpenPanel(null)}+ onOpenInSlicer={() => { void handleOpenInOrcaSlicer() }}+ canOpenInSlicer={showOpenInSlicer}+ />+ )}+ </div>++ {/* Smooth */}+ <div className="relative">+ <button+ onClick={() => setOpenPanel((p) => (p === 'smooth' ? null : 'smooth'))}+ disabled={smoothing}+ className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-medium border transition-colors disabled:opacity-50 disabled:pointer-events-none+ ${openPanel === 'smooth' || smoothing+ ? 'bg-zinc-700 border-zinc-600 text-zinc-200'+ : 'bg-zinc-800 border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600'+ }`}+ >+ {smoothing ? (+ <svg className="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M21 12a9 9 0 1 1-6.219-8.56" />+ </svg>+ ) : (+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z" />+ <circle cx="12" cy="12" r="3" />+ </svg>+ )}+ {smoothing ? 'Processing…' : 'Smooth'}+ </button>+ {openPanel === 'smooth' && (+ <SmoothPopover+ smoothing={smoothing}+ onSmooth={handleSmooth}+ onClose={() => setOpenPanel(null)}+ />+ )}+ </div>++ {/* Decimate */}+ <div className="relative">+ <button+ onClick={() => setOpenPanel((p) => (p === 'decimate' ? null : 'decimate'))}+ disabled={decimating}+ className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-medium border transition-colors disabled:opacity-50 disabled:pointer-events-none+ ${openPanel === 'decimate' || decimating+ ? 'bg-zinc-700 border-zinc-600 text-zinc-200'+ : 'bg-zinc-800 border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600'+ }`}+ >+ {decimating ? (+ <svg className="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M21 12a9 9 0 1 1-6.219-8.56" />+ </svg>+ ) : (+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <polygon points="12 2 22 20 2 20" />+ <line x1="12" y1="9" x2="8" y2="17" />+ <line x1="12" y1="9" x2="16" y2="17" />+ <line x1="8" y1="17" x2="16" y2="17" />+ </svg>+ )}+ {decimating ? 'Processing…' : 'Decimate'}+ </button>+ {openPanel === 'decimate' && (+ <DecimatePopover+ currentTriangles={meshStats?.triangles ?? null}+ decimating={decimating}+ onDecimate={handleDecimate}+ onClose={() => setOpenPanel(null)}+ />+ )}+ </div>++ </>+ )}++ {/* Light — always visible, pushed to the right */}+ <div className="relative ml-auto">+ <button+ onClick={() => setOpenPanel((p) => (p === 'light' ? null : 'light'))}+ title="Lighting"+ className={`flex items-center justify-center w-7 h-7 rounded-lg border transition-colors+ ${openPanel === 'light'+ ? 'bg-zinc-700 border-zinc-600 text-zinc-200'+ : 'bg-zinc-800 border-zinc-700/50 text-zinc-400 hover:text-zinc-200 hover:border-zinc-600'+ }`}+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <circle cx="12" cy="12" r="4" />+ <line x1="12" y1="2" x2="12" y2="5" />+ <line x1="12" y1="19" x2="12" y2="22" />+ <line x1="4.22" y1="4.22" x2="6.34" y2="6.34" />+ <line x1="17.66" y1="17.66" x2="19.78" y2="19.78" />+ <line x1="2" y1="12" x2="5" y2="12" />+ <line x1="19" y1="12" x2="22" y2="12" />+ <line x1="4.22" y1="19.78" x2="6.34" y2="17.66" />+ <line x1="17.66" y1="6.34" x2="19.78" y2="4.22" />+ </svg>+ </button>+ {openPanel === 'light' && (+ <LightPopover+ settings={lightSettings}+ onChange={setLightSettings}+ onClose={() => setOpenPanel(null)}+ pointLights={pointLights}+ onPointLightsChange={setPointLights}+ selectedPointLightId={selectedPointLightId}+ onSelectPointLight={handleSelectPointLight}+ />+ )}+ </div>+ </div>++ {/* Tools bar — always visible; transform tools appear once a mesh is selected */}+ <div className="flex items-center gap-2 px-3 h-10 border-b border-zinc-800 bg-surface-400 shrink-0">+ {(meshSelected || selectedPointLightId) && (+ <>+ <ToolButton+ label="Move"+ active={gizmoMode === 'translate'}+ onClick={() => setGizmoMode((m) => (m === 'translate' ? null : 'translate'))}+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <polyline points="5 9 2 12 5 15" />+ <polyline points="9 5 12 2 15 5" />+ <polyline points="15 19 12 22 9 19" />+ <polyline points="19 9 22 12 19 15" />+ <line x1="2" y1="12" x2="22" y2="12" />+ <line x1="12" y1="2" x2="12" y2="22" />+ </svg>+ </ToolButton>+ <ToolButton+ label="Rotate"+ active={gizmoMode === 'rotate'}+ onClick={() => setGizmoMode((m) => (m === 'rotate' ? null : 'rotate'))}+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <path d="M21 2v6h-6" />+ <path d="M21 13a9 9 0 1 1-3-7.7L21 8" />+ </svg>+ </ToolButton>+ <ToolButton+ label="Scale"+ active={gizmoMode === 'scale'}+ onClick={() => setGizmoMode((m) => (m === 'scale' ? null : 'scale'))}+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <path d="M15 3h6v6" />+ <path d="M9 21H3v-6" />+ <path d="M21 3l-7 7" />+ <path d="M3 21l7-7" />+ </svg>+ </ToolButton>+ </>+ )}+ </div>++ {/* Viewer area */}+ <div className="flex-1 relative overflow-hidden">+ <Viewer3D+ lightSettings={lightSettings}+ gizmoMode={gizmoMode}+ gizmoUndoRef={gizmoUndoRef}+ pointLights={pointLights}+ selectedPointLightId={selectedPointLightId}+ onSelectPointLight={handleSelectPointLight}+ onPointLightsChange={setPointLights}+ />+ <GenerationHUD />+ </div>+ </div>+ </>+ )+}\ No newline at end of filediff --git a/apps/forge-desktop/src/areas/generate/assetLibraryProjection.test.ts b/apps/forge-desktop/src/areas/generate/assetLibraryProjection.test.tsnew file mode 100644index 000000000..bc1c9df22--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/assetLibraryProjection.test.ts@@ -0,0 +1,112 @@+import assert from 'node:assert/strict'+import test from 'node:test'++import {+ filterAssetLibraryEntries,+ groupAssetLibraryEntries,+ projectAssetLibraryEntry,+ resolveAssetLibraryOpenTarget,+} from './assetLibraryProjection.ts'+import type { AssetLibraryEntry } from '../../shared/types/assetLibrary.ts'++const glbEntry: AssetLibraryEntry = {+ id: 'library:Workflows/checkpoints/hero.glb',+ workspacePath: 'Workflows/checkpoints/hero.glb',+ displayName: 'hero.glb',+ sourceScope: 'workflows',+ capability: 'mesh',+ state: 'ready',+ previewKind: '3d-model',+ warnings: ['safe', 'safe'],+ openable: true,+}++test('projects entries with deduped warnings and workspace URL open target', () => {+ const projected = projectAssetLibraryEntry(glbEntry)+ assert.deepEqual(projected.warnings, ['safe'])+ assert.deepEqual(resolveAssetLibraryOpenTarget(projected), {+ kind: 'self',+ url: '/workspace/Workflows/checkpoints/hero.glb',+ workspacePath: 'Workflows/checkpoints/hero.glb',+ })+})++test('projects sidecars with safe GLB source links as linked-source open targets', () => {+ const projected = projectAssetLibraryEntry({+ ...glbEntry,+ id: 'library:Workflows/checkpoints/hero.landmarks.v1.json',+ workspacePath: 'Workflows/checkpoints/hero.landmarks.v1.json',+ displayName: 'hero.landmarks.v1.json',+ capability: 'landmarks-sidecar',+ previewKind: 'text',+ openable: false,+ nonOpenableReason: 'Open the linked source mesh.',+ source: { workspacePath: 'Workflows/checkpoints/hero.glb', displayName: 'hero.glb', role: 'source-mesh' },+ manifest: { workspacePath: 'Workflows/checkpoints/hero.scene.json', capability: 'scene-manifest' },+ })++ assert.deepEqual(projected.source, { workspacePath: 'Workflows/checkpoints/hero.glb', displayName: 'hero.glb', role: 'source-mesh' })+ assert.deepEqual(projected.manifest, { workspacePath: 'Workflows/checkpoints/hero.scene.json', capability: 'scene-manifest' })+ assert.deepEqual(resolveAssetLibraryOpenTarget(projected), {+ kind: 'linked-source',+ workspacePath: 'Workflows/checkpoints/hero.landmarks.v1.json',+ sourceWorkspacePath: 'Workflows/checkpoints/hero.glb',+ url: '/workspace/Workflows/checkpoints/hero.glb',+ })+})++test('degrades unsafe source and manifest paths and unsupported formats to unavailable targets', () => {+ const projected = projectAssetLibraryEntry({+ ...glbEntry,+ id: 'unsafe-source',+ workspacePath: 'Workflows/checkpoints/hero.landmarks.v1.json',+ displayName: 'hero.landmarks.v1.json',+ capability: 'landmarks-sidecar',+ previewKind: 'text',+ openable: false,+ source: { workspacePath: 'Workflows/%2e%2e/secret.glb' },+ manifest: { workspacePath: '../secret.scene.json', capability: 'scene-manifest' },+ })+ const splat = projectAssetLibraryEntry({ ...glbEntry, id: 'splat', workspacePath: 'Workflows/scan.splat', displayName: 'scan.splat', openable: true })++ assert.equal(projected.source, undefined)+ assert.equal(projected.manifest, undefined)+ assert.deepEqual(projected.warnings, ['safe', 'Ignored unsafe source workspace path.', 'Ignored unsafe manifest workspace path.'])+ assert.deepEqual(resolveAssetLibraryOpenTarget(projected), {+ kind: 'unavailable',+ reason: 'Workspace asset is not openable.',+ })+ assert.deepEqual(resolveAssetLibraryOpenTarget(splat), {+ kind: 'unavailable',+ reason: 'Only safe .glb/.gltf workspace assets are openable in this release.',+ })+})++test('marks unsafe or non-openable entries unavailable without throwing', () => {+ const projected = projectAssetLibraryEntry({+ ...glbEntry,+ workspacePath: '../escape.glb',+ state: 'unsafe',+ openable: false,+ nonOpenableReason: 'Unsafe workspace path.',+ })+ assert.equal(projected.state, 'unsafe')+ assert.deepEqual(resolveAssetLibraryOpenTarget(projected), {+ kind: 'unavailable',+ reason: 'Unsafe workspace path.',+ })+})++test('filters by name, path, capability, scope, and groups by scope then capability', () => {+ const entries = [+ projectAssetLibraryEntry(glbEntry),+ projectAssetLibraryEntry({ ...glbEntry, id: 'export', workspacePath: 'Exports/static.ply', displayName: 'static.ply', sourceScope: 'exports', openable: false }),+ ]+ assert.deepEqual(filterAssetLibraryEntries(entries, 'exports').map((entry) => entry.workspacePath), ['Exports/static.ply'])+ assert.deepEqual(filterAssetLibraryEntries(entries, 'hero.glb').map((entry) => entry.displayName), ['hero.glb'])+ assert.deepEqual(filterAssetLibraryEntries(entries, 'mesh').map((entry) => entry.displayName), ['hero.glb', 'static.ply'])+ assert.deepEqual(groupAssetLibraryEntries(entries).map((group) => [group.scope, group.capabilityGroups.map((capability) => capability.capability)]), [+ ['exports', ['mesh']],+ ['workflows', ['mesh']],+ ])+})diff --git a/apps/forge-desktop/src/areas/generate/assetLibraryProjection.ts b/apps/forge-desktop/src/areas/generate/assetLibraryProjection.tsnew file mode 100644index 000000000..b65f5b509--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/assetLibraryProjection.ts@@ -0,0 +1,99 @@+import type { AssetCapability, AssetLibraryEntry, AssetLibrarySourceScope } from '../../shared/types/assetLibrary'++export interface ProjectedAssetLibraryEntry extends AssetLibraryEntry {+ warnings: string[]+}++export type AssetLibraryOpenTarget =+ | { kind: 'self', url: string, workspacePath: string }+ | { kind: 'linked-source', url: string, workspacePath: string, sourceWorkspacePath: string }+ | { kind: 'unavailable', reason: string }++export interface AssetLibraryCapabilityGroup {+ capability: AssetCapability | 'uncategorized'+ entries: ProjectedAssetLibraryEntry[]+}++export interface AssetLibraryScopeGroup {+ scope: AssetLibrarySourceScope+ capabilityGroups: AssetLibraryCapabilityGroup[]+}++function isSafeWorkspacePath(workspacePath: string): boolean {+ const normalized = workspacePath.replace(/\\/g, '/').trim()+ return /^(Workflows|Exports)\//.test(normalized)+ && !normalized.split('/').includes('..')+ && !/%2e|%2f|%5c/i.test(normalized)+ && !normalized.startsWith('/')+ && !/^[a-zA-Z]:[\\/]/.test(workspacePath)+ && !workspacePath.startsWith('\\\\')+}++function isGlbOrGltf(workspacePath: string): boolean {+ return /\.(glb|gltf)$/i.test(workspacePath)+}++export function projectAssetLibraryEntry(entry: AssetLibraryEntry): ProjectedAssetLibraryEntry {+ const warnings = [...new Set(entry.warnings)]+ if (!isSafeWorkspacePath(entry.workspacePath)) {+ return { ...entry, state: 'unsafe', openable: false, nonOpenableReason: entry.nonOpenableReason ?? 'Unsafe workspace path.', warnings }+ }+ const safeSource = entry.source && isSafeWorkspacePath(entry.source.workspacePath) ? entry.source : undefined+ const safeManifest = entry.manifest && isSafeWorkspacePath(entry.manifest.workspacePath) ? entry.manifest : undefined+ if (entry.source && !safeSource) warnings.push('Ignored unsafe source workspace path.')+ if (entry.manifest && !safeManifest) warnings.push('Ignored unsafe manifest workspace path.')+ return { ...entry, source: safeSource, manifest: safeManifest, warnings: [...new Set(warnings)] }+}++export function resolveAssetLibraryOpenTarget(entry: ProjectedAssetLibraryEntry): AssetLibraryOpenTarget {+ if (entry.state !== 'ready') {+ return { kind: 'unavailable', reason: entry.nonOpenableReason ?? 'Workspace asset is not openable.' }+ }+ if (entry.source?.workspacePath) {+ if (!isSafeWorkspacePath(entry.source.workspacePath) || entry.source.workspacePath === entry.workspacePath || !isGlbOrGltf(entry.source.workspacePath)) {+ return { kind: 'unavailable', reason: 'Linked source mesh is unavailable.' }+ }+ return {+ kind: 'linked-source',+ url: `/workspace/${entry.source.workspacePath}`,+ workspacePath: entry.workspacePath,+ sourceWorkspacePath: entry.source.workspacePath,+ }+ }+ if (!entry.openable) {+ return { kind: 'unavailable', reason: entry.nonOpenableReason ?? 'Workspace asset is not openable.' }+ }+ if (!isGlbOrGltf(entry.workspacePath)) {+ return { kind: 'unavailable', reason: 'Only safe .glb/.gltf workspace assets are openable in this release.' }+ }+ return { kind: 'self', url: `/workspace/${entry.workspacePath}`, workspacePath: entry.workspacePath }+}++export function filterAssetLibraryEntries(entries: ProjectedAssetLibraryEntry[], query: string): ProjectedAssetLibraryEntry[] {+ const needle = query.trim().toLowerCase()+ if (!needle) return entries+ return entries.filter((entry) => [+ entry.displayName,+ entry.workspacePath,+ entry.capability ?? '',+ entry.sourceScope,+ entry.state,+ entry.source?.workspacePath ?? '',+ entry.manifest?.workspacePath ?? '',+ ].some((value) => value.toLowerCase().includes(needle)))+}++export function groupAssetLibraryEntries(entries: ProjectedAssetLibraryEntry[]): AssetLibraryScopeGroup[] {+ const scopes = [...new Set(entries.map((entry) => entry.sourceScope))].sort()+ return scopes.map((scope) => {+ const scopeEntries = entries.filter((entry) => entry.sourceScope === scope)+ const capabilities = [...new Set(scopeEntries.map((entry) => entry.capability ?? 'uncategorized'))].sort()+ return {+ scope,+ capabilityGroups: capabilities.map((capability) => ({+ capability,+ entries: scopeEntries.filter((entry) => (entry.capability ?? 'uncategorized') === capability),+ })),+ }+ })+}diff --git a/apps/forge-desktop/src/areas/generate/assetLibraryService.test.ts b/apps/forge-desktop/src/areas/generate/assetLibraryService.test.tsnew file mode 100644index 000000000..9e7938c4e--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/assetLibraryService.test.ts@@ -0,0 +1,60 @@+import assert from 'node:assert/strict'+import test from 'node:test'++import { createAssetLibraryService } from './assetLibraryService.ts'++test('renderer service validates requests before IPC and projects structured errors', async () => {+ let invoked = false+ const service = createAssetLibraryService({+ list: async () => ({ success: true, entries: [] }),+ read: async () => { invoked = true; return { success: false, error: { code: 'unexpected', message: 'should not run' } } },+ open: async () => { invoked = true; return { success: false, error: { code: 'unexpected', message: 'should not run' } } },+ })++ const read = await service.read({ workspacePath: '../escape.glb' })+ const open = await service.open({ workspacePath: '/tmp/hero.glb' })+ assert.equal(read.success, false)+ assert.equal(!read.success && read.error.code, 'unsafe-path')+ assert.equal(open.success, false)+ assert.equal(!open.success && open.error.code, 'unsafe-path')+ assert.equal(invoked, false)+})++test('renderer service validates sourceWorkspacePath before read and open IPC calls', async () => {+ let invoked = false+ const service = createAssetLibraryService({+ list: async () => ({ success: true, entries: [] }),+ read: async () => { invoked = true; return { success: false, error: { code: 'unexpected', message: 'should not run' } } },+ open: async () => { invoked = true; return { success: false, error: { code: 'unexpected', message: 'should not run' } } },+ })++ const read = await service.read({ workspacePath: 'Workflows/hero.landmarks.v1.json', sourceWorkspacePath: '../secret.glb' })+ const open = await service.open({ workspacePath: 'Workflows/hero.landmarks.v1.json', sourceWorkspacePath: 'C:\\secret.glb' })++ assert.equal(read.success, false)+ assert.equal(!read.success && read.error.code, 'unsafe-path')+ assert.equal(open.success, false)+ assert.equal(!open.success && open.error.code, 'unsafe-path')+ assert.equal(invoked, false)+})++test('renderer service delegates safe IPC calls and normalizes returned entries', async () => {+ let openRequest: unknown = null+ const service = createAssetLibraryService({+ list: async () => ({+ success: true,+ entries: [{+ id: 'asset', workspacePath: 'Workflows/hero.glb', displayName: 'hero.glb', sourceScope: 'workflows',+ capability: 'mesh', state: 'ready', previewKind: '3d-model', warnings: ['a', 'a'], openable: true,+ }],+ }),+ read: async () => ({ success: false, error: { code: 'missing', message: 'Missing' } }),+ open: async (request) => { openRequest = request; return { success: false, error: { code: 'missing', message: 'Missing' } } },+ })++ const result = await service.list()+ assert.equal(result.success, true)+ assert.deepEqual(result.success && result.entries[0]?.warnings, ['a'])+ await service.open({ workspacePath: 'Workflows/hero.landmarks.v1.json', sourceWorkspacePath: 'Workflows/hero.glb' })+ assert.deepEqual(openRequest, { workspacePath: 'Workflows/hero.landmarks.v1.json', sourceWorkspacePath: 'Workflows/hero.glb' })+})diff --git a/apps/forge-desktop/src/areas/generate/assetLibraryService.ts b/apps/forge-desktop/src/areas/generate/assetLibraryService.tsnew file mode 100644index 000000000..38738579a--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/assetLibraryService.ts@@ -0,0 +1,68 @@+import type {+ AssetLibraryError,+ AssetLibraryListResult,+ AssetLibraryOpenRequest,+ AssetLibraryOpenResult,+ AssetLibraryReadRequest,+ AssetLibraryReadResult,+} from '../../shared/types/assetLibrary'+import { projectAssetLibraryEntry, type ProjectedAssetLibraryEntry } from './assetLibraryProjection'++export interface AssetLibraryPreloadApi {+ list: () => Promise<AssetLibraryListResult>+ read: (request: AssetLibraryReadRequest) => Promise<AssetLibraryReadResult>+ open: (request: AssetLibraryOpenRequest) => Promise<AssetLibraryOpenResult>+}++export type ProjectedAssetLibraryListResult =+ | { success: true, entries: ProjectedAssetLibraryEntry[] }+ | { success: false, error: AssetLibraryError }++export type ProjectedAssetLibraryReadResult =+ | { success: true, entry: ProjectedAssetLibraryEntry, preview: Extract<AssetLibraryReadResult, { success: true }>['preview'] }+ | { success: false, error: AssetLibraryError }++export type ProjectedAssetLibraryOpenResult =+ | { success: true, entry: ProjectedAssetLibraryEntry }+ | { success: false, error: AssetLibraryError }++function unsafeError(message = 'Workspace path must stay under Workflows/ or Exports/.'): AssetLibraryError {+ return { code: 'unsafe-path', message }+}++function validateWorkspacePath(workspacePath: string): AssetLibraryError | null {+ const trimmed = workspacePath.trim()+ if (!trimmed || trimmed.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(trimmed) || trimmed.startsWith('\\\\')) return unsafeError()+ if (/%2e|%2f|%5c/i.test(trimmed) || trimmed.split(/[\\/]+/).includes('..')) return unsafeError()+ const normalized = trimmed.replace(/\\/g, '/')+ if (!normalized.startsWith('Workflows/') && !normalized.startsWith('Exports/')) return unsafeError()+ return null+}++export function createAssetLibraryService(api: AssetLibraryPreloadApi) {+ return {+ async list(): Promise<ProjectedAssetLibraryListResult> {+ const result = await api.list()+ if (!result.success) return result+ return { success: true, entries: result.entries.map(projectAssetLibraryEntry) }+ },+ async read(request: AssetLibraryReadRequest): Promise<ProjectedAssetLibraryReadResult> {+ const invalid = validateWorkspacePath(request.workspacePath) ?? (request.sourceWorkspacePath ? validateWorkspacePath(request.sourceWorkspacePath) : null)+ if (invalid) return { success: false, error: invalid }+ const result = await api.read(request)+ if (!result.success) return result+ return { success: true, entry: projectAssetLibraryEntry(result.entry), preview: result.preview }+ },+ async open(request: AssetLibraryOpenRequest): Promise<ProjectedAssetLibraryOpenResult> {+ const invalid = validateWorkspacePath(request.workspacePath) ?? (request.sourceWorkspacePath ? validateWorkspacePath(request.sourceWorkspacePath) : null)+ if (invalid) return { success: false, error: invalid }+ const result = await api.open(request)+ if (!result.success) return result+ return { success: true, entry: projectAssetLibraryEntry(result.entry) }+ },+ }+}++export function getDefaultAssetLibraryService() {+ return createAssetLibraryService(window.electron.workspace.library)+}diff --git a/apps/forge-desktop/src/areas/generate/assetLibraryUi.test.ts b/apps/forge-desktop/src/areas/generate/assetLibraryUi.test.tsnew file mode 100644index 000000000..e6b9fbca6--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/assetLibraryUi.test.ts@@ -0,0 +1,125 @@+import assert from 'node:assert/strict'+import test from 'node:test'++import {+ buildAssetLibraryOpenRequest,+ createAssetLibraryOpenJob,+ describeAssetLibraryOpenability,+ filterAssetLibraryScopeGroups,+ getDefaultAssetLibraryCollapsedSectionKeys,+ isAssetLibraryEntryOpenable,+ resolveOpenPanelAfterLibrarySelection,+ toggleAssetLibrarySectionKey,+ type AssetLibrarySortMode,+ type GenerateOpenPanel,+} from './assetLibraryUi.ts'+import { projectAssetLibraryEntry, resolveAssetLibraryOpenTarget, type ProjectedAssetLibraryEntry } from './assetLibraryProjection.ts'+import type { AssetLibraryEntry } from '../../shared/types/assetLibrary.ts'++function entry(overrides: Partial<AssetLibraryEntry> = {}): ProjectedAssetLibraryEntry {+ const base: AssetLibraryEntry = {+ id: 'library:Workflows/hero.glb',+ workspacePath: 'Workflows/hero.glb',+ displayName: 'hero.glb',+ sourceScope: 'workflows',+ capability: 'mesh',+ state: 'ready',+ previewKind: '3d-model',+ warnings: [],+ openable: true,+ createdAt: '2026-06-16T10:00:00.000Z',+ ...overrides,+ }+ return projectAssetLibraryEntry(base)+}++function groupPaths(entries: ProjectedAssetLibraryEntry[], search = '', sortMode: AssetLibrarySortMode = 'type'): string[] {+ return filterAssetLibraryScopeGroups(entries, search, sortMode).flatMap((scopeGroup) => (+ scopeGroup.entryGroups.flatMap((group) => group.entries.map((item) => item.workspacePath))+ ))+}++test('organizes visible library assets by scope and capability with collapsible section keys', () => {+ const entries = [+ entry({ id: 'workflow-mesh', workspacePath: 'Workflows/run/hero.glb', displayName: 'hero.glb', sourceScope: 'workflows', capability: 'mesh' }),+ entry({ id: 'export-rig', workspacePath: 'Exports/rig/hero-rig.gltf', displayName: 'hero-rig.gltf', sourceScope: 'exports', capability: 'rigged-mesh' }),+ entry({ id: 'hidden-cache', workspacePath: 'Workflows/run/cache/internal.glb', displayName: 'internal.glb', sourceScope: 'workflows' }),+ entry({ id: 'unsupported', workspacePath: 'Exports/readme.txt', displayName: 'readme.txt', sourceScope: 'exports', state: 'unsupported', openable: false }),+ ]++ const groups = filterAssetLibraryScopeGroups(entries, '', 'type')+ assert.deepEqual(groups.map((group) => [group.sourceScope, group.entryGroups.map((entryGroup) => entryGroup.capability)]), [+ ['workflows', ['mesh']],+ ['exports', ['rigged-mesh']],+ ])+ assert.deepEqual(groupPaths(entries), ['Workflows/run/hero.glb', 'Exports/rig/hero-rig.gltf'])+ assert.equal(getDefaultAssetLibraryCollapsedSectionKeys().includes('scope:workflows'), true)+ assert.deepEqual(toggleAssetLibrarySectionKey(['scope:workflows'], 'scope:workflows'), [])+ assert.deepEqual(toggleAssetLibrarySectionKey([], 'scope:exports'), ['scope:exports'])+})++test('searches workspace assets by name path capability scope source and manifest while supporting name/date sorting', () => {+ const entries = [+ entry({ id: 'b', workspacePath: 'Workflows/run/zebra.glb', displayName: 'zebra.glb', sourceScope: 'workflows', capability: 'mesh', createdAt: '2026-06-15T10:00:00.000Z' }),+ entry({ id: 'a', workspacePath: 'Exports/rig/alpha.gltf', displayName: 'alpha.gltf', sourceScope: 'exports', capability: 'rigged-mesh', createdAt: '2026-06-16T10:00:00.000Z' }),+ entry({+ id: 'c', workspacePath: 'Exports/motion/walk.json', displayName: 'walk.json', sourceScope: 'exports', capability: 'animation-motion', openable: false, previewKind: 'text',+ source: { workspacePath: 'Workflows/run/zebra.glb', displayName: 'zebra.glb' },+ manifest: { workspacePath: 'Exports/motion/walk.scene.json', capability: 'scene-manifest' },+ }),+ ]++ assert.deepEqual(groupPaths(entries, 'rigged'), ['Exports/rig/alpha.gltf'])+ assert.deepEqual(groupPaths(entries, 'walk.scene'), ['Exports/motion/walk.json'])+ assert.deepEqual(groupPaths(entries, 'zebra.glb'), ['Workflows/run/zebra.glb', 'Exports/motion/walk.json'])+ assert.deepEqual(groupPaths(entries, 'exports', 'name'), ['Exports/rig/alpha.gltf', 'Exports/motion/walk.json'])+ assert.deepEqual(groupPaths(entries, '', 'date'), ['Workflows/run/zebra.glb', 'Exports/rig/alpha.gltf', 'Exports/motion/walk.json'])+})++test('opens only safe glb and gltf entries through existing Generate job and history state', () => {+ const glb = entry({ workspacePath: 'Workflows/run/hero.glb', displayName: 'hero.glb' })+ const ply = entry({ workspacePath: 'Exports/scan.ply', displayName: 'scan.ply', openable: false, nonOpenableReason: 'Only .glb/.gltf workspace assets are openable in this release.' })++ assert.equal(isAssetLibraryEntryOpenable(glb), true)+ assert.equal(isAssetLibraryEntryOpenable(ply), false)+ assert.equal(describeAssetLibraryOpenability(glb), 'Ready to open this asset directly in Generate.')+ assert.equal(describeAssetLibraryOpenability(ply), 'Only .glb/.gltf workspace assets are openable in this release.')+ assert.deepEqual(buildAssetLibraryOpenRequest(glb), { workspacePath: 'Workflows/run/hero.glb' })++ const target = resolveAssetLibraryOpenTarget(glb)+ assert.equal(target.kind, 'self')+ if (target.kind !== 'self') throw new Error('expected self target')++ const selection = createAssetLibraryOpenJob(glb, target, 1718546400000)+ assert.equal(selection.historyUrl, '/workspace/Workflows/run/hero.glb')+ assert.equal(selection.job.status, 'done')+ assert.equal(selection.job.outputUrl, '/workspace/Workflows/run/hero.glb')+ assert.equal(selection.job.originalOutputUrl, '/workspace/Workflows/run/hero.glb')+ assert.equal(resolveOpenPanelAfterLibrarySelection('library' satisfies GenerateOpenPanel), 'library')+})++test('builds linked-source open requests and import jobs for safe sidecars', () => {+ const sidecar = entry({+ id: 'sidecar',+ workspacePath: 'Workflows/run/hero.landmarks.v1.json',+ displayName: 'hero.landmarks.v1.json',+ capability: 'landmarks-sidecar',+ previewKind: 'text',+ openable: false,+ source: { workspacePath: 'Workflows/run/hero.glb', displayName: 'hero.glb' },+ })++ assert.equal(isAssetLibraryEntryOpenable(sidecar), true)+ assert.equal(describeAssetLibraryOpenability(sidecar), 'Ready to open linked source hero.glb in Generate.')+ assert.deepEqual(buildAssetLibraryOpenRequest(sidecar), {+ workspacePath: 'Workflows/run/hero.landmarks.v1.json',+ sourceWorkspacePath: 'Workflows/run/hero.glb',+ })++ const target = resolveAssetLibraryOpenTarget(sidecar)+ assert.equal(target.kind, 'linked-source')+ if (target.kind !== 'linked-source') throw new Error('expected linked source target')+ const selection = createAssetLibraryOpenJob(sidecar, target, 1718546400001)+ assert.equal(selection?.historyUrl, '/workspace/Workflows/run/hero.glb')+ assert.equal(selection?.job.outputUrl, '/workspace/Workflows/run/hero.glb')+})diff --git a/apps/forge-desktop/src/areas/generate/assetLibraryUi.ts b/apps/forge-desktop/src/areas/generate/assetLibraryUi.tsnew file mode 100644index 000000000..5e83e65a8--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/assetLibraryUi.ts@@ -0,0 +1,250 @@+import type { GenerationJob } from '../../shared/stores/appStore'+import type { AssetLibraryOpenRequest } from '../../shared/types/assetLibrary'+import { resolveAssetLibraryOpenTarget, type AssetLibraryOpenTarget, type ProjectedAssetLibraryEntry } from './assetLibraryProjection'++export type GenerateOpenPanel = 'export' | 'decimate' | 'smooth' | 'import' | 'library' | 'light' | null+export type AssetLibrarySortMode = 'type' | 'name' | 'date'++export interface AssetLibraryEntryGroup {+ capability: NonNullable<ProjectedAssetLibraryEntry['capability']>+ capabilityLabel: string+ sectionKey: string+ entries: ProjectedAssetLibraryEntry[]+}++export interface AssetLibrarySourceScopeGroup {+ sourceScope: ProjectedAssetLibraryEntry['sourceScope']+ sourceScopeLabel: string+ sectionKey: string+ entryGroups: AssetLibraryEntryGroup[]+}++export interface AssetLibraryOpenSelection {+ historyUrl: string+ job: GenerationJob+}++const ASSET_LIBRARY_CAPABILITY_SECTIONS = [+ { capability: 'mesh', label: 'Mesh' },+ { capability: 'rigged-mesh', label: 'Rigged mesh' },+ { capability: 'animation-motion', label: 'Animations/motions' },+ { capability: 'landmarks-sidecar', label: 'Landmarks sidecars' },+ { capability: 'generated-world', label: 'Generated worlds' },+ { capability: 'scene-manifest', label: 'Scene manifests' },+] as const satisfies ReadonlyArray<{ capability: NonNullable<ProjectedAssetLibraryEntry['capability']>, label: string }>++const ASSET_LIBRARY_SOURCE_SCOPE_SECTIONS = [+ { sourceScope: 'workflows', label: 'Workflows' },+ { sourceScope: 'exports', label: 'Exports' },+] as const satisfies ReadonlyArray<{ sourceScope: ProjectedAssetLibraryEntry['sourceScope'], label: string }>++const ASSET_LIBRARY_CAPABILITY_ORDER = new Map(+ ASSET_LIBRARY_CAPABILITY_SECTIONS.map((section, index) => [section.capability, index]),+)++const ASSET_LIBRARY_INTERNAL_DIRECTORY_NAMES = new Set(['tmp', 'temp', 'cache'])++export const ASSET_LIBRARY_SORT_OPTIONS = [+ { value: 'type', label: 'Type' },+ { value: 'name', label: 'Name' },+ { value: 'date', label: 'Date' },+] as const satisfies ReadonlyArray<{ value: AssetLibrarySortMode, label: string }>++export function getDefaultAssetLibraryCollapsedSectionKeys(): string[] {+ const sectionKeys = ASSET_LIBRARY_SOURCE_SCOPE_SECTIONS.flatMap((scopeSection) => {+ const capabilityKeys = ASSET_LIBRARY_CAPABILITY_SECTIONS.map(+ (capabilitySection) => `capability:${scopeSection.sourceScope}:${capabilitySection.capability}`,+ )++ return [`scope:${scopeSection.sourceScope}`, ...capabilityKeys]+ })++ return [...sectionKeys]+}++export function toggleAssetLibrarySectionKey(currentKeys: string[], sectionKey: string): string[] {+ return currentKeys.includes(sectionKey)+ ? currentKeys.filter((value) => value !== sectionKey)+ : [...currentKeys, sectionKey]+}++export function buildAssetLibraryOpenRequest(entry: ProjectedAssetLibraryEntry): AssetLibraryOpenRequest {+ const target = resolveAssetLibraryOpenTarget(entry)+ return target.kind === 'linked-source'+ ? { workspacePath: target.workspacePath, sourceWorkspacePath: target.sourceWorkspacePath }+ : { workspacePath: entry.workspacePath }+}++export function isAssetLibraryEntryOpenable(entry: ProjectedAssetLibraryEntry | null | undefined): entry is ProjectedAssetLibraryEntry {+ return Boolean(entry && resolveAssetLibraryOpenTarget(entry).kind !== 'unavailable')+}++export function describeAssetLibraryOpenability(entry: ProjectedAssetLibraryEntry): string {+ if (entry.state === 'unknown-metadata') return 'Missing metadata prevents a safe open in Generate.'+ if (entry.state === 'unsupported') return 'This asset is tracked in the library but is not supported in Generate.'+ if (entry.state === 'unsafe') return 'This asset was rejected because its workspace path is unsafe.'+ const target = resolveAssetLibraryOpenTarget(entry)+ if (target.kind === 'linked-source') return `Ready to open linked source ${entry.source?.displayName ?? target.sourceWorkspacePath} in Generate.`+ if (target.kind === 'self') return 'Ready to open this asset directly in Generate.'+ if (entry.nonOpenableReason) return entry.nonOpenableReason+ if (!/\.(glb|gltf)$/i.test(entry.workspacePath)) return 'Only .glb/.gltf workspace assets are openable in this release.'+ return target.reason+}++export function filterVisibleAssetLibraryEntries(entries: ProjectedAssetLibraryEntry[]): ProjectedAssetLibraryEntry[] {+ return entries.filter((entry) => entry.state !== 'unsupported' && !hasInternalAssetLibraryDirectory(entry.workspacePath))+}++export function filterAssetLibraryScopeGroups(+ entries: ProjectedAssetLibraryEntry[],+ searchQuery: string,+ sortMode: AssetLibrarySortMode,+): AssetLibrarySourceScopeGroup[] {+ const normalizedSearchQuery = normalizeAssetLibrarySearchQuery(searchQuery)+ const visibleEntries = filterVisibleAssetLibraryEntries(entries)++ return ASSET_LIBRARY_SOURCE_SCOPE_SECTIONS+ .map((scopeSection) => {+ const scopeEntries = visibleEntries.filter((entry) => entry.sourceScope === scopeSection.sourceScope)+ const scopeMatches = normalizedSearchQuery.length > 0 && matchesAssetLibrarySearch(scopeSection.label, normalizedSearchQuery)++ const entryGroups = ASSET_LIBRARY_CAPABILITY_SECTIONS+ .map((capabilitySection) => {+ const capabilityEntries = scopeEntries.filter((entry) => entry.capability === capabilitySection.capability)+ if (capabilityEntries.length === 0) return null++ const capabilityMatches = scopeMatches || (normalizedSearchQuery.length > 0 && matchesAssetLibrarySearch(capabilitySection.label, normalizedSearchQuery))+ const visibleCapabilityEntries = !normalizedSearchQuery || capabilityMatches+ ? capabilityEntries+ : capabilityEntries.filter((entry) => matchesAssetLibraryEntrySearch(entry, normalizedSearchQuery))++ if (visibleCapabilityEntries.length === 0) return null++ return {+ capability: capabilitySection.capability,+ capabilityLabel: capabilitySection.label,+ sectionKey: `capability:${scopeSection.sourceScope}:${capabilitySection.capability}`,+ entries: sortAssetLibraryEntries(visibleCapabilityEntries, sortMode),+ }+ })+ .filter((group): group is AssetLibraryEntryGroup => group !== null)++ const sortedEntryGroups = sortMode === 'type'+ ? entryGroups+ : [...entryGroups].sort((left, right) => compareAssetLibraryEntryGroups(left, right, sortMode))++ if (sortedEntryGroups.length === 0) return null+ return {+ sourceScope: scopeSection.sourceScope,+ sourceScopeLabel: scopeSection.label,+ sectionKey: `scope:${scopeSection.sourceScope}`,+ entryGroups: sortedEntryGroups,+ }+ })+ .filter((group): group is AssetLibrarySourceScopeGroup => group !== null)+}++export function createAssetLibraryOpenJob(+ entry: ProjectedAssetLibraryEntry,+ target: AssetLibraryOpenTarget,+ now = Date.now(),+): AssetLibraryOpenSelection | null {+ if (target.kind === 'unavailable') return null+ return {+ historyUrl: target.url,+ job: {+ id: `library-${now}`,+ imageFile: '',+ status: 'done',+ progress: 100,+ outputUrl: target.url,+ originalOutputUrl: target.url,+ createdAt: now,+ },+ }+}++export function resolveOpenPanelAfterLibrarySelection(currentPanel: GenerateOpenPanel): GenerateOpenPanel {+ return currentPanel === 'library' ? 'library' : currentPanel+}++function sortAssetLibraryEntries(+ entries: ProjectedAssetLibraryEntry[],+ sortMode: AssetLibrarySortMode,+): ProjectedAssetLibraryEntry[] {+ return [...entries].sort((left, right) => compareAssetLibraryEntries(left, right, sortMode))+}++function compareAssetLibraryEntryGroups(+ left: AssetLibraryEntryGroup,+ right: AssetLibraryEntryGroup,+ sortMode: Exclude<AssetLibrarySortMode, 'type'>,+): number {+ const entryComparison = compareAssetLibraryEntries(left.entries[0], right.entries[0], sortMode)+ if (entryComparison !== 0) return entryComparison++ return (ASSET_LIBRARY_CAPABILITY_ORDER.get(left.capability) ?? Number.MAX_SAFE_INTEGER)+ - (ASSET_LIBRARY_CAPABILITY_ORDER.get(right.capability) ?? Number.MAX_SAFE_INTEGER)+}++function compareAssetLibraryEntries(+ left: ProjectedAssetLibraryEntry,+ right: ProjectedAssetLibraryEntry,+ sortMode: AssetLibrarySortMode,+): number {+ if (sortMode === 'date') {+ const leftTime = resolveAssetLibrarySortTimestamp(left)+ const rightTime = resolveAssetLibrarySortTimestamp(right)+ if (leftTime !== null && rightTime !== null && leftTime !== rightTime) return rightTime - leftTime+ if (leftTime !== null && rightTime === null) return -1+ if (leftTime === null && rightTime !== null) return 1+ }++ return compareAssetLibraryEntryNames(left, right)+}++function compareAssetLibraryEntryNames(left: ProjectedAssetLibraryEntry, right: ProjectedAssetLibraryEntry): number {+ const displayNameComparison = left.displayName.localeCompare(right.displayName, undefined, { sensitivity: 'base' })+ if (displayNameComparison !== 0) return displayNameComparison+ const workspacePathComparison = left.workspacePath.localeCompare(right.workspacePath, undefined, { sensitivity: 'base' })+ if (workspacePathComparison !== 0) return workspacePathComparison+ return left.id.localeCompare(right.id, undefined, { sensitivity: 'base' })+}++function resolveAssetLibrarySortTimestamp(entry: ProjectedAssetLibraryEntry): number | null {+ return parseAssetLibrarySortTimestamp(entry.createdAt) ?? parseAssetLibrarySortTimestamp(entry.updatedAt)+}++function parseAssetLibrarySortTimestamp(value: string | undefined): number | null {+ if (typeof value !== 'string' || value.length === 0) return null+ const epochMs = Date.parse(value)+ return Number.isFinite(epochMs) ? epochMs : null+}++function normalizeAssetLibrarySearchQuery(searchQuery: string): string {+ return searchQuery.trim().toLocaleLowerCase()+}++function matchesAssetLibraryEntrySearch(entry: ProjectedAssetLibraryEntry, normalizedSearchQuery: string): boolean {+ return [+ entry.displayName,+ entry.workspacePath,+ entry.source?.workspacePath,+ entry.source?.displayName,+ entry.manifest?.workspacePath,+ entry.capability,+ entry.sourceScope,+ ...entry.warnings,+ ]+ .filter((value): value is string => typeof value === 'string' && value.length > 0)+ .some((value) => matchesAssetLibrarySearch(value, normalizedSearchQuery))+}++function matchesAssetLibrarySearch(value: string, normalizedSearchQuery: string): boolean {+ return value.toLocaleLowerCase().includes(normalizedSearchQuery)+}++function hasInternalAssetLibraryDirectory(workspacePath: string): boolean {+ const segments = workspacePath.replace(/\\/g, '/').trim().split('/').filter(Boolean)+ return segments.slice(1, -1).some((segment) => segment.startsWith('.') || ASSET_LIBRARY_INTERNAL_DIRECTORY_NAMES.has(segment.toLocaleLowerCase()))+}diff --git a/apps/forge-desktop/src/areas/generate/components/ChatPanel.tsx b/apps/forge-desktop/src/areas/generate/components/ChatPanel.tsxnew file mode 100644index 000000000..053e780a9--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/components/ChatPanel.tsx@@ -0,0 +1,706 @@+import { useEffect, useMemo, useRef, useState } from 'react'+import { useAppStore } from '@shared/stores/appStore'+import { useAgentStore, PROVIDERS, providerBaseUrl } from '@shared/stores/agentStore'+import { useLlmModels } from '@shared/stores/llmModelsStore'+import { useWorkflowsStore } from '@shared/stores/workflowsStore'+import { useExtensionsStore } from '@shared/stores/extensionsStore'+import { useWorkflowRunStore } from '@areas/workflows/workflowRunStore'+import { buildAllWorkflowExtensions } from '@areas/workflows/mockExtensions'++// ─── Types ────────────────────────────────────────────────────────────────────++import type { ThinkingMode } from '@shared/stores/agentStore'+import type { Workflow } from '@shared/types/electron.d'++interface Message {+ id: string+ role: 'user' | 'assistant'+ content: string+ thinking?: string+ imageDataUrls?: string[]+ actions?: ActionDone[]+}++interface ActionDone {+ tool: string+ result: string+ payload?: {+ type: string+ url?: string+ face_count?: number+ workflow_id?: string+ workflow_name?: string+ workflow?: Omit<Workflow, 'id' | 'createdAt' | 'updatedAt'>+ } | null+}++// ─── Constants ────────────────────────────────────────────────────────────────++const COLLAPSE_AFTER = 4++// ─── Prose renderer — basic markdown-like ────────────────────────────────────++function ProseMessage({ content }: { content: string }): JSX.Element {+ const blocks = content.split(/\n\n+/)+ return (+ <div className="flex flex-col gap-2.5 text-[12.5px] leading-relaxed text-zinc-200">+ {blocks.map((block, i) => {+ const lines = block.split('\n')+ const isList = lines.every((l) => /^[-•*]\s/.test(l.trim()) || l.trim() === '')+ if (isList) {+ return (+ <ul key={i} className="flex flex-col gap-1 pl-3">+ {lines.filter(Boolean).map((l, j) => (+ <li key={j} className="flex gap-2">+ <span className="text-zinc-500 shrink-0 mt-px">•</span>+ <span>{l.replace(/^[-•*]\s/, '')}</span>+ </li>+ ))}+ </ul>+ )+ }+ return (+ <p key={i} className="whitespace-pre-wrap">+ {block}+ </p>+ )+ })}+ </div>+ )+}++// ─── Actions card ─────────────────────────────────────────────────────────────++const TOOL_LABELS: Record<string, string> = {+ decimate_mesh: 'Decimated mesh',+ smooth_mesh: 'Smoothed mesh',+ list_models: 'Listed models',+ unload_models: 'Unloaded models',+ get_mesh_info: 'Inspected mesh',+ get_generation_status:'Checked generation',+ list_workflows: 'Listed workflows',+ run_workflow: 'Ran workflow',+ create_workflow: 'Created workflow',+}++function ActionsCard({ actions, onUndo }: { actions: ActionDone[]; onUndo?: () => void }): JSX.Element {+ const [expanded, setExpanded] = useState(false)+ const meshActions = actions.filter((a) => a.payload?.type === 'mesh_update')+ const canUndo = meshActions.length > 0 && !!onUndo++ return (+ <div className="rounded-xl border border-zinc-700/50 bg-zinc-800/40 overflow-hidden text-[11px]">+ {/* Header */}+ <div className="flex items-center justify-between px-3 py-2 border-b border-zinc-700/40">+ <span className="text-zinc-300 font-medium">+ {actions.length} action{actions.length > 1 ? 's' : ''} performed+ </span>+ <div className="flex items-center gap-2">+ {canUndo && (+ <button+ onClick={onUndo}+ className="flex items-center gap-1 text-zinc-400 hover:text-zinc-200 transition-colors"+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M3 7v6h6" /><path d="M3 13a9 9 0 1 0 2.28-5.93" />+ </svg>+ Undo+ </button>+ )}+ <button+ onClick={() => setExpanded((v) => !v)}+ className="text-zinc-500 hover:text-zinc-300 transition-colors"+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"+ className={`transition-transform ${expanded ? 'rotate-180' : ''}`}>+ <polyline points="6 9 12 15 18 9" />+ </svg>+ </button>+ </div>+ </div>++ {/* Rows */}+ {expanded && (+ <div className="flex flex-col divide-y divide-zinc-700/30">+ {actions.map((a, i) => (+ <div key={i} className="flex items-center justify-between px-3 py-1.5">+ <span className="text-zinc-400">{TOOL_LABELS[a.tool] ?? a.tool.replace(/_/g, ' ')}</span>+ {a.payload?.type === 'mesh_update' && a.payload.face_count && (+ <span className="text-emerald-400 font-mono">{a.payload.face_count.toLocaleString()} faces</span>+ )}+ {a.payload?.type === 'run_workflow' && (+ <span className="text-violet-400">{a.payload.workflow_name}</span>+ )}+ {a.payload?.type === 'create_workflow' && a.payload.workflow && (+ <span className="text-violet-400">{a.payload.workflow.name}</span>+ )}+ </div>+ ))}+ </div>+ )}+ </div>+ )+}++// ─── Feedback row ─────────────────────────────────────────────────────────────++function FeedbackRow({ content }: { content: string }): JSX.Element {+ const [copied, setCopied] = useState(false)++ function handleCopy() {+ navigator.clipboard.writeText(content)+ setCopied(true)+ setTimeout(() => setCopied(false), 1500)+ }++ return (+ <div className="flex items-center gap-2 pt-0.5">+ <button+ onClick={handleCopy}+ title="Copy"+ className="text-zinc-600 hover:text-zinc-400 transition-colors"+ >+ {copied ? (+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <polyline points="20 6 9 17 4 12" />+ </svg>+ ) : (+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <rect x="9" y="9" width="13" height="13" rx="2" /><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />+ </svg>+ )}+ </button>+ <button title="Good response" className="text-zinc-600 hover:text-zinc-400 transition-colors">+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3H14z" />+ <path d="M7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3" />+ </svg>+ </button>+ <button title="Bad response" className="text-zinc-600 hover:text-zinc-400 transition-colors">+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3H10z" />+ <path d="M17 2h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17" />+ </svg>+ </button>+ </div>+ )+}++// ─── Thinking block ───────────────────────────────────────────────────────────++function ThinkingBlock({ content }: { content: string }): JSX.Element {+ const [open, setOpen] = useState(false)+ return (+ <div className="text-[11px]">+ <button+ onClick={() => setOpen((v) => !v)}+ className="flex items-center gap-1.5 text-zinc-500 hover:text-zinc-400 transition-colors"+ >+ {/* brain icon */}+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">+ <path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96-.44 2.5 2.5 0 0 1-2.96-3.08 3 3 0 0 1-.34-5.58 2.5 2.5 0 0 1 1.32-4.24 2.5 2.5 0 0 1 1.98-3A2.5 2.5 0 0 1 9.5 2Z"/>+ <path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96-.44 2.5 2.5 0 0 0 2.96-3.08 3 3 0 0 0 .34-5.58 2.5 2.5 0 0 0-1.32-4.24 2.5 2.5 0 0 0-1.98-3A2.5 2.5 0 0 0 14.5 2Z"/>+ </svg>+ <span>Reasoning</span>+ <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"+ className={`transition-transform ${open ? 'rotate-180' : ''}`}>+ <polyline points="6 9 12 15 18 9" />+ </svg>+ </button>+ {open && (+ <div className="mt-2 pl-3 border-l-2 border-zinc-700">+ <p className="text-zinc-500 italic leading-relaxed whitespace-pre-wrap">{content}</p>+ </div>+ )}+ </div>+ )+}++// ─── Workflow progress card ────────────────────────────────────────────────────++function WorkflowProgressCard({ name }: { name: string }): JSX.Element {+ const runState = useWorkflowRunStore((s) => s.runState)+ const pct = runState.blockProgress+ return (+ <div className="rounded-xl border border-zinc-700/50 bg-zinc-800/40 px-3 py-2.5 flex flex-col gap-2">+ <div className="flex items-center justify-between text-[11px]">+ <div className="flex items-center gap-2">+ <span className="w-1.5 h-1.5 rounded-full bg-accent animate-pulse shrink-0" />+ <span className="text-zinc-300 font-medium truncate">{name}</span>+ </div>+ <span className="text-zinc-500 shrink-0">{pct}%</span>+ </div>+ <div className="h-0.5 bg-zinc-700 rounded-full overflow-hidden">+ <div className="h-full bg-accent rounded-full transition-all duration-500" style={{ width: `${pct}%` }} />+ </div>+ {runState.blockStep && (+ <p className="text-[10px] text-zinc-500 truncate">{runState.blockStep}</p>+ )}+ </div>+ )+}++// ─── Main component ──────────────────────────────────────────────────────────++export default function ChatPanel(): JSX.Element {+ const { provider, localModel, external, defaultThinking } = useAgentStore()+ const { models: llmModels } = useLlmModels()+ const isLocal = provider === 'local'+ const externalConfig = external[provider]++ const [messages, setMessages] = useState<Message[]>([])+ const [input, setInput] = useState('')+ const [isLoading, setIsLoading] = useState(false)+ const [error, setError] = useState<string | null>(null)+ const [showAll, setShowAll] = useState(false)+ // null = follow the default from Settings, which hydrates asynchronously.+ const [localPick, setLocalPick] = useState<string | null>(null)+ const model = isLocal ? (localPick ?? localModel) : (externalConfig?.model ?? '')+ // code/cad models are node tools, not chat models.+ const localModels = llmModels.filter((m) => m.downloaded && !(m.tags ?? []).some((t) => t === 'code' || t === 'cad'))+ const [showModelPicker, setShowModelPicker] = useState(false)+ const [pendingWorkflow, setPendingWorkflow] = useState<{ id: string; name: string } | null>(null)+ const [attachments, setAttachments] = useState<string[]>([]) // data URLs+ const [isDragging, setIsDragging] = useState(false)+ const [thinkingMode, setThinkingMode] = useState<ThinkingMode>(defaultThinking)+ const endRef = useRef<HTMLDivElement>(null)+ const textareaRef = useRef<HTMLTextAreaElement>(null)+ const modelPickerRef = useRef<HTMLDivElement>(null)+ const fileInputRef = useRef<HTMLInputElement>(null)+ const messagesRef = useRef<Message[]>([])+ messagesRef.current = messages++ const apiUrl = useAppStore((s) => s.apiUrl)+ const currentJob = useAppStore((s) => s.currentJob)+ const meshStats = useAppStore((s) => s.meshStats)+ const updateCurrentJob = useAppStore((s) => s.updateCurrentJob)+ const pushMeshUrl = useAppStore((s) => s.pushMeshUrl)+ const undoMesh = useAppStore((s) => s.undoMesh)++ const workflows = useWorkflowsStore((s) => s.workflows)+ const saveWorkflow = useWorkflowsStore((s) => s.save)+ const setActiveWorkflow = useWorkflowsStore((s) => s.setActive)+ const { modelExtensions, processExtensions } = useExtensionsStore()+ const runWorkflow = useWorkflowRunStore((s) => s.run)+ const runState = useWorkflowRunStore((s) => s.runState)+ const allExtensions = useMemo(+ () => buildAllWorkflowExtensions(modelExtensions, processExtensions),+ [modelExtensions, processExtensions],+ )++ // Close model picker on outside click+ useEffect(() => {+ if (!showModelPicker) return+ const handler = (e: MouseEvent) => {+ if (modelPickerRef.current && !modelPickerRef.current.contains(e.target as Node))+ setShowModelPicker(false)+ }+ document.addEventListener('mousedown', handler)+ return () => document.removeEventListener('mousedown', handler)+ }, [showModelPicker])++ // Watch workflow completion → send follow-up to agent+ useEffect(() => {+ if (!pendingWorkflow) return+ if (runState.status !== 'done' && runState.status !== 'error') return++ const wf = pendingWorkflow+ setPendingWorkflow(null)++ if (runState.status === 'error') {+ setMessages((prev) => [...prev, {+ id: `sys-${Date.now()}`,+ role: 'assistant',+ content: `The workflow '${wf.name}' failed: ${runState.error ?? 'Unknown error'}`,+ }])+ return+ }++ // Update viewer with the generated mesh+ if (runState.outputUrl) {+ updateCurrentJob({ outputUrl: runState.outputUrl, status: 'done', progress: 100 })+ pushMeshUrl(runState.outputUrl)+ }++ // Send automatic follow-up to agent+ const completionCtx = `Workflow '${wf.name}' just completed.${runState.outputUrl ? ` Output mesh: ${runState.outputUrl}` : ''} Ask the user what they'd like to do next.`+ callAgent(messagesRef.current, { workflowCompletion: completionCtx })+ // eslint-disable-next-line react-hooks/exhaustive-deps -- fire on run-status transition; error/outputUrl read atomically+ }, [runState.status, pendingWorkflow])++ useEffect(() => {+ endRef.current?.scrollIntoView({ behavior: 'smooth' })+ }, [messages, isLoading, pendingWorkflow])++ function buildContext(): Record<string, unknown> {+ const ctx: Record<string, unknown> = {}+ if (currentJob?.outputUrl) ctx.currentMeshPath = currentJob.outputUrl.replace('/workspace/', '')+ if (meshStats?.triangles) ctx.meshTriangles = meshStats.triangles+ if (workflows.length > 0) ctx.workflows = workflows.map((w) => ({ id: w.id, name: w.name }))+ if (allExtensions.length > 0) ctx.extensions = allExtensions.map((e) => ({+ id: e.id, name: e.name, input: e.input, output: e.output,+ }))+ return ctx+ }++ async function callAgent(msgs: Message[], extraContext: Record<string, unknown> = {}) {+ setIsLoading(true)+ setError(null)+ try {+ const context = { ...buildContext(), ...extraContext }++ // Inject workflow completion as a system hint if present+ const apiMessages = msgs.map((m) => {+ const entry: { role: string; content: string; images?: string[] } = {+ role: m.role,+ content: m.content,+ }+ if (m.imageDataUrls?.length) {+ entry.images = m.imageDataUrls+ }+ return entry+ })+ if (extraContext.workflowCompletion) {+ apiMessages.push({ role: 'user', content: `[System] ${extraContext.workflowCompletion}` })+ delete context.workflowCompletion+ }++ const res = await fetch(`${apiUrl}/agent/chat`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ messages: apiMessages,+ model,+ provider: isLocal+ ? { type: 'local' }+ : { type: 'external', base_url: providerBaseUrl(provider, externalConfig), api_key: externalConfig?.apiKey ?? '' },+ context,+ thinking: thinkingMode,+ }),+ })+ if (!res.ok) throw new Error(`API error ${res.status}`)++ const data: { message: string; actions: ActionDone[]; thinking?: string } = await res.json()++ setMessages((prev) => [...prev, {+ id: `a-${Date.now()}`,+ role: 'assistant',+ content: data.message,+ thinking: data.thinking ?? undefined,+ actions: data.actions?.length ? data.actions : undefined,+ }])++ // Extract base64 from the most recent user message that had an image attached+ const latestImageDataUrl = [...msgs].reverse()+ .find((m) => m.role === 'user' && m.imageDataUrls?.length)+ ?.imageDataUrls?.[0]+ const overrideImageData = latestImageDataUrl ? latestImageDataUrl.split(',')[1] : undefined++ for (const action of data.actions ?? []) {+ if (action.payload?.type === 'mesh_update' && action.payload.url) {+ updateCurrentJob({ outputUrl: action.payload.url })+ pushMeshUrl(action.payload.url)+ }+ if (action.payload?.type === 'run_workflow' && action.payload.workflow_id) {+ const wf = workflows.find((w) => w.id === action.payload!.workflow_id)+ if (wf) { runWorkflow(wf, allExtensions, overrideImageData); setPendingWorkflow({ id: wf.id, name: wf.name }) }+ }+ if (action.payload?.type === 'create_workflow' && action.payload.workflow) {+ const draft = action.payload.workflow as Omit<Workflow, 'id' | 'createdAt' | 'updatedAt'>+ const now = new Date().toISOString()+ const wf: Workflow = { ...draft, id: crypto.randomUUID(), createdAt: now, updatedAt: now }+ const res = await saveWorkflow(wf)+ if (res.success) setActiveWorkflow(wf.id)+ }+ }+ } catch (e: unknown) {+ const msg = e instanceof Error ? e.message : String(e)+ setError(msg.includes('fetch') ? 'Cannot reach Modly API. Is the backend running?' : msg)+ } finally {+ setIsLoading(false)+ }+ }++ function handleFiles(files: File[]) {+ files.forEach((file) => {+ if (!file.type.startsWith('image/')) return+ const reader = new FileReader()+ reader.onload = (e) => {+ const dataUrl = e.target?.result as string+ setAttachments((prev) => [...prev, dataUrl])+ }+ reader.readAsDataURL(file)+ })+ }++ function handleDragOver(e: React.DragEvent) {+ e.preventDefault()+ setIsDragging(true)+ }++ function handleDragLeave(e: React.DragEvent) {+ if (!(e.currentTarget as HTMLElement).contains(e.relatedTarget as Node)) setIsDragging(false)+ }++ function handleDrop(e: React.DragEvent) {+ e.preventDefault()+ setIsDragging(false)+ handleFiles(Array.from(e.dataTransfer.files))+ }++ function adjustHeight() {+ const el = textareaRef.current+ if (!el) return+ el.style.height = 'auto'+ el.style.height = `${Math.min(el.scrollHeight, 160)}px`+ }++ async function handleSend() {+ const text = input.trim()+ if (!text || isLoading || pendingWorkflow) return++ const userMsg: Message = {+ id: `u-${Date.now()}`,+ role: 'user',+ content: text,+ ...(attachments.length ? { imageDataUrls: [...attachments] } : {}),+ }+ const nextMessages = [...messages, userMsg]+ setMessages(nextMessages)+ setInput('')+ setAttachments([])+ if (textareaRef.current) textareaRef.current.style.height = 'auto'+ await callAgent(nextMessages)+ }++ function handleKeyDown(e: React.KeyboardEvent<HTMLTextAreaElement>) {+ if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend() }+ }++ // Collapsed history+ const collapsed = !showAll && messages.length > COLLAPSE_AFTER+ const hidden = collapsed ? messages.length - COLLAPSE_AFTER : 0+ const visible = collapsed ? messages.slice(-COLLAPSE_AFTER) : messages++ return (+ <div+ className="flex flex-col flex-1 min-h-0 relative"+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ >+ {/* Drag overlay */}+ {isDragging && (+ <div className="absolute inset-0 z-50 flex items-center justify-center rounded-xl border-2 border-dashed border-accent/60 bg-accent/5 pointer-events-none">+ <p className="text-[12px] text-accent font-medium">Drop image here</p>+ </div>+ )}++ {/* Messages */}+ <div className="flex-1 overflow-y-auto min-h-0 flex flex-col">++ {/* Empty state */}+ {messages.length === 0 && (+ <div className="flex-1 flex flex-col items-center justify-center gap-3 px-5 py-10">+ <div className="w-9 h-9 rounded-xl bg-accent/10 border border-accent/20 flex items-center justify-center text-accent">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">+ <rect x="3" y="11" width="18" height="10" rx="2" />+ <circle cx="12" cy="5" r="2" /><path d="M12 7v4" />+ </svg>+ </div>+ <p className="text-[11px] text-zinc-500 text-center leading-relaxed">+ Ask me to generate, optimize,<br />or run a workflow.+ </p>+ </div>+ )}++ {/* Previous messages pill */}+ {collapsed && (+ <button+ onClick={() => setShowAll(true)}+ className="mx-4 mt-4 mb-1 flex items-center gap-1 text-[11px] text-zinc-500 hover:text-zinc-300 transition-colors self-start"+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <polyline points="6 9 12 15 18 9" />+ </svg>+ {hidden} previous message{hidden > 1 ? 's' : ''}+ </button>+ )}++ {/* Message list */}+ <div className="flex flex-col px-4 py-3 gap-5">+ {visible.map((msg) => (+ <div key={msg.id}>+ {msg.role === 'user' ? (+ /* User message */+ <div className="flex flex-col items-end gap-1.5">+ {msg.imageDataUrls && msg.imageDataUrls.length > 0 && (+ <div className="flex flex-wrap gap-1.5 justify-end max-w-[80%]">+ {msg.imageDataUrls.map((url, i) => (+ <img key={i} src={url} alt="" className="max-h-36 max-w-full rounded-xl object-cover border border-zinc-700/50" />+ ))}+ </div>+ )}+ <div className="max-w-[80%] px-3 py-2 rounded-2xl rounded-br-sm bg-zinc-800 border border-zinc-700/50 text-[12px] text-zinc-200 leading-relaxed">+ {msg.content}+ </div>+ </div>+ ) : (+ /* Assistant message */+ <div className="flex flex-col gap-3">+ {msg.thinking && <ThinkingBlock content={msg.thinking} />}+ <ProseMessage content={msg.content} />+ {msg.actions && msg.actions.length > 0 && (+ <ActionsCard actions={msg.actions} onUndo={undoMesh} />+ )}+ <FeedbackRow content={msg.content} />+ </div>+ )}+ </div>+ ))}++ {/* Workflow progress card — visible while agent waits for workflow */}+ {pendingWorkflow && <WorkflowProgressCard name={pendingWorkflow.name} />}++ {/* Loading indicator */}+ {isLoading && (+ <div className="flex gap-1 items-center py-1">+ {[0, 1, 2].map((i) => (+ <span key={i}+ className="w-1.5 h-1.5 rounded-full bg-zinc-600 animate-bounce"+ style={{ animationDelay: `${i * 130}ms` }}+ />+ ))}+ </div>+ )}++ {/* Error */}+ {error && (+ <div className="px-3 py-2 rounded-lg bg-red-950/40 border border-red-800/40">+ <p className="text-[11px] text-red-400">{error}</p>+ </div>+ )}++ <div ref={endRef} />+ </div>+ </div>++ {/* Input bar */}+ <div className="shrink-0 px-3 pb-3 pt-2 border-t border-zinc-800">+ <input+ ref={fileInputRef}+ type="file"+ accept="image/*"+ multiple+ className="hidden"+ onChange={(e) => { if (e.target.files) handleFiles(Array.from(e.target.files)); e.target.value = '' }}+ />+ <div className="flex flex-col gap-1.5 bg-zinc-900 border border-zinc-700/60 rounded-2xl px-3 py-2.5">+ {/* Attachment previews */}+ {attachments.length > 0 && (+ <div className="flex flex-wrap gap-1.5">+ {attachments.map((url, i) => (+ <div key={i} className="relative group">+ <img src={url} alt="" className="h-14 w-14 object-cover rounded-lg border border-zinc-700/50" />+ <button+ onClick={() => setAttachments((prev) => prev.filter((_, j) => j !== i))}+ className="absolute -top-1 -right-1 w-4 h-4 rounded-full bg-zinc-700 border border-zinc-600 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"+ >+ <svg width="7" height="7" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">+ <line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />+ </svg>+ </button>+ </div>+ ))}+ </div>+ )}+ <textarea+ ref={textareaRef}+ value={input}+ onChange={(e) => { setInput(e.target.value); adjustHeight() }}+ onKeyDown={handleKeyDown}+ placeholder="Ask Modly…"+ rows={1}+ spellCheck={false}+ className="w-full bg-transparent text-[12.5px] text-zinc-200 placeholder-zinc-600 focus:outline-none resize-none leading-relaxed overflow-hidden"+ />+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ {/* Attach image button */}+ <button+ onClick={() => fileInputRef.current?.click()}+ title="Attach image"+ className="text-zinc-600 hover:text-zinc-400 transition-colors"+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="16" /><line x1="8" y1="12" x2="16" y2="12" />+ </svg>+ </button>+ {/* Thinking toggle */}+ <button+ onClick={() => setThinkingMode((m) => m === 'auto' ? 'on' : m === 'on' ? 'off' : 'auto')}+ title={`Thinking: ${thinkingMode}`}+ className={`transition-colors ${thinkingMode === 'on' ? 'text-accent' : thinkingMode === 'off' ? 'text-zinc-700' : 'text-zinc-600 hover:text-zinc-400'}`}+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">+ <path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96-.44 2.5 2.5 0 0 1-2.96-3.08 3 3 0 0 1-.34-5.58 2.5 2.5 0 0 1 1.32-4.24 2.5 2.5 0 0 1 1.98-3A2.5 2.5 0 0 1 9.5 2Z"/>+ <path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96-.44 2.5 2.5 0 0 0 2.96-3.08 3 3 0 0 0 .34-5.58 2.5 2.5 0 0 0-1.32-4.24 2.5 2.5 0 0 0-1.98-3A2.5 2.5 0 0 0 14.5 2Z"/>+ {thinkingMode === 'off' && <line x1="4" y1="4" x2="20" y2="20" strokeWidth="2" />}+ </svg>+ </button>+ {/* Model selector */}+ <div className="relative" ref={modelPickerRef}>+ <button+ onClick={() => setShowModelPicker((v) => !v)}+ className="flex items-center gap-1 text-[10px] text-zinc-500 hover:text-zinc-300 transition-colors"+ >+ {isLocal ? (localModels.find((m) => m.id === model)?.name ?? model) : (model || PROVIDERS[provider].label)}+ <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <polyline points="6 9 12 15 18 9" />+ </svg>+ </button>++ {showModelPicker && (+ <div className="absolute bottom-full mb-2 left-0 z-50 bg-zinc-900 border border-zinc-700/60 rounded-xl shadow-xl overflow-hidden min-w-[180px]">+ {!isLocal ? (+ <p className="px-3 py-2.5 text-[11px] text-zinc-500">{PROVIDERS[provider].label} — change the model in Settings → Agent.</p>+ ) : localModels.length === 0 ? (+ <p className="px-3 py-2.5 text-[11px] text-zinc-500">No local model downloaded — open Settings → Agent.</p>+ ) : (+ localModels.map((m) => (+ <button+ key={m.id}+ onClick={() => { setLocalPick(m.id); setShowModelPicker(false) }}+ className={`w-full px-3 py-2 text-left text-[11px] hover:bg-zinc-800 transition-colors flex items-center justify-between gap-3 ${m.id === model ? 'text-zinc-100' : 'text-zinc-400'}`}+ >+ <span className="truncate">{m.name}</span>+ {m.id === model && (+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="shrink-0 text-accent">+ <polyline points="20 6 9 17 4 12" />+ </svg>+ )}+ </button>+ ))+ )}+ </div>+ )}+ </div>+ </div>++ <button+ onClick={handleSend}+ disabled={!input.trim() || isLoading}+ className="w-6 h-6 rounded-full bg-accent hover:bg-accent-dark disabled:opacity-30 disabled:cursor-not-allowed text-white flex items-center justify-center transition-colors shrink-0"+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">+ <line x1="12" y1="19" x2="12" y2="5" /><polyline points="5 12 12 5 19 12" />+ </svg>+ </button>+ </div>+ </div>+ <p className="mt-1.5 text-[10px] text-zinc-700 text-center">Shift+Enter for new line</p>+ </div>++ </div>+ )+}diff --git a/apps/forge-desktop/src/areas/generate/components/GenerationHUD.tsx b/apps/forge-desktop/src/areas/generate/components/GenerationHUD.tsxnew file mode 100644index 000000000..6a9314e5a--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/components/GenerationHUD.tsx@@ -0,0 +1,179 @@+import { useEffect, useRef, useState } from 'react'+import { useGeneration } from '@shared/hooks/useGeneration'++function formatElapsed(seconds: number): string {+ const m = Math.floor(seconds / 60)+ const s = seconds % 60+ return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`+}++// Convert tqdm bar text to a clean "Verbing (N%)" form. Examples:+// "Diffusion Sampling: 60%|████| 3/5 [..." → "Diffusing (60%)"+// "Volume Decoding: 42%|██▏ | 1752/4200 [..." → "Decoding (42%)"+// "Loading pipeline components...: 100%|███| 4/4" → "Loading (100%)"+// Anything that isn't a tqdm progress line returns null so the caller+// leaves the HUD's sub-line untouched instead of filling it with noise.+const PHASE_VERB: Array<[RegExp, string]> = [+ [/diffusion|sampling/i, 'Generating'],+ [/volume|flashvdm|decoding/i, 'Decoding'],+ [/surface|extract/i, 'Extracting'],+ [/loading|download/i, 'Loading'],+]++function parseTqdmLine(line: string): string | null {+ const m = line.match(/^(.+?):\s*(\d+)%\|/)+ if (!m) return null+ const desc = m[1].replace(/\.+$/, '').trim()+ const pct = m[2]+ const verb =+ PHASE_VERB.find(([re]) => re.test(desc))?.[1] ??+ desc.replace(/^./, (c) => c.toUpperCase())+ return `${verb} (${pct}%)`+}++function parseProgressFromStderr(chunk: string): string | null {+ // One chunk may contain multiple tqdm ticks separated by \r or \n;+ // show the most recent tqdm-like line.+ const lines = chunk.split(/[\r\n]+/).filter(Boolean)+ for (let i = lines.length - 1; i >= 0; i--) {+ const parsed = parseTqdmLine(lines[i]!)+ if (parsed) return parsed+ }+ return null+}++export default function GenerationHUD(): JSX.Element | null {+ const { currentJob, reset } = useGeneration()+ const [elapsed, setElapsed] = useState(0)+ const [tqdmLog, setTqdmLog] = useState<string | null>(null)+ const [copied, setCopied] = useState(false)+ const copyTimeout = useRef<ReturnType<typeof setTimeout> | null>(null)++ function handleCopyError(text: string) {+ navigator.clipboard.writeText(text)+ setCopied(true)+ if (copyTimeout.current) clearTimeout(copyTimeout.current)+ copyTimeout.current = setTimeout(() => setCopied(false), 2000)+ }++ const status = currentJob?.status+ const isActive = status === 'uploading' || status === 'generating'+ const isVisible = status === 'uploading' || status === 'generating' || status === 'error'++ // Elapsed timer — based on currentJob.createdAt so it survives navigation+ useEffect(() => {+ if (isActive && currentJob?.createdAt) {+ const id = setInterval(() => {+ setElapsed(Math.floor((Date.now() - currentJob.createdAt) / 1000))+ }, 1000)+ return () => clearInterval(id)+ } else {+ setElapsed(0)+ }+ }, [isActive, currentJob?.createdAt])++ // tqdm log listener — parse to "Verbing (N%)" and skip non-progress noise+ useEffect(() => {+ if (isActive) {+ setTqdmLog(null)+ window.electron.python.onLog((line) => {+ const parsed = parseProgressFromStderr(line)+ if (parsed !== null) {+ setTqdmLog((prev) => (prev === parsed ? prev : parsed))+ }+ })+ return () => { window.electron.python.offLog(); setTqdmLog(null) }+ }+ }, [isActive])++ if (!currentJob || !isVisible) return null++ const { progress, step, error } = currentJob++ return (+ <div className="absolute bottom-8 left-1/2 animate-slide-up z-20 w-96 pointer-events-auto">+ <div className="bg-zinc-900/95 backdrop-blur-md border border-zinc-700/60 rounded-2xl shadow-2xl overflow-hidden">++ {/* Generating / uploading */}+ {isActive && (+ <div className="px-5 py-4 flex flex-col gap-3">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2.5">+ <div className="w-1.5 h-1.5 rounded-full bg-accent animate-pulse" />+ <span className="text-sm font-medium text-zinc-200">+ {step ?? (status === 'uploading' ? 'Reading image…' : 'Generating 3D mesh…')}+ </span>+ </div>+ <span className="text-xs tabular-nums text-zinc-500">{formatElapsed(elapsed)}</span>+ </div>++ <div className="flex flex-col gap-1.5">+ <div className="h-1.5 bg-zinc-800 rounded-full overflow-hidden">+ <div+ className="h-full bg-accent rounded-full transition-all duration-700 ease-out"+ style={{ width: `${progress}%` }}+ />+ </div>+ <div className="flex items-center justify-between gap-2">+ {tqdmLog && (+ <span className="text-[11px] text-zinc-500 truncate font-mono">{tqdmLog}</span>+ )}+ <span className="text-xs text-zinc-600 tabular-nums shrink-0 ml-auto">{progress}%</span>+ </div>+ </div>+ </div>+ )}++ {/* Error */}+ {status === 'error' && (+ <div className="px-5 py-4 flex flex-col gap-3 animate-fade-in">+ <div className="flex items-center gap-2.5">+ <div className="w-6 h-6 rounded-full bg-red-500/15 border border-red-500/30 flex items-center justify-center shrink-0">+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" className="text-red-400">+ <line x1="18" y1="6" x2="6" y2="18" />+ <line x1="6" y1="6" x2="18" y2="18" />+ </svg>+ </div>+ <span className="text-sm font-medium text-zinc-200">Generation failed</span>+ </div>+ <pre className="text-xs text-red-400 bg-red-950/40 border border-red-900/40 rounded-lg px-3 py-2 max-h-48 overflow-y-auto whitespace-pre-wrap break-words select-text font-mono leading-relaxed">+ {error}+ </pre>+ <div className="flex gap-2">+ <button+ onClick={reset}+ className="flex-1 py-2.5 rounded-xl bg-zinc-800 hover:bg-zinc-700 text-zinc-200 text-sm font-medium transition-colors"+ >+ Try again+ </button>+ {error && (+ <button+ onClick={() => handleCopyError(error)}+ title="Copy error"+ className="flex items-center gap-1.5 px-4 py-2.5 rounded-xl bg-zinc-800 hover:bg-zinc-700 text-zinc-400 hover:text-zinc-200 text-sm font-medium transition-colors"+ >+ {copied ? (+ <>+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className="text-green-400">+ <polyline points="20 6 9 17 4 12" />+ </svg>+ <span className="text-green-400">Copied</span>+ </>+ ) : (+ <>+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />+ </svg>+ <span>Copy</span>+ </>+ )}+ </button>+ )}+ </div>+ </div>+ )}+ </div>+ </div>+ )+}diff --git a/apps/forge-desktop/src/areas/generate/components/GenerationOptions.tsx b/apps/forge-desktop/src/areas/generate/components/GenerationOptions.tsxnew file mode 100644index 000000000..41841deea--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/components/GenerationOptions.tsx@@ -0,0 +1,501 @@+import { useEffect, useRef, useState } from 'react'+import { useAppStore } from '@shared/stores/appStore'+import { useApi } from '@shared/hooks/useApi'+import { FieldLabel, Tooltip, ConfirmModal } from '@shared/components/ui'++import type { CatalogModel } from '../models'++const REMESH_OPTIONS = [+ { label: 'Quad-Dominant', value: 'quad' },+ { label: 'Triangle', value: 'triangle' },+ { label: 'None', value: 'none' },+] as const++// ─── Schema types ──────────────────────────────────────────────────────────────++interface ParamSchema {+ id: string+ label: string+ type: 'select' | 'float' | 'int'+ default: any+ min?: number+ max?: number+ step?: number+ options?: { value: any; label: string }[]+ tooltip?: string+}++// ─── Dynamic parameter renderers ───────────────────────────────────────────────++function ShuffleIcon(): JSX.Element {+ return (+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <polyline points="17 1 21 5 17 9" />+ <path d="M3 11V9a4 4 0 0 1 4-4h14" />+ <polyline points="7 23 3 19 7 15" />+ <path d="M21 13v2a4 4 0 0 1-4 4H3" />+ </svg>+ )+}++function SelectParam({ schema, value, onChange }: { schema: ParamSchema; value: any; onChange: (v: any) => void }): JSX.Element {+ return (+ <div className="flex flex-col gap-1.5">+ <FieldLabel label={schema.label} tooltip={schema.tooltip} />+ <div className="flex gap-1.5">+ {schema.options?.map((opt) => (+ <button+ key={String(opt.value)}+ onClick={() => onChange(opt.value)}+ className={`flex-1 py-1.5 text-xs rounded-lg transition-colors ${+ value === opt.value+ ? 'bg-accent text-white'+ : 'bg-zinc-800 text-zinc-400 hover:bg-zinc-700'+ }`}+ >+ {opt.label}+ </button>+ ))}+ </div>+ </div>+ )+}++function FloatParam({ schema, value, onChange }: { schema: ParamSchema; value: any; onChange: (v: any) => void }): JSX.Element {+ const step = schema.step ?? 0.1+ return (+ <div className="flex flex-col gap-1.5">+ <FieldLabel label={schema.label} tooltip={schema.tooltip} />+ <div className="flex items-center gap-2">+ <input+ type="range"+ min={schema.min}+ max={schema.max}+ step={step}+ value={value}+ onChange={(e) => onChange(Number(e.target.value))}+ className="flex-1 accent-violet-500"+ />+ <span className="text-xs tabular-nums text-zinc-300 w-10 text-right">+ {Number(value).toFixed(step < 1 ? 1 : 0)}+ </span>+ </div>+ </div>+ )+}++function IntInput({ value, onChange, placeholder, className }: { value: number; onChange: (v: number) => void; placeholder?: string; className: string }) {+ const [text, setText] = useState(String(value))+ const prevValue = useRef(value)+ if (prevValue.current !== value && parseInt(text, 10) !== value) {+ prevValue.current = value+ setText(String(value))+ }+ return (+ <input+ type="text"+ inputMode="numeric"+ value={text}+ placeholder={placeholder}+ onChange={(e) => {+ const raw = e.target.value+ if (raw !== '' && raw !== '-' && !/^-?\d+$/.test(raw)) return+ setText(raw)+ const n = parseInt(raw, 10)+ if (!isNaN(n)) { prevValue.current = n; onChange(n) }+ }}+ className={className}+ />+ )+}++function IntParam({ schema, value, onChange }: { schema: ParamSchema; value: any; onChange: (v: any) => void }): JSX.Element {+ const isSeed = schema.id === 'seed'+ return (+ <div className="flex flex-col gap-1.5">+ <FieldLabel label={schema.label} tooltip={schema.tooltip} />+ <div className="flex items-center gap-2">+ <IntInput+ value={value}+ onChange={onChange}+ placeholder={isSeed ? '-1 = random' : undefined}+ className="w-full px-3 py-1.5 text-xs rounded-lg bg-zinc-900 border border-zinc-700/60 text-zinc-200 focus:outline-none focus:border-zinc-500"+ />+ {isSeed && (+ <button+ onClick={() => onChange(Math.floor(Math.random() * (schema.max ?? 2147483647)))}+ title="Random seed"+ className="shrink-0 w-7 h-7 flex items-center justify-center rounded-lg bg-zinc-800 hover:bg-zinc-700 text-zinc-400 hover:text-zinc-200 transition-colors"+ >+ <ShuffleIcon />+ </button>+ )}+ </div>+ </div>+ )+}++function DynamicParam({ schema, value, onChange }: { schema: ParamSchema; value: any; onChange: (v: any) => void }): JSX.Element | null {+ switch (schema.type) {+ case 'select': return <SelectParam schema={schema} value={value} onChange={onChange} />+ case 'float': return <FloatParam schema={schema} value={value} onChange={onChange} />+ case 'int': return <IntParam schema={schema} value={value} onChange={onChange} />+ default: return null+ }+}++// ─── Custom model dropdown ────────────────────────────────────────────────────++function ModelIcon(): JSX.Element {+ return (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">+ <path d="M12 2L2 7l10 5 10-5-10-5z" />+ <path d="M2 17l10 5 10-5" />+ <path d="M2 12l10 5 10-5" />+ </svg>+ )+}++function CheckIcon(): JSX.Element {+ return (+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">+ <polyline points="20 6 9 17 4 12" />+ </svg>+ )+}++function ChevronIcon({ open }: { open: boolean }): JSX.Element {+ return (+ <svg+ width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor"+ strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"+ className={`transition-transform duration-200 ${open ? 'rotate-180' : ''}`}+ >+ <polyline points="6 9 12 15 18 9" />+ </svg>+ )+}++interface ModelSelectProps {+ models: CatalogModel[]+ value: string+ onChange: (id: string) => void+}++function ModelSelect({ models, value, onChange }: ModelSelectProps): JSX.Element {+ const [open, setOpen] = useState(false)+ const ref = useRef<HTMLDivElement>(null)++ const selected = models.find((m) => m.id === value)++ useEffect(() => {+ if (!open) return+ const handler = (e: MouseEvent) => {+ if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false)+ }+ document.addEventListener('mousedown', handler)+ return () => document.removeEventListener('mousedown', handler)+ }, [open])++ if (models.length === 0) {+ return (+ <div className="flex items-center gap-2.5 px-3 py-2.5 rounded-xl bg-zinc-900 border border-zinc-800 text-zinc-600 text-sm">+ <div className="w-7 h-7 rounded-lg bg-zinc-800 flex items-center justify-center">+ <ModelIcon />+ </div>+ No model downloaded+ </div>+ )+ }++ return (+ <div ref={ref} className="relative">+ {/* Trigger */}+ <button+ onClick={() => setOpen((v) => !v)}+ className={`+ w-full flex items-center justify-between px-3 py-2.5 rounded-xl+ bg-zinc-900 border transition-all duration-150+ ${open ? 'border-zinc-500 ring-1 ring-zinc-600/40' : 'border-zinc-700/60 hover:border-zinc-600'}+ `}+ >+ <div className="flex items-center gap-2.5">+ <div className="w-7 h-7 rounded-lg bg-zinc-800 border border-zinc-700/50 flex items-center justify-center text-accent">+ <ModelIcon />+ </div>+ <span className="text-sm font-medium text-zinc-200">+ {selected?.name ?? value}+ </span>+ </div>+ <div className="text-zinc-500">+ <ChevronIcon open={open} />+ </div>+ </button>++ {/* Dropdown */}+ {open && (+ <div className="absolute top-full mt-1.5 left-0 right-0 z-50 rounded-xl bg-zinc-900 border border-zinc-700/60 shadow-2xl overflow-hidden">+ {models.map((m, i) => {+ const isSelected = m.id === value+ return (+ <button+ key={m.id}+ onClick={() => { onChange(m.id); setOpen(false) }}+ className={`+ w-full flex items-center justify-between px-3 py-2.5+ transition-colors duration-100 text-left+ ${i > 0 ? 'border-t border-zinc-800' : ''}+ ${isSelected ? 'bg-zinc-800' : 'hover:bg-zinc-800/60'}+ `}+ >+ <div className="flex items-center gap-2.5">+ <div className={`w-7 h-7 rounded-lg flex items-center justify-center border ${+ isSelected+ ? 'bg-accent/15 border-accent/30 text-accent'+ : 'bg-zinc-800 border-zinc-700/50 text-zinc-500'+ }`}>+ <ModelIcon />+ </div>+ <div className="flex flex-col items-start">+ <span className={`text-sm font-medium ${isSelected ? 'text-zinc-100' : 'text-zinc-300'}`}>+ {m.name}+ </span>+ <span className="text-[10px] text-zinc-600 uppercase tracking-wide">{m.id}</span>+ </div>+ </div>+ {isSelected && (+ <span className="text-accent">+ <CheckIcon />+ </span>+ )}+ </button>+ )+ })}+ </div>+ )}+ </div>+ )+}++// ─── Main component ───────────────────────────────────────────────────────────++export default function GenerationOptions(): JSX.Element {+ const { generationOptions, setGenerationOptions, currentJob, apiUrl } = useAppStore()+ const [models, setModels] = useState<CatalogModel[]>([])+ const [textureResolutionRaw, setTextureResolutionRaw] = useState(+ String(generationOptions.textureResolution ?? 512)+ )++ const isDisabled = currentJob?.status === 'uploading' || currentJob?.status === 'generating'+ const [showTextureWarning, setShowTextureWarning] = useState(false)++ // ─── Dynamic params schema ─────────────────────────────────────────────────+ const [schema, setSchema] = useState<ParamSchema[]>([])+ const schemaCache = useRef<Record<string, ParamSchema[]>>({})++ // Fetch schema when model changes+ useEffect(() => {+ const modelId = generationOptions.modelId+ if (!modelId || !apiUrl) {+ setSchema([])+ return+ }++ // Use cache if available+ if (schemaCache.current[modelId]) {+ setSchema(schemaCache.current[modelId])+ initDefaults(schemaCache.current[modelId])+ return+ }++ fetch(`${apiUrl}/model/params?model_id=${encodeURIComponent(modelId)}`)+ .then((res) => res.json())+ .then((params: ParamSchema[]) => {+ schemaCache.current[modelId] = params+ setSchema(params)+ initDefaults(params)+ })+ .catch(() => setSchema([]))+ // eslint-disable-next-line react-hooks/exhaustive-deps -- refetch only when model/apiUrl change; initDefaults is local+ }, [generationOptions.modelId, apiUrl])++ function initDefaults(params: ParamSchema[]) {+ const current = generationOptions.modelParams+ const defaults: Record<string, any> = {}+ for (const p of params) {+ if (!(p.id in current)) {+ defaults[p.id] = p.default+ }+ }+ if (Object.keys(defaults).length > 0) {+ setGenerationOptions({ modelParams: { ...current, ...defaults } })+ }+ }++ function setModelParam(id: string, value: any) {+ setGenerationOptions({+ modelParams: { ...generationOptions.modelParams, [id]: value },+ })+ }++ // ─── Load models list ──────────────────────────────────────────────────────++ const { getAllModelsStatus } = useApi()++ useEffect(() => {+ if (!apiUrl) return+ getAllModelsStatus()+ .then((statuses) => {+ const list = statuses+ .filter((s) => s.downloaded)+ .map((s) => ({ id: s.id, name: s.name ?? s.id }))+ setModels(list)+ if (list.length === 0) {+ setGenerationOptions({ modelId: '' })+ } else if (!generationOptions.modelId || !list.find((m) => m.id === generationOptions.modelId)) {+ setGenerationOptions({ modelId: list[0].id })+ }+ })+ .catch(() => {})+ // eslint-disable-next-line react-hooks/exhaustive-deps -- load once backend is ready; getAllModelsStatus is re-created each render (would loop)+ }, [apiUrl])++ return (+ <>+ <div className={`flex flex-col px-4 pb-4 gap-3 ${isDisabled ? 'opacity-50 pointer-events-none' : ''}`}>+ <div className="h-px bg-zinc-800" />+ <h2 className="text-xs font-semibold uppercase tracking-widest text-zinc-500">Options</h2>++ {/* Model */}+ <div className="flex flex-col gap-1.5">+ <FieldLabel+ label="Model"+ tooltip="The AI model used to generate the 3D mesh from your image. Only downloaded models are shown."+ />+ <ModelSelect+ models={models}+ value={generationOptions.modelId}+ onChange={(id) => setGenerationOptions({ modelId: id, modelParams: {} })}+ />+ </div>++ {/* Remesh */}+ <div className="flex flex-col gap-1.5">+ <FieldLabel+ label="Remesh"+ tooltip="Quad-Dominant regularizes the surface for cleaner downstream edits, but it is not character retopology. Triangle is faster and more compatible. None skips remeshing entirely."+ />+ <div className="flex gap-1.5">+ {REMESH_OPTIONS.map((opt) => (+ <button+ key={opt.value}+ onClick={() => setGenerationOptions({ remesh: opt.value })}+ className={`flex-1 py-1.5 text-xs rounded-lg transition-colors ${+ generationOptions.remesh === opt.value+ ? 'bg-accent text-white'+ : 'bg-zinc-800 text-zinc-400 hover:bg-zinc-700'+ }`}+ >+ {opt.label}+ </button>+ ))}+ </div>+ </div>++ {/* Dynamic model params */}+ {schema.map((param) => (+ <DynamicParam+ key={param.id}+ schema={param}+ value={generationOptions.modelParams[param.id] ?? param.default}+ onChange={(val) => setModelParam(param.id, val)}+ />+ ))}++ {/* Separator */}+ <div className="flex items-center gap-2 pt-1">+ <div className="h-px flex-1 bg-zinc-800" />+ <span className="text-xs font-semibold uppercase tracking-widest text-zinc-600">Texture</span>+ <div className="h-px flex-1 bg-zinc-800" />+ </div>++ {/* Texture */}+ <div className="flex flex-col gap-1.5">+ <div className="flex items-center w-full">+ <span className="text-sm text-zinc-300">Generate Texture</span>+ <button+ role="checkbox"+ aria-checked={generationOptions.enableTexture}+ onClick={() => {+ if (!generationOptions.enableTexture) {+ setShowTextureWarning(true)+ } else {+ setGenerationOptions({ enableTexture: false })+ }+ }}+ className={`ml-2 w-9 h-5 rounded-full transition-colors relative flex-shrink-0 ${+ generationOptions.enableTexture ? 'bg-accent' : 'bg-zinc-700'+ }`}+ >+ <span className={`absolute top-0.5 w-3.5 h-3.5 rounded-full bg-white shadow transition-all ${+ generationOptions.enableTexture ? 'left-[18px]' : 'left-0.5'+ }`} />+ </button>+ <span className="ml-auto">+ <Tooltip content="Bake UV-mapped textures onto the mesh. Requires uv_unwrapper and texture_baker to be compiled.">+ <span className="w-5 h-5 rounded-full flex items-center justify-center text-zinc-600 hover:text-accent-light transition-colors cursor-default select-none">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">+ <circle cx="12" cy="12" r="10" />+ <line x1="12" y1="16" x2="12" y2="12" />+ <line x1="12" y1="8" x2="12.01" y2="8" />+ </svg>+ </span>+ </Tooltip>+ </span>+ </div>++ <div className={`flex flex-col gap-1 transition-opacity ${generationOptions.enableTexture ? '' : 'opacity-40'}`}>+ <FieldLabel+ label="Texture Resolution"+ tooltip="Width and height of the baked texture in pixels. Higher values give more detail but take longer. Must be between 64 and 2048."+ />+ <div className="flex items-center gap-2">+ <input+ type="number"+ min={64}+ max={2048}+ step={64}+ value={textureResolutionRaw}+ disabled={!generationOptions.enableTexture}+ onChange={(e) => setTextureResolutionRaw(e.target.value)}+ onBlur={() => {+ const v = parseInt(textureResolutionRaw)+ const clamped = isNaN(v) ? 512 : Math.max(64, Math.min(2048, v))+ setTextureResolutionRaw(String(clamped))+ setGenerationOptions({ textureResolution: clamped })+ }}+ className="w-full px-3 py-1.5 text-xs rounded-lg bg-zinc-900 border border-zinc-700/60 text-zinc-200 focus:outline-none focus:border-zinc-500 disabled:cursor-not-allowed [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"+ />+ <span className="text-xs text-zinc-600 flex-shrink-0">px</span>+ </div>+ </div>+ </div>++ </div>++ {showTextureWarning && (+ <ConfirmModal+ title="Texture generation is experimental"+ description="This feature is still in development and may produce unexpected results, crash, or significantly slow down generation. Use at your own risk."+ confirmLabel="Enable anyway"+ cancelLabel="Cancel"+ onConfirm={() => {+ setGenerationOptions({ enableTexture: true })+ setShowTextureWarning(false)+ }}+ onCancel={() => setShowTextureWarning(false)}+ />+ )}+ </>+ )+}diff --git a/apps/forge-desktop/src/areas/generate/components/GenerationPanel.tsx b/apps/forge-desktop/src/areas/generate/components/GenerationPanel.tsxnew file mode 100644index 000000000..d9f4c17c4--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/components/GenerationPanel.tsx@@ -0,0 +1,116 @@+import { useEffect, useRef, useState } from 'react'+import { useGeneration } from '@shared/hooks/useGeneration'++function formatElapsed(seconds: number): string {+ const m = Math.floor(seconds / 60)+ const s = seconds % 60+ return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`+}++export default function GenerationPanel(): JSX.Element {+ const { currentJob, reset } = useGeneration()+ const [elapsed, setElapsed] = useState(0)+ const startRef = useRef<number | null>(null)+ const [exportFormat, setExportFormat] = useState('glb')+ const [exporting, setExporting] = useState(false)++ async function handleExport() {+ if (!currentJob?.outputUrl || exporting) return+ setExporting(true)+ await window.electron.model.export({ outputUrl: currentJob.outputUrl, format: exportFormat })+ setExporting(false)+ }++ const status = currentJob?.status+ const isActive = status === 'uploading' || status === 'generating'++ // Elapsed timer — starts when generation begins, resets on idle+ useEffect(() => {+ if (isActive) {+ if (!startRef.current) startRef.current = Date.now()+ const id = setInterval(() => {+ setElapsed(Math.floor((Date.now() - startRef.current!) / 1000))+ }, 1000)+ return () => clearInterval(id)+ } else {+ startRef.current = null+ setElapsed(0)+ }+ }, [isActive])++ if (!currentJob) return <></>++ const { status: jobStatus, progress, step, error } = currentJob++ const statusLabel: Record<string, string> = {+ uploading: 'Reading image…',+ generating: step ?? 'Generating 3D mesh…',+ done: 'Done!',+ error: 'Generation failed',+ }++ return (+ <div className="flex flex-col px-4 pb-4 gap-3">+ <div className="h-px bg-zinc-800" />+ <h2 className="text-xs font-semibold uppercase tracking-widest text-zinc-500">Progress</h2>++ {/* Step + timer */}+ <div className="flex items-center justify-between">+ <p className="text-sm text-zinc-300">{statusLabel[jobStatus] ?? jobStatus}</p>+ {isActive && (+ <span className="text-xs tabular-nums text-zinc-500">{formatElapsed(elapsed)}</span>+ )}+ </div>++ {/* Progress bar */}+ {isActive && (+ <div className="flex flex-col gap-1.5">+ <div className="h-1.5 bg-zinc-800 rounded-full overflow-hidden">+ <div+ className="h-full bg-accent rounded-full transition-all duration-700 ease-out"+ style={{ width: `${progress}%` }}+ />+ </div>+ <span className="text-xs text-zinc-600 tabular-nums">{progress}%</span>+ </div>+ )}++ {/* Error */}+ {jobStatus === 'error' && (+ <div className="p-3 bg-red-900/30 border border-red-800 rounded-lg">+ <p className="text-xs text-red-400 whitespace-pre-wrap break-words">{error}</p>+ </div>+ )}++ {/* Done actions */}+ {jobStatus === 'done' && (+ <div className="flex flex-col gap-2">+ <div className="flex gap-1.5">+ <select+ value={exportFormat}+ onChange={(e) => setExportFormat(e.target.value)}+ className="px-2 py-2 rounded-lg bg-zinc-800 border border-zinc-700/50 text-zinc-300 text-xs font-medium focus:outline-none focus:border-zinc-500 transition-colors cursor-pointer"+ >+ {['glb', 'stl', 'obj', 'ply'].map((f) => (+ <option key={f} value={f}>{f.toUpperCase()}</option>+ ))}+ </select>+ <button+ onClick={handleExport}+ disabled={exporting}+ className="flex-1 py-2 text-xs rounded-lg bg-zinc-800 hover:bg-zinc-700 disabled:opacity-50 disabled:cursor-not-allowed text-zinc-200 transition-colors"+ >+ {exporting ? 'Exporting…' : 'Export'}+ </button>+ </div>+ <button+ onClick={reset}+ className="w-full py-2 text-xs rounded-lg bg-zinc-800 hover:bg-zinc-700 text-zinc-200 transition-colors"+ >+ New+ </button>+ </div>+ )}+ </div>+ )+}diff --git a/apps/forge-desktop/src/areas/generate/components/ImageUpload.tsx b/apps/forge-desktop/src/areas/generate/components/ImageUpload.tsxnew file mode 100644index 000000000..f5284f7d3--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/components/ImageUpload.tsx@@ -0,0 +1,112 @@+import { useState, useCallback } from 'react'+import { useAppStore } from '@shared/stores/appStore'+import { useGeneration } from '@shared/hooks/useGeneration'++export default function ImageUpload(): JSX.Element {+ const { currentJob } = useGeneration()+ const { setSelectedImagePath, selectedImagePreviewUrl, setSelectedImagePreviewUrl, setSelectedImageData } = useAppStore()+ const [isDragging, setIsDragging] = useState(false)++ const isGenerating = currentJob?.status === 'uploading' || currentJob?.status === 'generating'++ const handleFileSelect = useCallback(async () => {+ const path = await window.electron.fs.selectImage()+ if (!path) return+ setSelectedImageData(null)+ setSelectedImagePath(path)++ // Read via IPC → blob URL (file:// blocked when served from localhost in dev)+ const base64 = await window.electron.fs.readFileBase64(path)+ const byteArray = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0))+ const blob = new Blob([byteArray], { type: 'image/png' })+ setSelectedImagePreviewUrl(URL.createObjectURL(blob))+ }, [setSelectedImagePath, setSelectedImagePreviewUrl, setSelectedImageData])++ const handleDrop = useCallback((e: React.DragEvent) => {+ e.preventDefault()+ setIsDragging(false)+ const file = e.dataTransfer.files[0]+ if (!file || !file.type.startsWith('image/')) return++ setSelectedImagePreviewUrl(URL.createObjectURL(file))++ const filePath = (file as File & { path?: string }).path+ if (filePath) {+ setSelectedImageData(null)+ setSelectedImagePath(filePath)+ } else {+ // file.path unavailable (some Electron configs) — read directly via FileReader+ const reader = new FileReader()+ reader.onload = (ev) => {+ const dataUrl = ev.target?.result as string+ const base64 = dataUrl.split(',')[1]+ setSelectedImageData(base64)+ setSelectedImagePath('__blob__')+ }+ reader.readAsDataURL(file)+ }+ }, [setSelectedImagePath, setSelectedImagePreviewUrl, setSelectedImageData])++ return (+ <div className="flex flex-col p-4 gap-3">+ <h2 className="text-xs font-semibold uppercase tracking-widest text-zinc-500">Input Image</h2>++ {/* Drop zone */}+ <div+ onClick={isGenerating ? undefined : handleFileSelect}+ onDrop={handleDrop}+ onDragOver={(e) => { e.preventDefault(); setIsDragging(true) }}+ onDragLeave={() => setIsDragging(false)}+ className={`+ relative aspect-square rounded-xl border-2 border-dashed+ flex items-center justify-center overflow-hidden+ transition-colors cursor-pointer+ ${isDragging ? 'border-accent bg-accent/10' : 'border-zinc-700 hover:border-zinc-500'}+ ${isGenerating ? 'cursor-not-allowed opacity-60' : ''}+ `}+ >+ {selectedImagePreviewUrl ? (+ <>+ <img+ src={selectedImagePreviewUrl}+ alt="Input"+ className="w-full h-full object-cover"+ />+ {!isGenerating && (+ <button+ onClick={(e) => {+ e.stopPropagation()+ setSelectedImagePath(null)+ setSelectedImagePreviewUrl(null)+ setSelectedImageData(null)+ }}+ className="absolute top-2 right-2 w-6 h-6 rounded-full bg-black/70 hover:bg-black/90 text-zinc-300 hover:text-white flex items-center justify-center transition-colors"+ >+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <line x1="18" y1="6" x2="6" y2="18" />+ <line x1="6" y1="6" x2="18" y2="18" />+ </svg>+ </button>+ )}+ </>+ ) : (+ <div className="flex flex-col items-center gap-2 text-zinc-600">+ <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1">+ <rect x="3" y="3" width="18" height="18" rx="2" />+ <circle cx="8.5" cy="8.5" r="1.5" />+ <polyline points="21 15 16 10 5 21" />+ </svg>+ <p className="text-xs text-center">Drop image here<br />or click to browse</p>+ </div>+ )}++ {/* Generating overlay */}+ {isGenerating && (+ <div className="absolute inset-0 bg-surface-500/80 flex items-center justify-center">+ <div className="w-8 h-8 border-2 border-accent border-t-transparent rounded-full animate-spin" />+ </div>+ )}+ </div>+ </div>+ )+}diff --git a/apps/forge-desktop/src/areas/generate/components/SplatViewer.tsx b/apps/forge-desktop/src/areas/generate/components/SplatViewer.tsxnew file mode 100644index 000000000..5e4027668--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/components/SplatViewer.tsx@@ -0,0 +1,306 @@+import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'+import { Canvas, useFrame } from '@react-three/fiber'+import * as THREE from 'three'+import * as GaussianSplats3D from '@mkkellogg/gaussian-splats-3d'++export interface SplatViewerHandle {+ screenshot: () => string | null+}++// ---------------------------------------------------------------------------+// X/Y/Z orientation gizmo — a tiny overlay Canvas synced to the splat camera.+// mkkellogg runs outside R3F, so the mesh viewer's drei GizmoHelper can't be+// reused; this mirrors its look (coloured axis bubbles) driven by the live+// camera quaternion.+// ---------------------------------------------------------------------------++function makeAxisLabelTexture(letter: string, bg: string): THREE.CanvasTexture {+ const canvas = document.createElement('canvas')+ canvas.width = canvas.height = 64+ const ctx = canvas.getContext('2d')!+ ctx.beginPath()+ ctx.arc(32, 32, 16, 0, 2 * Math.PI)+ ctx.fillStyle = bg+ ctx.fill()+ ctx.font = '18px Arial, sans-serif'+ ctx.textAlign = 'center'+ ctx.fillStyle = '#ffffff'+ ctx.fillText(letter, 32, 41)+ return new THREE.CanvasTexture(canvas)+}++const GIZMO_AXES: { letter: string; color: string; pos: [number, number, number]; rot: [number, number, number] }[] = [+ { letter: 'X', color: '#f87171', pos: [1, 0, 0], rot: [0, 0, 0] },+ { letter: 'Y', color: '#4ade80', pos: [0, 1, 0], rot: [0, 0, Math.PI / 2] },+ { letter: 'Z', color: '#60a5fa', pos: [0, 0, 1], rot: [0, -Math.PI / 2, 0] },+]++type Axis = 'x' | 'y' | 'z'++function AxisBubble({+ axis,+ texture,+ onAxisClick,+}: {+ axis: (typeof GIZMO_AXES)[number]+ texture: THREE.CanvasTexture+ onAxisClick: (axis: Axis) => void+}): JSX.Element {+ const [hovered, setHovered] = useState(false)+ return (+ <sprite+ position={axis.pos}+ scale={hovered ? 1.2 : 1}+ onPointerDown={(e) => { e.stopPropagation(); onAxisClick(axis.letter.toLowerCase() as Axis) }}+ onPointerOver={(e) => { e.stopPropagation(); setHovered(true); document.body.style.cursor = 'pointer' }}+ onPointerOut={() => { setHovered(false); document.body.style.cursor = 'default' }}+ >+ <spriteMaterial map={texture} alphaTest={0.3} toneMapped={false} />+ </sprite>+ )+}++function GizmoContent({+ getQuaternion,+ onAxisClick,+}: {+ getQuaternion: () => THREE.Quaternion | undefined+ onAxisClick: (axis: Axis) => void+}): JSX.Element {+ const groupRef = useRef<THREE.Group>(null)+ const textures = useMemo(() => GIZMO_AXES.map((a) => makeAxisLabelTexture(a.letter, a.color)), [])+ useEffect(() => () => { textures.forEach((t) => t.dispose()) }, [textures])++ useFrame(() => {+ const q = getQuaternion()+ if (q && groupRef.current) groupRef.current.quaternion.copy(q).invert()+ })++ // Same proportions as the mesh viewer's drei GizmoHelper: bubbles group at+ // scale 40 under an orthographic camera (1 world unit ≈ 1 px).+ return (+ <group ref={groupRef} scale={40}>+ {GIZMO_AXES.map((axis) => (+ <group key={`line-${axis.letter}`} rotation={axis.rot}>+ <mesh position={[0.4, 0, 0]}>+ <boxGeometry args={[0.8, 0.05, 0.05]} />+ <meshBasicMaterial color={axis.color} toneMapped={false} />+ </mesh>+ </group>+ ))}+ {GIZMO_AXES.map((axis, i) => (+ <AxisBubble key={axis.letter} axis={axis} texture={textures[i]} onAxisClick={onAxisClick} />+ ))}+ </group>+ )+}++function SplatGizmo({+ getQuaternion,+ onAxisClick,+}: {+ getQuaternion: () => THREE.Quaternion | undefined+ onAxisClick: (axis: Axis) => void+}): JSX.Element {+ // Orthographic camera mirrors drei's GizmoHelper so the splat gizmo matches+ // the mesh (GLB) gizmo's size and look exactly.+ return (+ <div className="absolute top-3 right-3 w-32 h-32">+ <Canvas orthographic camera={{ position: [0, 0, 200], zoom: 1 }} gl={{ alpha: true }}>+ <GizmoContent getQuaternion={getQuaternion} onAxisClick={onAxisClick} />+ </Canvas>+ </div>+ )+}++// ---------------------------------------------------------------------------+// Frame the loaded splat like the mesh viewer: the mesh viewer recenters the+// model and uses a fixed camera, but mkkellogg sorts splats by their built+// positions, so translating the splatMesh would corrupt depth sorting. Instead+// we measure the splat's bounds (sampled splat centres) and fit the *camera*+// to them, then drop the grid under the model's feet.+// ---------------------------------------------------------------------------++function frameSplatToView(viewer: any, grid: THREE.GridHelper): void {+ const splatMesh = viewer?.splatMesh+ const camera = viewer?.camera+ if (!splatMesh || !camera) return++ const count: number = splatMesh.getSplatCount?.() ?? 0+ if (count === 0) return++ const box = new THREE.Box3()+ const c = new THREE.Vector3()+ const step = Math.max(1, Math.floor(count / 20000)) // sample for large clouds+ for (let i = 0; i < count; i += step) {+ splatMesh.getSplatCenter(i, c, true) // true → built (rendered) coordinates+ box.expandByPoint(c)+ }+ if (box.isEmpty()) return++ const center = box.getCenter(new THREE.Vector3())+ const size = box.getSize(new THREE.Vector3())+ const maxDim = Math.max(size.x, size.y, size.z)++ // Pull back enough to fit the largest dimension at fov 45, with margin.+ const fov = (camera.fov ?? 45) * (Math.PI / 180)+ const dist = (maxDim / 2 / Math.tan(fov / 2)) * 1.6++ // Same 3/4 front view as the mesh viewer; −Z side shows the face after the+ // 180° Z flip applied in addSplatScene.+ const dir = new THREE.Vector3(0, 0.35, -1).normalize()+ camera.position.copy(center).add(dir.multiplyScalar(dist))+ camera.lookAt(center)++ const controls = viewer.controls+ if (controls?.target) {+ controls.target.copy(center)+ controls.update?.()+ }++ grid.position.y = box.min.y // feet on the grid, like the mesh viewer+}++// ---------------------------------------------------------------------------+// SplatViewer — self-contained Gaussian-Splatting viewer (mkkellogg, outside+// R3F). It owns its own canvas / scene / camera / controls, so nothing from the+// mesh viewer's pipeline can interfere. Fed a normalised binary .splat.+// ---------------------------------------------------------------------------++const SplatViewer = forwardRef<SplatViewerHandle, { url: string; autoRotate: boolean }>(+ function SplatViewer({ url, autoRotate }, ref): JSX.Element {+ const containerRef = useRef<HTMLDivElement | null>(null)+ const viewerRef = useRef<any>(null)+ const [status, setStatus] = useState<'loading' | 'ready' | 'error'>('loading')+ const [message, setMessage] = useState<string>('')++ // Screenshot: render() is not gated by mkkellogg's shouldRender() optimisation,+ // so a synchronous render + toDataURL in the same tick captures a full frame+ // even though the renderer has no preserveDrawingBuffer.+ useImperativeHandle(ref, () => ({+ screenshot: () => {+ const viewer = viewerRef.current+ if (!viewer?.renderer) return null+ try { viewer.render() } catch { return null }+ return viewer.renderer.domElement.toDataURL('image/png')+ },+ }), [])++ // Auto-rotate via mkkellogg's built-in OrbitControls.+ useEffect(() => {+ const controls = viewerRef.current?.controls+ if (!controls) return+ controls.autoRotate = autoRotate+ controls.autoRotateSpeed = 1.5+ }, [autoRotate, status])++ useEffect(() => {+ const container = containerRef.current+ if (!container) return++ setStatus('loading')+ setMessage('')++ let disposed = false+ let viewer: any = null++ try {+ viewer = new GaussianSplats3D.Viewer({+ rootElement: container,+ selfDrivenMode: true,+ useBuiltInControls: true,+ sharedMemoryForWorkers: false, // no cross-origin isolation in Electron/Vite+ gpuAcceleratedSort: false, // CPU sort — most robust across GPUs/Electron+ // Frame like the mesh viewer: look at the model's centre (feet at y=0,+ // head ≈ 2), from the front. This splat faces −Z after the 180° Z flip,+ // so the camera sits on the −Z side to show the face, not the back.+ initialCameraPosition: [0, 1.2, -3.8],+ initialCameraLookAt: [0, 0.8, 0],+ cameraUp: [0, 1, 0],+ })+ viewerRef.current = viewer++ // Match the mesh viewer's framing: mkkellogg defaults to fov 65, the mesh+ // Canvas uses 45 — the wider fov made the splat look smaller / distorted.+ if (viewer.camera) {+ viewer.camera.fov = 45+ viewer.camera.updateProjectionMatrix()+ }++ // Floor grid, matching the mesh viewer.+ const grid = new THREE.GridHelper(10, 20, 0x3f3f46, 0x27272a)+ viewer.threeScene.add(grid)++ viewer+ .addSplatScene(url, {+ format: GaussianSplats3D.SceneFormat.Splat,+ showLoadingUI: false,+ progressiveLoad: false,+ rotation: [0, 0, 1, 0], // 180° about Z — 3DGS is Y-down; stands it upright while keeping the front toward the camera (X-mirror is invisible on a symmetric model)+ })+ .then(() => {+ if (disposed) return+ viewer.start()+ frameSplatToView(viewer, grid)+ setStatus('ready')+ })+ .catch((err: unknown) => {+ if (disposed) return+ console.error('[SplatViewer] load failed:', err)+ setStatus('error')+ setMessage(String((err as Error)?.message ?? err))+ })+ } catch (err) {+ console.error('[SplatViewer] init failed:', err)+ setStatus('error')+ setMessage(String((err as Error)?.message ?? err))+ }++ return () => {+ disposed = true+ viewerRef.current = null+ try {+ viewer?.stop()+ viewer?.dispose()+ } catch { /* already torn down */ }+ }+ }, [url])++ const getCameraQuaternion = () => viewerRef.current?.camera?.quaternion as THREE.Quaternion | undefined++ // Snap the camera to look down an axis, like the mesh viewer's gizmo.+ const snapToAxis = (axis: Axis) => {+ const viewer = viewerRef.current+ const camera = viewer?.camera+ if (!camera) return+ const controls = viewer.controls+ const target: THREE.Vector3 = controls?.target ?? new THREE.Vector3(0, 0.8, 0)+ const dist = camera.position.distanceTo(target) || 4+ const dir = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] }[axis]+ camera.position.set(target.x + dir[0] * dist, target.y + dir[1] * dist, target.z + dir[2] * dist)+ camera.up.set(...(axis === 'y' ? [0, 0, -1] : [0, 1, 0]) as [number, number, number])+ camera.lookAt(target)+ controls?.update?.()+ }++ return (+ <div className="absolute inset-0">+ <div ref={containerRef} className="absolute inset-0" />+ {status === 'ready' && <SplatGizmo getQuaternion={getCameraQuaternion} onAxisClick={snapToAxis} />}+ {status !== 'ready' && (+ <div className="absolute inset-0 flex flex-col items-center justify-center text-zinc-400 pointer-events-none gap-2">+ {status === 'loading' ? (+ <p className="text-sm">Loading splat…</p>+ ) : (+ <>+ <p className="text-sm text-red-400">Splat failed to load</p>+ {message && <p className="text-xs text-zinc-500 max-w-md text-center px-4 break-words">{message}</p>}+ </>+ )}+ </div>+ )}+ </div>+ )+})++export default SplatViewerdiff --git a/apps/forge-desktop/src/areas/generate/components/Viewer3D.tsx b/apps/forge-desktop/src/areas/generate/components/Viewer3D.tsxnew file mode 100644index 000000000..a2621cc64--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/components/Viewer3D.tsx@@ -0,0 +1,1221 @@+import { Component, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react'+import type { ReactNode, ErrorInfo, MutableRefObject } from 'react'+import { Canvas, useFrame, useLoader, useThree } from '@react-three/fiber'+import type { ThreeEvent } from '@react-three/fiber'+import { Environment, GizmoHelper, Lightformer, OrbitControls, useGizmoContext, useGLTF } from '@react-three/drei'+import { EffectComposer, Outline, Select, Selection } from '@react-three/postprocessing'+import * as THREE from 'three'+import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js'+import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast } from 'three-mesh-bvh'++// Patch THREE pour utiliser BVH sur tous les meshes — réduit le raycast O(N) → O(log N)+THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree as any+THREE.BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree as any+THREE.Mesh.prototype.raycast = acceleratedRaycast+import SplatViewer, { type SplatViewerHandle } from './SplatViewer'+import { useGeneration } from '@shared/hooks/useGeneration'+import { useAppStore } from '@shared/stores/appStore'+import { ViewerToolbar, type ViewMode } from './ViewerToolbar'+import type { LightSettings, PointLight } from '@shared/stores/appStore'+import { DEFAULT_LIGHT_SETTINGS } from '@shared/stores/appStore'++export type GizmoMode = 'translate' | 'rotate' | 'scale'++const SELECTION_OUTLINE_VISIBLE_COLOR = 0x8b5cf6+const SELECTION_OUTLINE_HIDDEN_COLOR = 0x5b21b6+const SELECTION_OUTLINE_EDGE_STRENGTH = 2.5+const SELECTION_OUTLINE_BLUR = false+const SELECTION_OUTLINE_MULTISAMPLING = 0+const SELECTION_OUTLINE_RESOLUTION_SCALE = 0.5++// ---------------------------------------------------------------------------+// Procedural textures+// ---------------------------------------------------------------------------++function createMatcapTexture(): THREE.CanvasTexture {+ const size = 128+ const canvas = document.createElement('canvas')+ canvas.width = canvas.height = size+ const ctx = canvas.getContext('2d')!+ const grad = ctx.createRadialGradient(size * 0.35, size * 0.3, 0, size / 2, size / 2, size / 2)+ grad.addColorStop(0, '#ffffff')+ grad.addColorStop(0.45, '#aaaaaa')+ grad.addColorStop(1, '#222222')+ ctx.fillStyle = grad+ ctx.fillRect(0, 0, size, size)+ return new THREE.CanvasTexture(canvas)+}++function createCheckerTexture(): THREE.CanvasTexture {+ const size = 256+ const tileCount = 8+ const tileSize = size / tileCount+ const canvas = document.createElement('canvas')+ canvas.width = canvas.height = size+ const ctx = canvas.getContext('2d')!+ for (let row = 0; row < tileCount; row++) {+ for (let col = 0; col < tileCount; col++) {+ ctx.fillStyle = (row + col) % 2 === 0 ? '#e0e0e0' : '#888888'+ ctx.fillRect(col * tileSize, row * tileSize, tileSize, tileSize)+ }+ }+ const tex = new THREE.CanvasTexture(canvas)+ tex.wrapS = tex.wrapT = THREE.RepeatWrapping+ return tex+}++const SELECTION_OUTLINE_COLOR = '#8b5cf6'++function makeLightBulbTexture(color: string, isSelected: boolean): THREE.CanvasTexture {+ const size = 64+ const canvas = document.createElement('canvas')+ canvas.width = canvas.height = size+ const ctx = canvas.getContext('2d')!++ const cx = size / 2+ const cy = size / 2++ // Draws the bulb glyph (rays + circle + base). `pad` grows every part by a+ // few pixels — used to lay down an oversized violet silhouette behind the+ // normal-sized icon, so the outline hugs the actual glyph shape instead of+ // being a plain circle around it.+ const drawGlyph = (fillColor: string, pad: number) => {+ ctx.strokeStyle = fillColor+ ctx.lineWidth = 2 + pad * 2+ ctx.lineCap = 'round'+ for (let i = 0; i < 6; i++) {+ const a = (i / 6) * Math.PI * 2 - Math.PI / 2+ const r1 = 20 - pad+ const r2 = 27 + pad+ ctx.beginPath()+ ctx.moveTo(cx + Math.cos(a) * r1, cy + Math.sin(a) * r1)+ ctx.lineTo(cx + Math.cos(a) * r2, cy + Math.sin(a) * r2)+ ctx.stroke()+ }++ ctx.beginPath()+ ctx.arc(cx, cy - 1, 12 + pad, 0, Math.PI * 2)+ ctx.fillStyle = fillColor+ ctx.fill()+ if (pad === 0) {+ ctx.strokeStyle = '#ffffff'+ ctx.lineWidth = 1.5+ ctx.stroke()+ }++ ctx.fillStyle = fillColor+ ctx.fillRect(cx - 4 - pad, cy + 11 - pad, 8 + pad * 2, 8 + pad * 2)+ if (pad === 0) {+ ctx.strokeStyle = '#ffffff'+ ctx.lineWidth = 1+ ctx.strokeRect(cx - 4, cy + 11, 8, 8)+ }+ }++ if (isSelected) drawGlyph(SELECTION_OUTLINE_COLOR, 2.5)+ drawGlyph(color, 0)++ return new THREE.CanvasTexture(canvas)+}++// ---------------------------------------------------------------------------+// CanvasCapture — exposes gl.domElement ref outside Canvas+// ---------------------------------------------------------------------------++function CanvasCapture({+ domRef,+}: {+ domRef: React.MutableRefObject<HTMLCanvasElement | null>+}): null {+ const { gl } = useThree()+ useEffect(() => {+ domRef.current = gl.domElement+ // eslint-disable-next-line react-hooks/exhaustive-deps -- domRef is a stable ref+ }, [gl])+ return null+}++// ---------------------------------------------------------------------------+// ModelErrorBoundary — catches useGLTF load failures (e.g. 404)+// ---------------------------------------------------------------------------++interface ErrorBoundaryProps {+ children: ReactNode+ fallback: ReactNode+ resetKey?: string | null+}++interface ErrorBoundaryState {+ hasError: boolean+}++class ModelErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {+ state: ErrorBoundaryState = { hasError: false }++ static getDerivedStateFromError(): ErrorBoundaryState {+ return { hasError: true }+ }++ componentDidCatch(error: Error, info: ErrorInfo): void {+ console.warn('[Viewer3D] Failed to load model:', error.message, info.componentStack)+ }++ componentDidUpdate(prevProps: ErrorBoundaryProps): void {+ if (prevProps.resetKey !== this.props.resetKey && this.state.hasError) {+ this.setState({ hasError: false })+ }+ }++ render(): ReactNode {+ return this.state.hasError ? this.props.fallback : this.props.children+ }+}++function ModelLoadError(): JSX.Element {+ return (+ <div className="absolute inset-0 flex flex-col items-center justify-center text-zinc-600 pointer-events-none">+ <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">+ <circle cx="12" cy="12" r="10" />+ <line x1="15" y1="9" x2="9" y2="15" />+ <line x1="9" y1="9" x2="15" y2="15" />+ </svg>+ <p className="mt-3 text-sm">Model file not found</p>+ </div>+ )+}++// ---------------------------------------------------------------------------+// MeshModel+// ---------------------------------------------------------------------------++interface MeshModelProps {+ url: string+ jobId: string+ viewMode: ViewMode+ selected: boolean+ onStats: (stats: { vertices: number; triangles: number }) => void+ onSelect: () => void+ onObject: (obj: THREE.Object3D | null) => void+}++function MeshModel({ url, jobId, viewMode, selected, onStats, onSelect, onObject }: MeshModelProps): JSX.Element {+ const extension = url.split('?')[0]?.split('.').pop()?.toLowerCase()+ const common = { url, jobId, viewMode, selected, onStats, onSelect, onObject }+ return extension === 'obj' ? <ObjMeshModel {...common} /> : <GltfMeshModel {...common} />+}++function GltfMeshModel(props: MeshModelProps): JSX.Element {+ const { scene } = useGLTF(props.url)+ return <SceneMeshModel {...props} scene={scene} loaderType="gltf" />+}++function ObjMeshModel(props: MeshModelProps): JSX.Element {+ const scene = useLoader(OBJLoader, props.url)+ return <SceneMeshModel {...props} scene={scene} loaderType="obj" />+}++function SceneMeshModel({+ url,+ viewMode,+ selected,+ onStats,+ onSelect,+ onObject,+ scene,+ loaderType,+}: MeshModelProps & {+ scene: THREE.Group | THREE.Scene+ loaderType: 'gltf' | 'obj'+}): JSX.Element {+ const captured = useRef(false)+ const edgeHelpers = useRef<THREE.LineSegments[]>([])++ // Expose the scene object so Viewer3D can attach the transform gizmo to it.+ useEffect(() => {+ onObject(scene)+ return () => onObject(null)+ }, [scene, onObject])++ // Free GPU resources and loader cache when this model is replaced or unmounted+ useEffect(() => {+ return () => {+ if (loaderType === 'obj') {+ useLoader.clear(OBJLoader, url)+ } else {+ useGLTF.clear(url)+ }+ scene.traverse((child) => {+ if (child instanceof THREE.Mesh) {+ child.geometry.dispose()+ const materials = Array.isArray(child.material) ? child.material : [child.material]+ materials.forEach((m: THREE.Material) => m.dispose())+ }+ })+ }+ }, [loaderType, scene, url])++ // Compute BVH on all geometries for fast raycasting (O(log N) vs O(N)).+ // Also force DoubleSide on every material so faces with inverted normals+ // (a known artifact of the flexible-dual-grid mesh decoder) are still visible.+ useEffect(() => {+ scene.traverse((child) => {+ if (child instanceof THREE.Mesh) {+ (child.geometry as any).computeBoundsTree()+ const mats = Array.isArray(child.material) ? child.material : [child.material]+ mats.forEach((m: THREE.Material) => { m.side = THREE.DoubleSide })+ }+ })+ return () => {+ scene.traverse((child) => {+ if (child instanceof THREE.Mesh) {+ (child.geometry as any).disposeBoundsTree?.()+ }+ })+ }+ }, [scene])++ // Centre the mesh on the grid. Runs only on first load / model change — never+ // on plain re-renders, so a live gizmo transform is not silently overwritten.+ useEffect(() => {+ // Clear any cached transform before measuring (useGLTF may reuse a scene+ // that still carries an earlier gizmo pose).+ scene.position.set(0, 0, 0)+ scene.rotation.set(0, 0, 0)+ scene.scale.set(1, 1, 1)+ const box = new THREE.Box3().setFromObject(scene)+ const center = new THREE.Vector3()+ box.getCenter(center)+ scene.position.set(-center.x, -box.min.y, -center.z)++ // Compute stats+ let vertices = 0+ let triangles = 0+ scene.traverse((child) => {+ if (child instanceof THREE.Mesh) {+ vertices += child.geometry.attributes.position?.count ?? 0+ triangles += child.geometry.index+ ? child.geometry.index.count / 3+ : (child.geometry.attributes.position?.count ?? 0) / 3+ }+ })+ const roundedTriangles = Math.round(triangles)+ onStats({ vertices: Math.round(vertices), triangles: roundedTriangles })+ // eslint-disable-next-line react-hooks/exhaustive-deps -- recompute on scene change only; onStats is a stable callback+ }, [scene])++ // Thumbnail capture (kept for future use)+ useEffect(() => {+ captured.current = false+ }, [url])++ // Material swapping based on viewMode+ useEffect(() => {+ // Remove any edge helpers from previous wireframe pass+ edgeHelpers.current.forEach((lines) => lines.parent?.remove(lines))+ edgeHelpers.current = []++ scene.traverse((child) => {+ if (!(child instanceof THREE.Mesh)) return++ // Save original material on first visit+ if (!child.userData.originalMaterial) {+ child.userData.originalMaterial = child.material+ }++ let next: THREE.Material+ switch (viewMode) {+ case 'wireframe': {+ next = new THREE.MeshBasicMaterial({ color: 0x4ade80, wireframe: true })+ break+ }+ case 'normals':+ // Ensure vertex normals exist — AI-generated meshes often skip this+ child.geometry.computeVertexNormals()+ next = new THREE.MeshNormalMaterial({ side: THREE.DoubleSide })+ break+ case 'matcap':+ next = new THREE.MeshMatcapMaterial({ matcap: createMatcapTexture() })+ break+ case 'uv':+ next = new THREE.MeshBasicMaterial({ map: createCheckerTexture() })+ break+ default:+ next = child.userData.originalMaterial as THREE.Material+ }++ child.material = next+ })+ }, [scene, viewMode])++ return (+ <Select enabled={selected}>+ <primitive+ object={scene}+ onClick={(e: { stopPropagation: () => void }) => { e.stopPropagation(); onSelect() }}+ />+ </Select>+ )++}++// ---------------------------------------------------------------------------+// Orientation gizmo — coloured bubbles only (X/Y/Z)+// ---------------------------------------------------------------------------++function makeAxisLabelTexture(letter: string, bg: string): THREE.CanvasTexture {+ const canvas = document.createElement('canvas')+ canvas.width = canvas.height = 64+ const ctx = canvas.getContext('2d')!+ ctx.beginPath()+ ctx.arc(32, 32, 16, 0, 2 * Math.PI)+ ctx.closePath()+ ctx.fillStyle = bg+ ctx.fill()+ ctx.font = '18px Arial, sans-serif'+ ctx.textAlign = 'center'+ ctx.fillStyle = '#ffffff'+ ctx.fillText(letter, 32, 41)+ return new THREE.CanvasTexture(canvas)+}++const GIZMO_AXES: {+ letter: string+ color: string+ pos: [number, number, number]+ lineRotation: [number, number, number]+}[] = [+ { letter: 'X', color: '#f87171', pos: [1, 0, 0], lineRotation: [0, 0, 0] },+ { letter: 'Y', color: '#4ade80', pos: [0, 1, 0], lineRotation: [0, 0, Math.PI / 2] },+ { letter: 'Z', color: '#60a5fa', pos: [0, 0, 1], lineRotation: [0, -Math.PI / 2, 0] },+]++function AxisLine({ color, rotation }: { color: string; rotation: [number, number, number] }) {+ return (+ <group rotation={rotation}>+ <mesh position={[0.4, 0, 0]}>+ <boxGeometry args={[0.8, 0.05, 0.05]} />+ <meshBasicMaterial color={color} toneMapped={false} />+ </mesh>+ </group>+ )+}++function AxisBubble({ letter, color, pos }: { letter: string; color: string; pos: [number, number, number] }) {+ const { tweenCamera } = useGizmoContext()+ const texture = useMemo(() => makeAxisLabelTexture(letter, color), [letter, color])+ const [hovered, setHovered] = useState(false)++ return (+ <sprite+ position={pos}+ scale={hovered ? 1.2 : 1}+ onPointerDown={(e) => { tweenCamera(e.object.position); e.stopPropagation() }}+ onPointerOver={(e) => { e.stopPropagation(); setHovered(true) }}+ onPointerOut={() => setHovered(false)}+ >+ <spriteMaterial map={texture} alphaTest={0.3} toneMapped={false} />+ </sprite>+ )+}++function GizmoBubbles() {+ return (+ <group scale={40}>+ {GIZMO_AXES.map((axis) => (+ <AxisLine key={`line-${axis.letter}`} color={axis.color} rotation={axis.lineRotation} />+ ))}+ {GIZMO_AXES.map((axis) => (+ <AxisBubble key={axis.letter} {...axis} />+ ))}+ </group>+ )+}++// ---------------------------------------------------------------------------+// Transform gizmos — custom move / rotate / scale handles (shared style)+// ---------------------------------------------------------------------------++type GizmoAxis = 'x' | 'y' | 'z'+type TranslateHandleId = GizmoAxis | 'xy' | 'yz' | 'xz'+type ScaleHandleId = GizmoAxis | 'xyz'++const AXIS_COLORS: Record<GizmoAxis, string> = {+ x: '#f87171',+ y: '#4ade80',+ z: '#60a5fa',+}++const AXIS_DIR: Record<GizmoAxis, [number, number, number]> = {+ x: [1, 0, 0],+ y: [0, 1, 0],+ z: [0, 0, 1],+}++// Orient a +Y cylinder/cone/box onto each axis.+const AXIS_ROTATION: Record<GizmoAxis, [number, number, number]> = {+ x: [0, 0, -Math.PI / 2],+ y: [0, 0, 0],+ z: [Math.PI / 2, 0, 0],+}++// Orient a default-XY torus so its ring spins around each axis.+const RING_ROTATION: Record<GizmoAxis, [number, number, number]> = {+ x: [0, Math.PI / 2, 0],+ y: [Math.PI / 2, 0, 0],+ z: [0, 0, 0],+}++// Two-axis plane handles, coloured by their locked (normal) axis.+const PLANE_HANDLES: {+ id: 'xy' | 'yz' | 'xz'+ normal: [number, number, number]+ color: string+ position: [number, number, number]+ rotation: [number, number, number]+}[] = [+ { id: 'xy', normal: [0, 0, 1], color: AXIS_COLORS.z, position: [0.26, 0.26, 0], rotation: [0, 0, 0] },+ { id: 'yz', normal: [1, 0, 0], color: AXIS_COLORS.x, position: [0, 0.26, 0.26], rotation: [0, -Math.PI / 2, 0] },+ { id: 'xz', normal: [0, 1, 0], color: AXIS_COLORS.y, position: [0.26, 0, 0.26], rotation: [Math.PI / 2, 0, 0] },+]++const GIZMO_SCREEN_SIZE = 0.12++function lightenColor(hex: string, amount = 0.5): string {+ return '#' + new THREE.Color(hex).lerp(new THREE.Color('#ffffff'), amount).getHexString()+}++function intersectPlane(ray: THREE.Ray, origin: THREE.Vector3, normal: THREE.Vector3): THREE.Vector3 | null {+ const plane = new THREE.Plane().setFromNormalAndCoplanarPoint(normal, origin)+ const hit = new THREE.Vector3()+ return ray.intersectPlane(plane, hit) ? hit : null+}++// Shared plumbing: follow the object, keep a constant on-screen size, and run+// the pointer-drag lifecycle (window listeners + OrbitControls locking).+function useGizmoBase(object: THREE.Object3D) {+ const camera = useThree((s) => s.camera)+ const gl = useThree((s) => s.gl)+ const raycaster = useThree((s) => s.raycaster)+ const controls = useThree((s) => s.controls) as { enabled: boolean } | null++ const groupRef = useRef<THREE.Group>(null)+ const ndc = useRef(new THREE.Vector2())+ const moveRef = useRef<((ev: PointerEvent) => void) | null>(null)+ const endRef = useRef<(() => void) | null>(null)++ useFrame(() => {+ const g = groupRef.current+ if (!g) return+ object.getWorldPosition(g.position)+ g.scale.setScalar(Math.max(camera.position.distanceTo(g.position) * GIZMO_SCREEN_SIZE, 0.001))+ })++ const pointerRay = useCallback((ev: PointerEvent): THREE.Ray => {+ const rect = gl.domElement.getBoundingClientRect()+ ndc.current.set(+ ((ev.clientX - rect.left) / rect.width) * 2 - 1,+ -((ev.clientY - rect.top) / rect.height) * 2 + 1,+ )+ raycaster.setFromCamera(ndc.current, camera)+ return raycaster.ray+ }, [camera, gl, raycaster])++ const stop = useCallback(() => {+ if (!moveRef.current) return+ window.removeEventListener('pointermove', moveRef.current)+ window.removeEventListener('pointerup', stop)+ moveRef.current = null+ endRef.current?.()+ endRef.current = null+ if (controls) controls.enabled = true+ gl.domElement.style.cursor = ''+ }, [controls, gl])++ const start = useCallback((onMove: (ev: PointerEvent) => void, onEnd?: () => void) => {+ moveRef.current = onMove+ endRef.current = onEnd ?? null+ if (controls) controls.enabled = false+ gl.domElement.style.cursor = 'grabbing'+ window.addEventListener('pointermove', onMove)+ window.addEventListener('pointerup', stop)+ }, [controls, gl, stop])++ useEffect(() => stop, [stop]) // release the drag if unmounted mid-interaction++ return { camera, groupRef, pointerRay, start }+}++function hoverHandlers<T extends string>(+ id: T,+ setHovered: (value: T | null) => void,+ onDown: (e: ThreeEvent<PointerEvent>) => void,+) {+ return {+ onPointerOver: (e: ThreeEvent<PointerEvent>) => { e.stopPropagation(); setHovered(id) },+ onPointerOut: () => setHovered(null),+ onPointerDown: onDown,+ }+}++function GizmoArrow({ color, active }: { color: string; active: boolean }): JSX.Element {+ const tint = active ? lightenColor(color) : color+ return (+ <group>+ {/* Invisible, fat hit target spanning the whole arm */}+ <mesh position={[0, 0.55, 0]}>+ <cylinderGeometry args={[0.09, 0.09, 1.1, 8]} />+ <meshBasicMaterial transparent opacity={0} depthWrite={false} />+ </mesh>+ {/* Shaft */}+ <mesh position={[0, 0.48, 0]} renderOrder={999}>+ <cylinderGeometry args={[0.014, 0.014, 0.66, 16]} />+ <meshBasicMaterial color={tint} toneMapped={false} transparent depthTest={false} depthWrite={false} />+ </mesh>+ {/* Arrowhead */}+ <mesh position={[0, 0.9, 0]} renderOrder={999}>+ <coneGeometry args={[0.055, 0.2, 20]} />+ <meshBasicMaterial color={tint} toneMapped={false} transparent depthTest={false} depthWrite={false} />+ </mesh>+ </group>+ )+}++function GizmoScaleArm({ color, active }: { color: string; active: boolean }): JSX.Element {+ const tint = active ? lightenColor(color) : color+ return (+ <group>+ {/* Invisible, fat hit target — starts above the centre cube so a+ centre click hits the uniform-scale handle, not an axis */}+ <mesh position={[0, 0.6, 0]}>+ <cylinderGeometry args={[0.09, 0.09, 0.8, 8]} />+ <meshBasicMaterial transparent opacity={0} depthWrite={false} />+ </mesh>+ {/* Shaft */}+ <mesh position={[0, 0.42, 0]} renderOrder={999}>+ <cylinderGeometry args={[0.014, 0.014, 0.7, 16]} />+ <meshBasicMaterial color={tint} toneMapped={false} transparent depthTest={false} depthWrite={false} />+ </mesh>+ {/* Cube head */}+ <mesh position={[0, 0.84, 0]} renderOrder={999}>+ <boxGeometry args={[0.11, 0.11, 0.11]} />+ <meshBasicMaterial color={tint} toneMapped={false} transparent depthTest={false} depthWrite={false} />+ </mesh>+ </group>+ )+}++function GizmoRing({ color, active }: { color: string; active: boolean }): JSX.Element {+ const tint = active ? lightenColor(color) : color+ return (+ <group>+ {/* Invisible, fat hit target */}+ <mesh>+ <torusGeometry args={[0.9, 0.06, 8, 48]} />+ <meshBasicMaterial transparent opacity={0} depthWrite={false} />+ </mesh>+ <mesh renderOrder={999}>+ <torusGeometry args={[0.9, 0.012, 12, 64]} />+ <meshBasicMaterial color={tint} toneMapped={false} transparent depthTest={false} depthWrite={false} />+ </mesh>+ </group>+ )+}++function GizmoPlane({ color, active }: { color: string; active: boolean }): JSX.Element {+ return (+ <mesh renderOrder={998}>+ <planeGeometry args={[0.26, 0.26]} />+ <meshBasicMaterial+ color={active ? lightenColor(color) : color}+ transparent+ opacity={active ? 0.6 : 0.28}+ side={THREE.DoubleSide}+ toneMapped={false}+ depthTest={false}+ depthWrite={false}+ />+ </mesh>+ )+}++function TranslateGizmo({ object, onDragStart, onDragEnd }: { object: THREE.Object3D; onDragStart?: () => void; onDragEnd?: () => void }): JSX.Element {+ const { camera, groupRef, pointerRay, start } = useGizmoBase(object)+ const [hovered, setHovered] = useState<TranslateHandleId | null>(null)+ const [activeId, setActiveId] = useState<TranslateHandleId | null>(null)+ const drag = useRef<{+ axisDir: THREE.Vector3 | null+ planeNormal: THREE.Vector3+ origin: THREE.Vector3+ startHit: THREE.Vector3+ startPos: THREE.Vector3+ } | null>(null)++ const beginDrag = useCallback((id: TranslateHandleId, e: ThreeEvent<PointerEvent>) => {+ e.stopPropagation()+ const origin = new THREE.Vector3()+ object.getWorldPosition(origin)+ const startPos = object.position.clone()++ let axisDir: THREE.Vector3 | null = null+ let planeNormal: THREE.Vector3+ if (id === 'x' || id === 'y' || id === 'z') {+ axisDir = new THREE.Vector3(...AXIS_DIR[id])+ // Drag plane: contains the axis and faces the camera as much as possible.+ const view = new THREE.Vector3().subVectors(camera.position, origin)+ planeNormal = view.sub(axisDir.clone().multiplyScalar(view.dot(axisDir)))+ if (planeNormal.lengthSq() < 1e-6) planeNormal.set(axisDir.y ? 1 : 0, axisDir.y ? 0 : 1, 0)+ planeNormal.normalize()+ } else {+ planeNormal = new THREE.Vector3(...PLANE_HANDLES.find((p) => p.id === id)!.normal)+ }++ const startHit = intersectPlane(e.ray, origin, planeNormal)+ if (!startHit) return+ drag.current = { axisDir, planeNormal, origin, startHit, startPos }+ setActiveId(id)+ onDragStart?.()+ start((ev) => {+ const d = drag.current+ if (!d) return+ const hit = intersectPlane(pointerRay(ev), d.origin, d.planeNormal)+ if (!hit) return+ const delta = new THREE.Vector3().subVectors(hit, d.startHit)+ if (d.axisDir) {+ object.position.copy(d.startPos).addScaledVector(d.axisDir, delta.dot(d.axisDir))+ } else {+ object.position.copy(d.startPos).add(delta)+ }+ }, () => { drag.current = null; setActiveId(null); onDragEnd?.() })+ }, [object, camera, pointerRay, start, onDragStart, onDragEnd])++ return (+ <group ref={groupRef} renderOrder={999}>+ {/* Central origin handle (decorative — never blocks picking) */}+ <mesh raycast={() => null} renderOrder={999}>+ <sphereGeometry args={[0.05, 20, 20]} />+ <meshBasicMaterial color="#e4e4e7" toneMapped={false} transparent depthTest={false} depthWrite={false} />+ </mesh>++ {(['x', 'y', 'z'] as GizmoAxis[]).map((axis) => (+ <group key={axis} rotation={AXIS_ROTATION[axis]} {...hoverHandlers<TranslateHandleId>(axis, setHovered, (e) => beginDrag(axis, e))}>+ <GizmoArrow color={AXIS_COLORS[axis]} active={hovered === axis || activeId === axis} />+ </group>+ ))}++ {PLANE_HANDLES.map((plane) => (+ <group key={plane.id} position={plane.position} rotation={plane.rotation} {...hoverHandlers<TranslateHandleId>(plane.id, setHovered, (e) => beginDrag(plane.id, e))}>+ <GizmoPlane color={plane.color} active={hovered === plane.id || activeId === plane.id} />+ </group>+ ))}+ </group>+ )+}++function RotateGizmo({ object, onDragStart, onDragEnd }: { object: THREE.Object3D; onDragStart?: () => void; onDragEnd?: () => void }): JSX.Element {+ const { groupRef, pointerRay, start } = useGizmoBase(object)+ const [hovered, setHovered] = useState<GizmoAxis | null>(null)+ const [activeId, setActiveId] = useState<GizmoAxis | null>(null)+ const drag = useRef<{+ axisDir: THREE.Vector3+ origin: THREE.Vector3+ startVec: THREE.Vector3+ startQuat: THREE.Quaternion+ } | null>(null)++ const beginDrag = useCallback((axis: GizmoAxis, e: ThreeEvent<PointerEvent>) => {+ e.stopPropagation()+ const origin = new THREE.Vector3()+ object.getWorldPosition(origin)+ const axisDir = new THREE.Vector3(...AXIS_DIR[axis]).normalize()+ // Rotation happens in the plane perpendicular to the axis (the ring's plane).+ const startHit = intersectPlane(e.ray, origin, axisDir)+ if (!startHit) return+ const startVec = new THREE.Vector3().subVectors(startHit, origin)+ if (startVec.lengthSq() < 1e-9) return+ drag.current = { axisDir, origin, startVec, startQuat: object.quaternion.clone() }+ setActiveId(axis)+ onDragStart?.()+ start((ev) => {+ const d = drag.current+ if (!d) return+ const hit = intersectPlane(pointerRay(ev), d.origin, d.axisDir)+ if (!hit) return+ const cur = new THREE.Vector3().subVectors(hit, d.origin)+ // Signed angle between the start and current vectors, around the axis.+ const cross = new THREE.Vector3().crossVectors(d.startVec, cur)+ const angle = Math.atan2(cross.dot(d.axisDir), d.startVec.dot(cur))+ const q = new THREE.Quaternion().setFromAxisAngle(d.axisDir, angle)+ object.quaternion.copy(d.startQuat).premultiply(q)+ }, () => { drag.current = null; setActiveId(null); onDragEnd?.() })+ }, [object, pointerRay, start, onDragStart, onDragEnd])++ return (+ <group ref={groupRef} renderOrder={999}>+ {(['x', 'y', 'z'] as GizmoAxis[]).map((axis) => (+ <group key={axis} rotation={RING_ROTATION[axis]} {...hoverHandlers<GizmoAxis>(axis, setHovered, (e) => beginDrag(axis, e))}>+ <GizmoRing color={AXIS_COLORS[axis]} active={hovered === axis || activeId === axis} />+ </group>+ ))}+ </group>+ )+}++function ScaleGizmo({ object, onDragStart, onDragEnd }: { object: THREE.Object3D; onDragStart?: () => void; onDragEnd?: () => void }): JSX.Element {+ const { camera, groupRef, pointerRay, start } = useGizmoBase(object)+ const [hovered, setHovered] = useState<ScaleHandleId | null>(null)+ const [activeId, setActiveId] = useState<ScaleHandleId | null>(null)+ const drag = useRef<{+ axisDir: THREE.Vector3 | null+ planeNormal: THREE.Vector3+ origin: THREE.Vector3+ startProj: number+ startScale: THREE.Vector3+ armLength: number+ } | null>(null)++ const beginDrag = useCallback((id: ScaleHandleId, e: ThreeEvent<PointerEvent>) => {+ e.stopPropagation()+ const origin = new THREE.Vector3()+ object.getWorldPosition(origin)+ // World length of one local unit — maps drag distance to a sensible factor.+ const armLength = Math.max(groupRef.current?.scale.x ?? 1, 1e-4)++ let axisDir: THREE.Vector3 | null = null+ let planeNormal: THREE.Vector3+ if (id === 'xyz') {+ planeNormal = new THREE.Vector3().subVectors(camera.position, origin).normalize()+ } else {+ axisDir = new THREE.Vector3(...AXIS_DIR[id])+ const view = new THREE.Vector3().subVectors(camera.position, origin)+ planeNormal = view.sub(axisDir.clone().multiplyScalar(view.dot(axisDir)))+ if (planeNormal.lengthSq() < 1e-6) planeNormal.set(axisDir.y ? 1 : 0, axisDir.y ? 0 : 1, 0)+ planeNormal.normalize()+ }++ const startHit = intersectPlane(e.ray, origin, planeNormal)+ if (!startHit) return+ const startRel = new THREE.Vector3().subVectors(startHit, origin)+ const startProj = axisDir ? startRel.dot(axisDir) : startRel.length()+ drag.current = { axisDir, planeNormal, origin, startProj, startScale: object.scale.clone(), armLength }+ setActiveId(id)+ onDragStart?.()+ start((ev) => {+ const d = drag.current+ if (!d) return+ const hit = intersectPlane(pointerRay(ev), d.origin, d.planeNormal)+ if (!hit) return+ const rel = new THREE.Vector3().subVectors(hit, d.origin)+ const proj = d.axisDir ? rel.dot(d.axisDir) : rel.length()+ const factor = Math.max(0.01, 1 + (proj - d.startProj) / d.armLength)+ if (d.axisDir) {+ const s = d.startScale.clone()+ if (d.axisDir.x) s.x = Math.max(0.01, d.startScale.x * factor)+ if (d.axisDir.y) s.y = Math.max(0.01, d.startScale.y * factor)+ if (d.axisDir.z) s.z = Math.max(0.01, d.startScale.z * factor)+ object.scale.copy(s)+ } else {+ object.scale.copy(d.startScale).multiplyScalar(factor)+ }+ }, () => { drag.current = null; setActiveId(null); onDragEnd?.() })+ }, [object, camera, pointerRay, start, groupRef, onDragStart, onDragEnd])++ const uniformActive = hovered === 'xyz' || activeId === 'xyz'++ return (+ <group ref={groupRef} renderOrder={999}>+ {/* Central cube — uniform scale */}+ <mesh {...hoverHandlers<ScaleHandleId>('xyz', setHovered, (e) => beginDrag('xyz', e))} renderOrder={999}>+ <boxGeometry args={[0.12, 0.12, 0.12]} />+ <meshBasicMaterial color={uniformActive ? lightenColor('#e4e4e7') : '#e4e4e7'} toneMapped={false} transparent depthTest={false} depthWrite={false} />+ </mesh>++ {(['x', 'y', 'z'] as GizmoAxis[]).map((axis) => (+ <group key={axis} rotation={AXIS_ROTATION[axis]} {...hoverHandlers<ScaleHandleId>(axis, setHovered, (e) => beginDrag(axis, e))}>+ <GizmoScaleArm color={AXIS_COLORS[axis]} active={hovered === axis || activeId === axis} />+ </group>+ ))}+ </group>+ )+}++// ---------------------------------------------------------------------------+// PointLightMarker — renders a point light + billboard icon + optional gizmo+// ---------------------------------------------------------------------------++function PointLightMarker({+ light,+ isSelected,+ gizmoMode,+ onSelect,+ onPositionChange,+}: {+ light: PointLight+ isSelected: boolean+ gizmoMode: GizmoMode | null+ onSelect: () => void+ onPositionChange: (pos: [number, number, number]) => void+}) {+ const [group, setGroup] = useState<THREE.Group | null>(null)+ const iconTexture = useMemo(() => makeLightBulbTexture(light.color, isSelected), [light.color, isSelected])++ return (+ <>+ <group ref={setGroup} position={light.position}>+ <pointLight color={light.color} intensity={light.intensity} distance={8} decay={2} />+ <sprite+ scale={[0.3, 0.3, 1]}+ onClick={(e) => { e.stopPropagation(); onSelect() }}+ >+ <spriteMaterial map={iconTexture} toneMapped={false} depthTest={false} />+ </sprite>+ </group>+ {group && isSelected && gizmoMode === 'translate' && (+ <TranslateGizmo+ object={group}+ onDragEnd={() => onPositionChange([group.position.x, group.position.y, group.position.z])}+ />+ )}+ {group && isSelected && gizmoMode === 'rotate' && (+ <RotateGizmo+ object={group}+ onDragEnd={() => onPositionChange([group.position.x, group.position.y, group.position.z])}+ />+ )}+ {group && isSelected && gizmoMode === 'scale' && (+ <ScaleGizmo+ object={group}+ onDragEnd={() => onPositionChange([group.position.x, group.position.y, group.position.z])}+ />+ )}+ </>+ )+}++// ---------------------------------------------------------------------------+// EmptyState+// ---------------------------------------------------------------------------++function EmptyState(): JSX.Element {+ return (+ <div className="absolute inset-0 flex flex-col items-center justify-center text-zinc-700 pointer-events-none">+ <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="0.75">+ <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" />+ </svg>+ <p className="mt-4 text-sm">3D model will appear here</p>+ </div>+ )+}++// ---------------------------------------------------------------------------+// Viewer3D+// ---------------------------------------------------------------------------++type TransformSnapshot = { p: THREE.Vector3; q: THREE.Quaternion; s: THREE.Vector3 }++export default function Viewer3D({+ lightSettings = DEFAULT_LIGHT_SETTINGS,+ gizmoMode = null,+ gizmoUndoRef,+ pointLights = [],+ selectedPointLightId = null,+ onSelectPointLight,+ onPointLightsChange,+}: {+ lightSettings?: LightSettings+ gizmoMode?: GizmoMode | null+ gizmoUndoRef?: MutableRefObject<(() => boolean) | null>+ pointLights?: PointLight[]+ selectedPointLightId?: string | null+ onSelectPointLight?: (id: string | null) => void+ onPointLightsChange?: (lights: PointLight[]) => void+}): JSX.Element {+ const { currentJob } = useGeneration()+ const apiUrl = useAppStore((s) => s.apiUrl)++ const setStoreMeshStats = useAppStore((s) => s.setMeshStats)+ const meshStats = useAppStore((s) => s.meshStats)+ const setCurrentJob = useAppStore((s) => s.setCurrentJob)++ const [viewMode, setViewMode] = useState<ViewMode>('solid')+ const [autoRotate, setAutoRotate] = useState(false)+ const selected = useAppStore((s) => s.meshSelected)+ const setSelected = useAppStore((s) => s.setMeshSelected)+ const canvasRef = useRef<HTMLCanvasElement | null>(null)+ const splatRef = useRef<SplatViewerHandle | null>(null)++ const [meshObject, setMeshObject] = useState<THREE.Object3D | null>(null)++ // Local gizmo-transform history (live TRS), undoable with Ctrl+Z. A snapshot+ // is taken when a drag starts and committed on release only if it changed.+ const transformHistory = useRef<TransformSnapshot[]>([])+ const pendingTransform = useRef<TransformSnapshot | null>(null)++ const outputUrl = currentJob?.outputUrl ?? ''+ const modelUrl =+ currentJob?.status === 'done' && currentJob.outputUrl+ ? `${apiUrl}${currentJob.outputUrl}`+ : null++ // A .ply/.splat reaching the viewer is always a Gaussian splat here: mesh+ // plys are converted to GLB on import and workflow mesh outputs are .glb.+ const isSplat = /\.(ply|splat)$/i.test(outputUrl)++ // The splat viewer needs binary .splat — route raw workspace .ply through the+ // conversion endpoint; import URLs already point at a .splat via serve-file.+ const splatUrl = outputUrl.startsWith('/workspace/')+ ? `${apiUrl}/optimize/ply-to-splat?path=${encodeURIComponent(outputUrl.slice('/workspace/'.length))}`+ : modelUrl++ // Reset view state when model changes+ useEffect(() => {+ setSelected(false)+ setViewMode('solid')+ setStoreMeshStats(null)+ // eslint-disable-next-line react-hooks/exhaustive-deps -- reset only when the model changes; setters are stable+ }, [modelUrl])++ // Clear the shared selection when the viewer unmounts — the store would+ // otherwise keep it set and flash a stale selection on the next mount.+ useEffect(() => () => setSelected(false), [setSelected])++ // Delete key removes the model from the scene+ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ if (e.key !== 'Delete') return+ if (document.activeElement instanceof HTMLInputElement) return+ if (!selected) return+ setCurrentJob(null)+ setSelected(false)+ }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ // eslint-disable-next-line react-hooks/exhaustive-deps -- setSelected is a stable store setter+ }, [selected, setCurrentJob])++ // Deselect both mesh and point light when clicking empty space+ const handlePointerMissed = useCallback(() => {+ setSelected(false)+ onSelectPointLight?.(null)+ }, [setSelected, onSelectPointLight])++ // Select mesh and deselect any selected point light+ const handleMeshSelect = useCallback(() => {+ setSelected(true)+ onSelectPointLight?.(null)+ }, [setSelected, onSelectPointLight])++ const handleScreenshot = () => {+ const dataUrl = isSplat+ ? splatRef.current?.screenshot() ?? null+ : canvasRef.current?.toDataURL('image/png') ?? null+ if (!dataUrl) return+ const link = document.createElement('a')+ link.download = `modly-${Date.now()}.png`+ link.href = dataUrl+ link.click()+ }++ // Snapshot the pre-drag pose when a gizmo manipulation starts.+ const handleGizmoDragStart = useCallback(() => {+ if (meshObject) {+ pendingTransform.current = {+ p: meshObject.position.clone(),+ q: meshObject.quaternion.clone(),+ s: meshObject.scale.clone(),+ }+ }+ }, [meshObject])++ // Commit the snapshot on release, but only if the pose actually changed.+ const handleGizmoDragEnd = useCallback(() => {+ const before = pendingTransform.current+ pendingTransform.current = null+ if (!before || !meshObject) return+ const changed = !meshObject.position.equals(before.p)+ || !meshObject.quaternion.equals(before.q)+ || !meshObject.scale.equals(before.s)+ if (changed) transformHistory.current.push(before)+ }, [meshObject])++ // Revert the most recent gizmo manipulation. Returns false when there is+ // nothing to undo, so the caller can fall back to the mesh-history undo.+ const undoTransform = useCallback((): boolean => {+ const prev = transformHistory.current.pop()+ if (!prev || !meshObject) return false+ meshObject.position.copy(prev.p)+ meshObject.quaternion.copy(prev.q)+ meshObject.scale.copy(prev.s)+ return true+ }, [meshObject])++ // Expose transform-undo so the page's Ctrl+Z undoes gizmo edits first.+ useEffect(() => {+ if (!gizmoUndoRef) return+ gizmoUndoRef.current = undoTransform+ return () => { if (gizmoUndoRef.current === undoTransform) gizmoUndoRef.current = null }+ }, [gizmoUndoRef, undoTransform])++ // Drop the transform history when the model changes.+ useEffect(() => {+ transformHistory.current = []+ pendingTransform.current = null+ }, [modelUrl])++ // Memoise the post-processing stack so its children stay referentially stable.+ // @react-three/postprocessing rebuilds (recompiles) all EffectPasses whenever the+ // <EffectComposer> children identity changes; without this, every Viewer3D re-render+ // (e.g. dragging a Lighting slider) recompiles the outline shader. The Outline still+ // tracks selection through the <Selection> context, so nothing here needs to depend+ // on render state.+ const postProcessing = useMemo(() => (+ <EffectComposer+ autoClear={false}+ multisampling={SELECTION_OUTLINE_MULTISAMPLING}+ resolutionScale={SELECTION_OUTLINE_RESOLUTION_SCALE}+ frameBufferType={THREE.HalfFloatType}+ >+ <Outline+ blur={SELECTION_OUTLINE_BLUR}+ edgeStrength={SELECTION_OUTLINE_EDGE_STRENGTH}+ visibleEdgeColor={SELECTION_OUTLINE_VISIBLE_COLOR}+ hiddenEdgeColor={SELECTION_OUTLINE_HIDDEN_COLOR}+ xRay={false}+ />+ </EffectComposer>+ ), [])+++ return (+ <ModelErrorBoundary resetKey={modelUrl} fallback={<ModelLoadError />}>+ <div className="relative w-full h-full bg-surface-400">+ {!modelUrl && <EmptyState />}++ {/* Splat path → fully isolated viewer (mkkellogg, outside R3F) */}+ {modelUrl && isSplat && splatUrl ? (+ <SplatViewer ref={splatRef} url={splatUrl} autoRotate={autoRotate} />+ ) : null}++ {/* Mesh path → original Canvas, unchanged */}+ {!isSplat && (+ <Canvas+ onPointerMissed={handlePointerMissed}+ camera={{ position: [0, 1.5, 4], fov: 45 }}+ dpr={[1, 2]}+ gl={{+ antialias: true,+ preserveDrawingBuffer: true,+ outputColorSpace: THREE.SRGBColorSpace,+ }}+ >+ <color attach="background" args={['#18181b']} />+ <CanvasCapture domRef={canvasRef} />+ <ambientLight intensity={lightSettings.ambientIntensity ?? DEFAULT_LIGHT_SETTINGS.ambientIntensity} />+ <Environment background={false}>+ <Lightformer intensity={2 * (lightSettings.envIntensity ?? DEFAULT_LIGHT_SETTINGS.envIntensity)} position={[0, 4, 4]} scale={8} />+ <Lightformer intensity={0.5 * (lightSettings.envIntensity ?? DEFAULT_LIGHT_SETTINGS.envIntensity)} position={[-4, 2, -4]} scale={6} />+ <Lightformer intensity={0.3 * (lightSettings.envIntensity ?? DEFAULT_LIGHT_SETTINGS.envIntensity)} position={[4, 1, -4]} scale={6} />+ </Environment>++ <gridHelper args={[10, 20, '#3f3f46', '#27272a']} />++ {modelUrl && currentJob ? (+ <Selection enabled={selected}>+ {postProcessing}+ <Suspense fallback={null}>+ <directionalLight position={[5, 8, 5]} color={lightSettings.mainColor} intensity={lightSettings.mainIntensity} castShadow />+ <directionalLight position={[-4, 2, -4]} color={lightSettings.fillColor} intensity={lightSettings.fillIntensity} />+ <MeshModel+ url={modelUrl}+ jobId={currentJob.id}+ viewMode={viewMode}+ selected={selected}+ onStats={setStoreMeshStats}+ onSelect={handleMeshSelect}+ onObject={setMeshObject}+ />+ </Suspense>+ </Selection>+ ) : null}++ {/* Point light markers */}+ {onPointLightsChange && pointLights.map((pl) => (+ <PointLightMarker+ key={pl.id}+ light={pl}+ isSelected={pl.id === selectedPointLightId}+ gizmoMode={gizmoMode}+ onSelect={() => {+ setSelected(false)+ onSelectPointLight?.(pl.id)+ }}+ onPositionChange={(pos) => {+ onPointLightsChange!(pointLights.map((p) => p.id === pl.id ? { ...p, position: pos } : p))+ }}+ />+ ))}++ {selected && meshObject && gizmoMode === 'translate' && (+ <TranslateGizmo object={meshObject} onDragStart={handleGizmoDragStart} onDragEnd={handleGizmoDragEnd} />+ )}+ {selected && meshObject && gizmoMode === 'rotate' && (+ <RotateGizmo object={meshObject} onDragStart={handleGizmoDragStart} onDragEnd={handleGizmoDragEnd} />+ )}+ {selected && meshObject && gizmoMode === 'scale' && (+ <ScaleGizmo object={meshObject} onDragStart={handleGizmoDragStart} onDragEnd={handleGizmoDragEnd} />+ )}++ <OrbitControls+ makeDefault+ enablePan+ enableZoom+ enableRotate+ minDistance={0.5}+ maxDistance={20}+ autoRotate={autoRotate}+ autoRotateSpeed={1.5}+ enableDamping+ dampingFactor={0.05}+ />++ <GizmoHelper alignment="top-right" margin={[72, 72]} renderPriority={modelUrl && currentJob ? 2 : 0}>+ <GizmoBubbles />+ </GizmoHelper>+ </Canvas>+ )}++ {/* Left toolbar — visible only when a model is loaded */}+ {modelUrl && (+ <ViewerToolbar+ viewMode={viewMode}+ autoRotate={autoRotate}+ onViewMode={setViewMode}+ onAutoRotate={() => setAutoRotate((v) => !v)}+ onScreenshot={handleScreenshot}+ showViewModes={!isSplat}+ />+ )}++ {/* Bottom-left stats overlay */}+ {meshStats && (+ <div className="absolute bottom-4 left-4 pointer-events-none">+ <p className="text-xs text-zinc-500">+ {meshStats.triangles.toLocaleString()} tri • {meshStats.vertices.toLocaleString()} verts+ </p>+ </div>+ )}++ {/* Bottom-right hint */}+ {modelUrl && (+ <div className="absolute bottom-4 right-4 pointer-events-none">+ <p className="text-xs text-zinc-600">+ {selected+ ? <>Click mesh to select • <span className="text-zinc-500">Delete</span> to remove</>+ : 'Drag to rotate \u2022 Scroll to zoom'+ }+ </p>+ </div>+ )}+ </div>+ </ModelErrorBoundary>+ )+}\ No newline at end of filediff --git a/apps/forge-desktop/src/areas/generate/components/ViewerToolbar.tsx b/apps/forge-desktop/src/areas/generate/components/ViewerToolbar.tsxnew file mode 100644index 000000000..c83d4f33c--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/components/ViewerToolbar.tsx@@ -0,0 +1,141 @@+import type { ViewMode } from '../models'+export type { ViewMode }++interface ViewerToolbarProps {+ viewMode: ViewMode+ autoRotate: boolean+ onViewMode: (mode: ViewMode) => void+ onAutoRotate: () => void+ onScreenshot: () => void+ showViewModes?: boolean // view modes are mesh-only; hidden for splats+}++const MODES: { mode: ViewMode; icon: React.ReactNode; label: string }[] = [+ {+ mode: 'solid',+ label: 'Solid',+ icon: (+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" />+ </svg>+ ),+ },+ {+ mode: 'wireframe',+ label: 'Wireframe',+ icon: (+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <rect x="3" y="3" width="18" height="18" rx="1" />+ <line x1="3" y1="9" x2="21" y2="9" />+ <line x1="3" y1="15" x2="21" y2="15" />+ <line x1="9" y1="3" x2="9" y2="21" />+ <line x1="15" y1="3" x2="15" y2="21" />+ </svg>+ ),+ },+ {+ mode: 'normals',+ label: 'Normals',+ icon: (+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <circle cx="12" cy="12" r="9" />+ <ellipse cx="12" cy="12" rx="4" ry="9" />+ <line x1="3" y1="12" x2="21" y2="12" />+ </svg>+ ),+ },+ {+ mode: 'matcap',+ label: 'Matcap',+ icon: (+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <circle cx="12" cy="12" r="9" />+ <path d="M8 10 Q10 7 12 10 Q14 13 16 10" />+ </svg>+ ),+ },+ {+ mode: 'uv',+ label: 'UV Checker',+ icon: (+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <rect x="3" y="3" width="18" height="18" rx="1" />+ <rect x="3" y="3" width="9" height="9" fill="currentColor" fillOpacity="0.3" />+ <rect x="12" y="12" width="9" height="9" fill="currentColor" fillOpacity="0.3" />+ </svg>+ ),+ },+]++export function ViewerToolbar({+ viewMode,+ autoRotate,+ onViewMode,+ onAutoRotate,+ onScreenshot,+ showViewModes = true,+}: ViewerToolbarProps): JSX.Element {+ return (+ <div className="absolute left-4 top-1/2 -translate-y-1/2 z-20 flex flex-col gap-1 bg-zinc-900/70 border border-zinc-700/50 backdrop-blur-sm rounded-xl p-1.5">+ {showViewModes && MODES.map(({ mode, icon, label }) => (+ <ToolbarButton+ key={mode}+ active={viewMode === mode}+ label={label}+ onClick={() => onViewMode(mode)}+ >+ {icon}+ </ToolbarButton>+ ))}++ {showViewModes && <div className="my-1 border-t border-zinc-700/50" />}++ <ToolbarButton+ active={autoRotate}+ label="Auto-rotate"+ onClick={onAutoRotate}+ >+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />+ <path d="M3 3v5h5" />+ </svg>+ </ToolbarButton>++ <ToolbarButton+ active={false}+ label="Screenshot"+ onClick={onScreenshot}+ >+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">+ <path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3z" />+ <circle cx="12" cy="13" r="3" />+ </svg>+ </ToolbarButton>+ </div>+ )+}++interface ToolbarButtonProps {+ active: boolean+ label: string+ onClick: () => void+ children: React.ReactNode+}++function ToolbarButton({ active, label, onClick, children }: ToolbarButtonProps): JSX.Element {+ return (+ <button+ title={label}+ onClick={onClick}+ className={`+ relative w-8 h-8 flex items-center justify-center rounded-lg transition-colors+ ${active+ ? 'bg-violet-600 text-white'+ : 'text-zinc-400 hover:text-zinc-200 hover:bg-zinc-700/60'+ }+ `}+ >+ {children}+ </button>+ )+}diff --git a/apps/forge-desktop/src/areas/generate/components/WorkflowPanel.tsx b/apps/forge-desktop/src/areas/generate/components/WorkflowPanel.tsxnew file mode 100644index 000000000..14b257815--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/components/WorkflowPanel.tsx@@ -0,0 +1,723 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import {+ ReactFlowProvider,+ useNodesState, useEdgesState, useReactFlow,+ type Node as FlowNode, type Edge as FlowEdge,+} from '@xyflow/react'+// ReactFlowProvider wraps EmbeddedCanvas so useReactFlow() works in param rows+import { useWorkflowsStore } from '@shared/stores/workflowsStore'+import { useAppStore } from '@shared/stores/appStore'+import { useExtensionsStore } from '@shared/stores/extensionsStore'+import { useNavStore } from '@shared/stores/navStore'+import { useWorkflowRunStore } from '@areas/workflows/workflowRunStore'+import { useWaitButton } from '@areas/workflows/useWaitButton'+import { buildAllWorkflowExtensions, getWorkflowExtension } from '@areas/workflows/mockExtensions'+import { validateWorkflowPreflight } from '@areas/workflows/preflight'+import { mimeFromPath } from '@areas/workflows/nodes/imageUtils'+import type { WorkflowExtension } from '@areas/workflows/mockExtensions'+import type { Workflow, WFNode, WFEdge, ParamSchema } from '@shared/types/electron.d'+import { PICKER_LABELS, openParamPicker, resolvePickerIntent } from '@shared/utils/paramPicker'+import { FloatInput, IntInput, PickerIcon } from '@shared/components/ui'+import { isMissingWeightVariant, withWeightVariantAvailability } from '@shared/utils/weightVariants'+import ChatPanel from './ChatPanel'++type PanelMode = 'basic' | 'chat'++// ─── Constants ────────────────────────────────────────────────────────────────++const TYPE_COLOR: Record<string, string> = {+ image: '#38bdf8',+ mesh: '#a78bfa',+ text: '#fbbf24',+}++const SUPPORTED_IMAGE_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp'])++// ─── Helpers ──────────────────────────────────────────────────────────────────++function topoSortNodes(nodes: Workflow['nodes'], edges: Workflow['edges']): WFNode[] {+ const nodeMap = new Map(nodes.map((n) => [n.id, n]))+ const inDegree = new Map(nodes.map((n) => [n.id, 0]))+ const adj = new Map(nodes.map((n) => [n.id, [] as string[]]))+ for (const e of edges) {+ if (!nodeMap.has(e.source) || !nodeMap.has(e.target)) continue+ adj.get(e.source)!.push(e.target)+ inDegree.set(e.target, (inDegree.get(e.target) ?? 0) + 1)+ }+ const queue = nodes.filter((n) => (inDegree.get(n.id) ?? 0) === 0)+ const result: WFNode[] = []+ while (queue.length > 0) {+ const node = queue.shift()!+ result.push(node)+ for (const neighbor of adj.get(node.id) ?? []) {+ const deg = (inDegree.get(neighbor) ?? 0) - 1+ inDegree.set(neighbor, deg)+ if (deg === 0) queue.push(nodeMap.get(neighbor)!)+ }+ }+ return result+}++// ─── Param field ──────────────────────────────────────────────────────────────++const inputCls = 'w-full bg-zinc-800 border border-zinc-700/80 rounded-md px-2 py-1 text-[11px] text-zinc-200 focus:outline-none focus:border-accent/60'++function ParamField({ param, value, onChange }: {+ param: ParamSchema+ value: number | string+ onChange: (v: number | string) => void+}) {+ if (param.type === 'select') {+ return (+ <select value={value} onChange={(e) => onChange(e.target.value)} className={inputCls}>+ {param.options?.map((o) => (+ <option key={String(o.value)} value={o.value}>{o.label ?? String(o.value)}</option>+ ))}+ </select>+ )+ }+ if (param.type === 'string') {+ const intent = resolvePickerIntent(param)+ return (+ <div className="flex items-center gap-1">+ <input type="text" value={value as string} placeholder={param.tooltip ?? ''}+ onChange={(e) => onChange(e.target.value)} className={`${inputCls} flex-1`} />+ <button onClick={async () => {+ const p = await openParamPicker(param, window.electron.fs)+ if (p) onChange(p)+ }} title={PICKER_LABELS[intent]} aria-label={PICKER_LABELS[intent]}+ className="shrink-0 flex items-center justify-center w-6 h-6 rounded bg-zinc-700 hover:bg-zinc-600 text-zinc-400 hover:text-zinc-200 transition-colors">+ <PickerIcon intent={intent} />+ </button>+ </div>+ )+ }+ if (param.type === 'float') {+ return <FloatInput value={value as number} onChange={(v) => onChange(v)} className={inputCls}+ min={param.min} max={param.max} step={param.step} label={param.label} />+ }+ // int+ return <IntInput value={value as number} onChange={(v) => onChange(v)} className={inputCls} />+}++// ─── Workflow dropdown ────────────────────────────────────────────────────────++function WorkflowDropdown({ workflows, value, onChange }: {+ workflows: Workflow[]+ value: string | null+ onChange: (id: string) => void+}) {+ const [open, setOpen] = useState(false)+ const selected = workflows.find((w) => w.id === value)++ if (workflows.length === 0) {+ return (+ <div className="px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-800 text-zinc-600 text-xs">+ No workflows yet+ </div>+ )+ }++ return (+ <div className="relative">+ <button+ onClick={() => setOpen((v) => !v)}+ className={`w-full flex items-center justify-between px-3 py-2 rounded-lg bg-zinc-900 border text-left transition-colors ${open ? 'border-zinc-600' : 'border-zinc-800 hover:border-zinc-700'}`}+ >+ <span className="text-xs font-medium text-zinc-200 truncate">+ {selected?.name ?? 'Select a workflow…'}+ </span>+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"+ className={`shrink-0 ml-2 text-zinc-500 transition-transform ${open ? 'rotate-180' : ''}`}>+ <polyline points="6 9 12 15 18 9"/>+ </svg>+ </button>++ {open && (+ <div className="absolute top-full mt-1 left-0 right-0 z-50 rounded-lg bg-zinc-900 border border-zinc-700 shadow-xl overflow-hidden">+ {workflows.map((wf, i) => (+ <button key={wf.id} onClick={() => { onChange(wf.id); setOpen(false) }}+ className={`w-full flex items-center gap-2 px-3 py-2 text-left text-xs transition-colors+ ${i > 0 ? 'border-t border-zinc-800' : ''}+ ${wf.id === value ? 'bg-zinc-800 text-zinc-100' : 'text-zinc-300 hover:bg-zinc-800/60'}`}>+ <span className="flex-1 truncate">{wf.name}</span>+ <span className="text-[9px] text-zinc-600 shrink-0">+ {wf.nodes.filter((n) => n.type === 'extensionNode').length} nodes+ </span>+ </button>+ ))}+ </div>+ )}+ </div>+ )+}++// ─── Node param rows ──────────────────────────────────────────────────────────+// These components receive nodes + onPatch directly from EmbeddedCanvas+// to avoid relying on the React Flow store (which requires a mounted <ReactFlow>).++type PatchFn = (nodeId: string, patch: Record<string, unknown>) => void++function ImageParamRow({ nodeId, nodes, onPatch }: { nodeId: string; nodes: FlowNode[]; onPatch: PatchFn }) {+ const node = nodes.find((n) => n.id === nodeId)+ const data = node?.data as { params: Record<string, unknown> } | undefined+ const preview = data?.params.preview as string | undefined+ const showToast = useAppStore((state) => state.showToast)+ const loadRequest = useRef(0)++ const applyImagePath = useCallback(async (path: string | null) => {+ const request = ++loadRequest.current+ if (!path) return+ try {+ const base64 = await window.electron.fs.readFileBase64(path)+ if (request !== loadRequest.current) return+ const src = `data:${mimeFromPath(path)};base64,${base64}`+ onPatch(nodeId, { params: { ...(data?.params ?? {}), filePath: path, preview: src } })+ } catch {+ if (request === loadRequest.current) showToast('Unable to load the selected image')+ }+ }, [nodeId, data?.params, onPatch, showToast])++ const browse = useCallback(async () => {+ await applyImagePath(await window.electron.fs.selectImage())+ }, [applyImagePath])++ return (+ <div+ className="flex flex-col gap-1.5"+ onDragOver={(event) => {+ event.preventDefault()+ event.dataTransfer.dropEffect = 'copy'+ }}+ onDrop={(event) => {+ event.preventDefault()+ const file = event.dataTransfer.files[0]+ if (!file || !SUPPORTED_IMAGE_TYPES.has(file.type)) return+ void applyImagePath(window.electron.fs.getPathForFile(file))+ }}+ >+ <div className="flex items-center gap-1.5">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#38bdf8" strokeWidth="2">+ <rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/>+ <polyline points="21 15 16 10 5 21"/>+ </svg>+ <span className="text-[11px] font-medium text-zinc-300">Image</span>+ </div>+ {preview ? (+ <button onClick={browse} className="relative w-full aspect-square rounded-lg overflow-hidden border border-zinc-700 group">+ <img src={preview} alt="" className="w-full h-full object-cover" />+ <div className="absolute inset-0 bg-black/0 group-hover:bg-black/50 transition-colors flex items-center justify-center">+ <span className="text-[10px] text-white font-medium opacity-0 group-hover:opacity-100 transition-opacity">Change…</span>+ </div>+ </button>+ ) : (+ <button onClick={browse}+ className="w-full aspect-square flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-zinc-700 hover:border-sky-500/50 hover:bg-sky-500/5 transition-colors">+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="text-zinc-600">+ <rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/>+ <polyline points="21 15 16 10 5 21"/>+ </svg>+ <span className="text-[10px] text-zinc-500">Browse image…</span>+ </button>+ )}+ </div>+ )+}++function MeshParamRow({ nodeId, nodes, onPatch }: { nodeId: string; nodes: FlowNode[]; onPatch: PatchFn }) {+ const node = nodes.find((n) => n.id === nodeId)+ const data = node?.data as { params: Record<string, unknown> } | undefined+ const source = (data?.params.source as 'file' | 'current' | undefined) ?? 'file'+ const fileName = data?.params.fileName as string | undefined++ const browse = useCallback(async () => {+ const p = await window.electron.fs.selectMeshFile()+ if (!p) return+ const name = p.split(/[\\/]/).pop() ?? p+ onPatch(nodeId, { params: { ...(data?.params ?? {}), filePath: p, fileName: name, source: 'file' } })+ }, [nodeId, data?.params, onPatch])++ const toggleSource = useCallback(() => {+ const next = source === 'file' ? 'current' : 'file'+ onPatch(nodeId, { params: { ...(data?.params ?? {}), source: next } })+ }, [nodeId, data?.params, source, onPatch])++ return (+ <div className="flex flex-col gap-2">+ <div className="flex items-center gap-1.5">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#a78bfa" strokeWidth="2">+ <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/>+ </svg>+ <span className="text-[11px] font-medium text-zinc-300">Load 3D Mesh</span>+ </div>++ {/* Toggle: use current model */}+ <button onClick={toggleSource} className="flex items-center gap-2 w-full text-left">+ <div className={`w-7 h-4 rounded-full relative shrink-0 transition-colors ${source === 'current' ? 'bg-violet-500' : 'bg-zinc-700'}`}>+ <div className={`absolute top-0.5 w-3 h-3 rounded-full bg-white shadow transition-transform ${source === 'current' ? 'translate-x-3.5' : 'translate-x-0.5'}`} />+ </div>+ <span className="text-[10px] text-zinc-400">Use current model</span>+ </button>++ {source === 'file' ? (+ fileName ? (+ <button onClick={browse}+ className="w-full flex items-center gap-2 px-2.5 py-2 rounded-lg bg-zinc-800 hover:bg-zinc-700 transition-colors group">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#a78bfa" strokeWidth="2" className="shrink-0">+ <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/>+ </svg>+ <span className="text-[10px] text-zinc-300 truncate flex-1 text-left">{fileName}</span>+ <span className="text-[9px] text-zinc-500 group-hover:text-zinc-400 shrink-0">Change…</span>+ </button>+ ) : (+ <button onClick={browse}+ className="w-full flex items-center justify-center gap-2 py-5 rounded-lg border border-dashed border-zinc-700 hover:border-violet-500/50 hover:bg-violet-500/5 transition-colors">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="text-zinc-600">+ <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/>+ </svg>+ <span className="text-[10px] text-zinc-500">Browse mesh…</span>+ </button>+ )+ ) : (+ <div className="px-2.5 py-2 rounded-lg bg-zinc-800/50 border border-zinc-700/40">+ <span className="text-[10px] text-zinc-500">Uses the model currently loaded in the 3D viewer</span>+ </div>+ )}+ </div>+ )+}++function TextParamRow({ nodeId, nodes, onPatch }: { nodeId: string; nodes: FlowNode[]; onPatch: PatchFn }) {+ const node = nodes.find((n) => n.id === nodeId)+ const data = node?.data as { params: Record<string, unknown> } | undefined+ const text = (data?.params.text as string | undefined) ?? ''++ return (+ <div className="flex flex-col gap-1.5">+ <div className="flex items-center gap-1.5">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#fbbf24" strokeWidth="2">+ <path d="M17 6.1H3M21 12.1H3M15.1 18H3"/>+ </svg>+ <span className="text-[11px] font-medium text-zinc-300">Text</span>+ </div>+ <textarea+ value={text}+ onChange={(e) => onPatch(nodeId, { params: { ...(data?.params ?? {}), text: e.target.value } })}+ placeholder="Enter text…" rows={3}+ className="w-full bg-zinc-800 border border-zinc-700/80 rounded-md px-2.5 py-2 text-[11px] text-zinc-200 placeholder-zinc-600 focus:outline-none focus:border-amber-500/40 resize-none leading-relaxed"+ />+ </div>+ )+}++function WaitParamRow({ nodeId }: { nodeId: string }) {+ const { waitState, canContinue, isRunning, label, buttonClass, onContinue } = useWaitButton(nodeId)++ return (+ <div className="flex flex-col gap-1.5">+ <div className="flex items-center gap-1.5">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#71717a" strokeWidth="2">+ <circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>+ </svg>+ <span className="text-[11px] font-medium text-zinc-300">Wait</span>+ </div>+ {waitState ? (+ <button+ onClick={onContinue}+ disabled={!canContinue}+ className={`w-full flex items-center justify-center gap-1.5 px-2.5 py-2 rounded-md border transition-colors text-[11px] font-medium ${buttonClass} ${+ canContinue ? (waitState === 'pending' ? 'animate-pulse' : '') : 'opacity-40 cursor-not-allowed'+ }`}+ >+ {isRunning ? (+ <>+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" className="animate-spin">+ <path d="M21 12a9 9 0 1 1-6.219-8.56" />+ </svg>+ Running…+ </>+ ) : (+ <>+ <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor">+ <polygon points="5 3 19 12 5 21 5 3"/>+ </svg>+ {label}+ </>+ )}+ </button>+ ) : (+ <p className="text-[10px] text-zinc-600 italic px-0.5">+ Pauses the workflow until you click Continue.+ </p>+ )}+ </div>+ )+}++function ExtensionParamRow({ nodeId, ext, nodes, onPatch }: { nodeId: string; ext: WorkflowExtension; nodes: FlowNode[]; onPatch: PatchFn }) {+ const [expanded, setExpanded] = useState(true)+ const installedVariants = useExtensionsStore((s) => s.installedWeightVariants[ext.id])+ const openExtension = useNavStore((s) => s.openExtension)+ const node = nodes.find((n) => n.id === nodeId)+ const data = node?.data as { enabled: boolean; params: Record<string, unknown> } | undefined+ const enabled = data?.enabled ?? true++ const inputColor = TYPE_COLOR[ext.input] ?? '#71717a'+ const outputColor = TYPE_COLOR[ext.output] ?? '#71717a'++ return (+ <div className={`flex flex-col transition-opacity ${enabled ? '' : 'opacity-40'}`}>+ <div className="flex items-center gap-2">+ <div className="flex-1 min-w-0">+ <p className="text-[11px] font-medium text-zinc-200 truncate">{ext.name}</p>+ <div className="flex items-center gap-1 mt-0.5">+ <span className="text-[9px]" style={{ color: inputColor }}>{ext.input}</span>+ <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-600">+ <line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/>+ </svg>+ <span className="text-[9px]" style={{ color: outputColor }}>{ext.output}</span>+ </div>+ </div>++ {/* Toggle enabled */}+ <button onClick={() => onPatch(nodeId, { enabled: !enabled })}+ className="relative shrink-0" style={{ width: 26, height: 15 }}>+ <span className={`absolute inset-0 rounded-full transition-colors ${enabled ? 'bg-accent/70' : 'bg-zinc-700'}`} />+ <span className={`absolute top-[1.5px] w-3 h-3 rounded-full bg-white shadow transition-all ${enabled ? 'left-[11px]' : 'left-[1.5px]'}`} />+ </button>++ {ext.params.length > 0 && (+ <button onClick={() => setExpanded((v) => !v)}+ className="p-0.5 rounded text-zinc-600 hover:text-zinc-400 transition-colors">+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"+ className={`transition-transform ${expanded ? 'rotate-180' : ''}`}>+ <polyline points="6 9 12 15 18 9"/>+ </svg>+ </button>+ )}+ </div>++ {expanded && ext.params.length > 0 && (+ <div className="mt-2 flex flex-col gap-2">+ {ext.params.map((param) => {+ const val = ((data?.params[param.id] ?? param.default) as number | string)+ return (+ <div key={param.id} className="flex items-center gap-2">+ <label className="text-[10px] text-zinc-500 w-20 shrink-0 truncate">{param.label}</label>+ <div className="flex-1">+ <ParamField param={withWeightVariantAvailability(param, ext.weightVariants, installedVariants)} value={val}+ onChange={(v) => onPatch(nodeId, { params: { ...(data?.params ?? {}), [param.id]: v } })} />+ {/* Offer the install instead of leaving the panel on selection. */}+ {isMissingWeightVariant(param.id, val, ext.weightVariants, installedVariants) && (+ <button+ onClick={() => openExtension(ext.extensionId)}+ className="mt-1 text-[10px] text-amber-400 hover:text-amber-300 hover:underline"+ >+ Not installed — install it+ </button>+ )}+ </div>+ </div>+ )+ })}+ </div>+ )}+ </div>+ )+}++// ─── Embedded canvas ──────────────────────────────────────────────────────────++function EmbeddedCanvas({ workflow, allExtensions }: {+ workflow: Workflow+ allExtensions: ReturnType<typeof buildAllWorkflowExtensions>+}) {+ const [nodes, setNodes] = useNodesState(workflow.nodes as FlowNode[])+ const [edges, setEdges] = useEdgesState(workflow.edges as FlowEdge[])+ const { updateNodeData } = useReactFlow()+ const { navigate } = useNavStore()+ const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null)++ // Direct patch into controlled nodes state — no React Flow store dependency+ const patchNode = useCallback<PatchFn>((nodeId, patch) => {+ setNodes((nds) => nds.map((n) =>+ n.id === nodeId ? { ...n, data: { ...n.data, ...patch } } : n,+ ))+ // Push params live so a paused/looping run uses the latest values on the next node start.+ if (patch.params) {+ useWorkflowRunStore.getState().setLiveNodeParams(nodeId, patch.params as Record<string, unknown>)+ }+ }, [setNodes])++ // ─── Tab sync ──────────────────────────────────────────────────────────────+ const lastSyncedAtRef = useRef<string>(workflow.updatedAt)+ const didMountRef = useRef(false)++ // Sync local state when Workflows tab saves to the store (Workflows→Generate)+ useEffect(() => {+ if (workflow.updatedAt === lastSyncedAtRef.current) return+ setNodes(workflow.nodes as FlowNode[])+ setEdges(workflow.edges as FlowEdge[])+ lastSyncedAtRef.current = workflow.updatedAt+ // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on updatedAt only; adding nodes/edges would resync on every local edit+ }, [workflow.updatedAt])++ // Persist to the store and claim the echo so the sync effect above does not+ // treat our own write as an external change. The claim is optimistic — the store+ // is updated before save() resolves — and is rolled back when the write fails, so+ // a failed save never silently replaces the canvas with the last persisted version.+ const saveAndClaim = useCallback((updated: Workflow) => {+ const prevSyncedAt = lastSyncedAtRef.current+ lastSyncedAtRef.current = updated.updatedAt+ void useWorkflowsStore.getState().save(updated).then((res) => {+ if (!res.success) lastSyncedAtRef.current = prevSyncedAt+ })+ }, [])++ // Debounced save to the store when local state changes (Generate→Workflows)+ // No cleanup return — lets the timer fire even if user navigates away+ useEffect(() => {+ if (!didMountRef.current) { didMountRef.current = true; return }+ if (saveTimer.current) clearTimeout(saveTimer.current)+ saveTimer.current = setTimeout(() => {+ saveTimer.current = null+ saveAndClaim({+ ...workflow,+ nodes: nodes as WFNode[],+ edges: edges as WFEdge[],+ updatedAt: new Date().toISOString(),+ })+ }, 500)+ // eslint-disable-next-line react-hooks/exhaustive-deps -- debounce on editable state; latest workflow read in the timeout+ }, [nodes, edges])++ const currentMeshUrl = useAppStore((s) => s.currentJob?.outputUrl)+ const showToast = useAppStore((s) => s.showToast)+ const { runState, run, cancel } = useWorkflowRunStore()+ const isRunning = runState.status === 'running' || runState.status === 'paused'++ // Update AddToScene node when run completes+ useEffect(() => {+ if (runState.status !== 'done' || !runState.outputUrl) return+ const out = nodes.find((n) => n.type === 'outputNode')+ if (out) updateNodeData(out.id, { params: { outputUrl: runState.outputUrl } })+ // eslint-disable-next-line react-hooks/exhaustive-deps -- react to run completion; nodes/updateNodeData read at that point+ }, [runState.status, runState.outputUrl])++ const preflightIssues = useMemo(() => {+ const wf: Workflow = { ...workflow, nodes: nodes as WFNode[], edges: edges as WFEdge[] }+ return validateWorkflowPreflight(wf, allExtensions, { currentMeshUrl })+ }, [workflow, nodes, edges, allExtensions, currentMeshUrl])++ const firstPreflightIssue = preflightIssues[0]?.message ?? null++ // Ordered nodes for params list — only those marked showInGenerate+ const sortedNodes = useMemo(+ () => topoSortNodes(nodes as WFNode[], edges as WFEdge[]),+ [nodes, edges],+ )++ const paramNodes = sortedNodes.filter((n) =>+ (n.type === 'imageNode' || n.type === 'textNode' || n.type === 'meshNode' || n.type === 'extensionNode' || n.type === 'waitNode')+ && (n.data as { showInGenerate?: boolean }).showInGenerate === true,+ )++ const handleGenerate = useCallback(() => {+ if (firstPreflightIssue) {+ showToast(firstPreflightIssue)+ return+ }+ // Persist the edited params so they survive remounts and are the values actually used.+ // Drop the pending debounce — this save supersedes it.+ if (saveTimer.current) { clearTimeout(saveTimer.current); saveTimer.current = null }+ const wf: Workflow = {+ ...workflow,+ nodes: nodes as WFNode[],+ edges: edges as WFEdge[],+ updatedAt: new Date().toISOString(),+ }+ saveAndClaim(wf)+ run(wf, allExtensions)+ }, [firstPreflightIssue, nodes, edges, workflow, allExtensions, run, showToast, saveAndClaim])++ return (+ <div className="flex flex-col flex-1 min-h-0">++ {/* Params list */}+ <div className="flex-1 overflow-y-auto min-h-0 px-4 py-3 flex flex-col gap-4">+ {paramNodes.map((node, i) => {+ const isLast = i === paramNodes.length - 1+ return (+ <div key={node.id}>+ {node.type === 'imageNode' && <ImageParamRow nodeId={node.id} nodes={nodes} onPatch={patchNode} />}+ {node.type === 'textNode' && <TextParamRow nodeId={node.id} nodes={nodes} onPatch={patchNode} />}+ {node.type === 'meshNode' && <MeshParamRow nodeId={node.id} nodes={nodes} onPatch={patchNode} />}+ {node.type === 'waitNode' && <WaitParamRow nodeId={node.id} />}+ {node.type === 'extensionNode' && (() => {+ const ext = getWorkflowExtension(node.data.extensionId ?? '', allExtensions)+ return ext ? <ExtensionParamRow nodeId={node.id} ext={ext} nodes={nodes} onPatch={patchNode} /> : null+ })()}+ {!isLast && <div className="mt-4 border-t border-zinc-800/60" />}+ </div>+ )+ })}++ {paramNodes.length === 0 && (+ <div className="flex flex-col items-center gap-3 py-8 px-2">+ <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="text-zinc-700">+ <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>+ </svg>+ <p className="text-[11px] text-zinc-600 text-center leading-relaxed">+ No nodes pinned to Generate.<br/>+ Click the <span className="text-zinc-400">eye icon</span> on a node in the workflow editor.+ </p>+ <button onClick={() => navigate('workflows')}+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-zinc-700 hover:border-zinc-500 text-zinc-400 hover:text-zinc-200 text-[10px] font-medium transition-colors">+ <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>+ <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>+ </svg>+ Open workflow editor+ </button>+ </div>+ )}+ </div>++ {/* Footer */}+ <div className="shrink-0 px-4 pt-3 pb-4 border-t border-zinc-800 flex flex-col gap-2">+ {firstPreflightIssue && !isRunning && (+ <div className="flex items-center gap-2 px-2.5 py-2 rounded-lg bg-amber-950/40 border border-amber-800/50">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-amber-300 shrink-0">+ <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>+ <line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>+ </svg>+ <span className="text-[10px] text-amber-300 font-medium">{firstPreflightIssue}</span>+ </div>+ )}+ {isRunning ? (+ <button onClick={() => cancel()}+ className="w-full py-2.5 rounded-lg text-sm font-semibold bg-red-600 hover:bg-red-700 text-white transition-colors">+ Stop+ </button>+ ) : (+ <button onClick={handleGenerate} disabled={Boolean(firstPreflightIssue)}+ className="w-full py-2.5 rounded-lg text-sm font-semibold bg-accent hover:bg-accent-dark disabled:opacity-40 disabled:cursor-not-allowed text-white transition-colors">+ Generate 3D Model+ </button>+ )}+ </div>+ </div>+ )+}++// ─── Mode toggle ──────────────────────────────────────────────────────────────++function ModeToggle({ mode, onChange }: { mode: PanelMode; onChange: (m: PanelMode) => void }): JSX.Element {+ return (+ <div className="shrink-0 px-3 pt-3 pb-2.5">+ <div className="flex bg-zinc-900 border border-zinc-800 rounded-lg p-0.5">+ {(['basic', 'chat'] as PanelMode[]).map((m) => (+ <button+ key={m}+ onClick={() => onChange(m)}+ className={`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors capitalize ${+ mode === m+ ? 'bg-zinc-700 text-zinc-100 shadow-sm'+ : 'text-zinc-500 hover:text-zinc-300'+ }`}+ >+ {m}+ </button>+ ))}+ </div>+ </div>+ )+}++// ─── Main panel ───────────────────────────────────────────────────────────────++export default function WorkflowPanel() {+ const { workflows, load, activeId } = useWorkflowsStore()+ const { modelExtensions, processExtensions } = useExtensionsStore()+ const loadExtensions = useExtensionsStore((s) => s.loadExtensions)+ const { navigate } = useNavStore()+ const [selectedId, setSelectedId] = useState<string | null>(activeId)+ const [mode, setMode] = useState<PanelMode>('basic')++ const allExtensions = useMemo(+ () => buildAllWorkflowExtensions(modelExtensions, processExtensions),+ [modelExtensions, processExtensions],+ )++ // eslint-disable-next-line react-hooks/exhaustive-deps -- load once on mount+ useEffect(() => { load(); loadExtensions() }, [])++ // Sync when navigated here from the workflow editor (activeId set externally)+ useEffect(() => {+ if (activeId) setSelectedId(activeId)+ }, [activeId])++ useEffect(() => {+ if (!selectedId && workflows.length > 0) setSelectedId(workflows[0].id)+ // eslint-disable-next-line react-hooks/exhaustive-deps -- default selection reacts to workflows list only+ }, [workflows])++ const workflow = workflows.find((w) => w.id === selectedId) ?? null++ return (+ <div className="flex flex-col flex-1 min-h-0">++ {/* Mode toggle */}+ <ModeToggle mode={mode} onChange={setMode} />++ {mode === 'chat' ? (+ <>+ <div className="shrink-0 h-px bg-zinc-800" />+ <ChatPanel />+ </>+ ) : (+ <>+ {/* Header */}+ <div className="shrink-0 px-4 pt-2.5 pb-3 border-b border-zinc-800 flex flex-col gap-3">+ <h2 className="text-xs font-semibold uppercase tracking-widest text-zinc-500">Workflow</h2>+ <div className="flex items-center gap-2">+ <div className="flex-1 min-w-0">+ <WorkflowDropdown workflows={workflows} value={selectedId} onChange={setSelectedId} />+ </div>+ {selectedId && (+ <button+ onClick={() => { useWorkflowsStore.getState().setActive(selectedId!); navigate('workflows') }}+ title="Edit workflow"+ className="shrink-0 p-1.5 rounded-lg border border-zinc-700 bg-zinc-800/60 text-zinc-400+ hover:text-zinc-100 hover:bg-zinc-700 hover:border-zinc-600 transition-colors"+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>+ <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>+ </svg>+ </button>+ )}+ </div>+ </div>++ {/* Canvas or empty state */}+ {workflow ? (+ <ReactFlowProvider>+ <EmbeddedCanvas+ key={workflow.id}+ workflow={workflow}+ allExtensions={allExtensions}+ />+ </ReactFlowProvider>+ ) : (+ <div className="flex-1 flex items-center justify-center px-6">+ <p className="text-xs text-zinc-600 text-center leading-relaxed">+ No workflows yet.<br/>Create one in the Workflows tab.+ </p>+ </div>+ )}+ </>+ )}+ </div>+ )+}diff --git a/apps/forge-desktop/src/areas/generate/models.ts b/apps/forge-desktop/src/areas/generate/models.tsnew file mode 100644index 000000000..c7e704a07--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/models.ts@@ -0,0 +1,3 @@+export type ViewMode = 'solid' | 'wireframe' | 'normals' | 'matcap' | 'uv'++export type CatalogModel = { id: string; name: string }diff --git a/apps/forge-desktop/src/areas/generate/orcaSlicerLink.test.ts b/apps/forge-desktop/src/areas/generate/orcaSlicerLink.test.tsnew file mode 100644index 000000000..514618eb2--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/orcaSlicerLink.test.ts@@ -0,0 +1,82 @@+import assert from 'node:assert/strict'+import test from 'node:test'++import {+ SLICER_FORMAT,+ buildOrcaSlicerDeepLink,+ canOpenInOrcaSlicer,+ encodeWorkspacePathToken,+} from './orcaSlicerLink.ts'++test('builds an orcaslicer://open deeplink whose file= is a percent-encoded, query-less URL ending in model.stl', () => {+ const link = buildOrcaSlicerDeepLink('http://localhost:8765', '/workspace/Workflows/checkpoints/hero.glb')+ assert.ok(link.startsWith('orcaslicer://open?file='))+ const modelUrl = decodeURIComponent(link.slice('orcaslicer://open?file='.length))+ // OrcaSlicer derives the import format from the URL's final path segment, so+ // it must end in the real extension and carry no query string.+ assert.ok(!modelUrl.includes('?'), 'model URL must not contain a query string')+ assert.ok(modelUrl.endsWith('/model.stl'), 'model URL must end in model.stl')+ assert.equal(+ modelUrl,+ `http://localhost:8765/export/slicer/stl/${encodeWorkspacePathToken('Workflows/checkpoints/hero.glb')}/model.stl`,+ )+})++test('token round-trips a workspace path through url-safe base64 (matches the API decode)', () => {+ const path = 'Workflows/checkpoints/hero model (v2).glb'+ const token = encodeWorkspacePathToken(path)+ assert.ok(!/[+/=]/.test(token), 'token must be url-safe with no padding')+ // Decode the way the Python API does: restore padding, then urlsafe-decode.+ const padded = token + '='.repeat((4 - (token.length % 4)) % 4)+ const decoded = Buffer.from(padded.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf-8')+ assert.equal(decoded, path)+})++test('strips a trailing slash from the api origin', () => {+ const link = buildOrcaSlicerDeepLink('http://localhost:8765/', '/workspace/a.glb')+ const modelUrl = decodeURIComponent(link.slice('orcaslicer://open?file='.length))+ assert.equal(modelUrl, `http://localhost:8765/export/slicer/stl/${encodeWorkspacePathToken('a.glb')}/model.stl`)+})++test('canOpenInOrcaSlicer accepts sliceable workspace meshes and rejects splats and empty', () => {+ assert.equal(canOpenInOrcaSlicer('/workspace/Foo/hero.glb'), true)+ assert.equal(canOpenInOrcaSlicer('/workspace/Foo/part.stl'), true)+ assert.equal(canOpenInOrcaSlicer('/workspace/Foo/part.obj'), true)+ // Gaussian splats are point clouds, not printable meshes.+ assert.equal(canOpenInOrcaSlicer('/workspace/Foo/scan.ply'), false)+ assert.equal(canOpenInOrcaSlicer('/workspace/Foo/scan.splat'), false)+ // A format the slicer route cannot convert.+ assert.equal(canOpenInOrcaSlicer('/workspace/Foo/rig.fbx'), false)+ assert.equal(canOpenInOrcaSlicer(undefined), false)+ assert.equal(canOpenInOrcaSlicer(''), false)+})++test('canOpenInOrcaSlicer accepts an imported mesh served from outside the workspace', () => {+ // `Import` serves user-picked files through /optimize/serve-file, never from+ // the workspace — excluding those made the action invisible for the most+ // direct "I have a model, slice it" path.+ assert.equal(canOpenInOrcaSlicer('/optimize/serve-file?path=%2Ftmp%2Fx.glb'), true)+ assert.equal(canOpenInOrcaSlicer('/optimize/serve-file?path=C%3A%5CUsers%5CMe%5Cmage.glb'), true)+ assert.equal(canOpenInOrcaSlicer('/optimize/serve-file?path=%2Ftmp%2Fscan.splat'), false)+})++test('deeplink for an imported mesh tokenises the decoded absolute path', () => {+ const absolute = String.raw`C:\Users\Me\Downloads\mage_v2.glb`+ const outputUrl = `/optimize/serve-file?path=${encodeURIComponent(absolute)}`+ const modelUrl = decodeURIComponent(+ buildOrcaSlicerDeepLink('http://localhost:8765', outputUrl).slice('orcaslicer://open?file='.length),+ )+ assert.equal(+ modelUrl,+ `http://localhost:8765/export/slicer/stl/${encodeWorkspacePathToken(absolute)}/model.stl`,+ )+ assert.ok(!modelUrl.includes('?'), 'model URL must not contain a query string')+})++test('buildOrcaSlicerDeepLink refuses an output it cannot slice', () => {+ assert.throws(() => buildOrcaSlicerDeepLink('http://localhost:8765', '/workspace/Foo/scan.splat'))+})++test('SLICER_FORMAT is a format OrcaSlicer can import', () => {+ assert.equal(SLICER_FORMAT, 'stl')+})diff --git a/apps/forge-desktop/src/areas/generate/orcaSlicerLink.ts b/apps/forge-desktop/src/areas/generate/orcaSlicerLink.tsnew file mode 100644index 000000000..d5a76c9b1--- /dev/null+++ b/apps/forge-desktop/src/areas/generate/orcaSlicerLink.ts@@ -0,0 +1,79 @@+// Builds the OrcaSlicer deeplink for a generated mesh.+//+// OrcaSlicer registers the `orcaslicer://open?file=<url>` scheme; its handler+// downloads the http(s) URL in `file=` and imports it, deriving the filename —+// and therefore the mesh format — from the URL's FINAL path segment. That means+// the served URL must be path-only and end in a real `model.<ext>` with NO+// query string, and the whole thing must be percent-encoded. OrcaSlicer cannot+// import GLB, so we point at the backend's slicer-export route which converts to+// STL on the fly.++/** Format handed to OrcaSlicer. STL is universal and OrcaSlicer auto-repairs it. */+export const SLICER_FORMAT = 'stl'++/** Prefix of an imported mesh served from outside the workspace. */+const SERVE_FILE_PREFIX = '/optimize/serve-file?path='++/**+ * Source formats the slicer route can convert. Gaussian splats (`.splat`, and+ * the `.ply` they are delivered in) are point clouds, not printable meshes.+ */+const SLICEABLE_SOURCE = /\.(glb|gltf|obj|stl)$/i++/** URL-safe base64 (no padding) of a UTF-8 string — matches the API's token decode. */+export function encodeWorkspacePathToken(workspacePath: string): string {+ const bytes = new TextEncoder().encode(workspacePath)+ let binary = ''+ for (const b of bytes) binary += String.fromCharCode(b)+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')+}++/**+ * The source path the slicer route should convert, or `undefined` when the+ * output cannot be sliced.+ *+ * Two output shapes reach the viewer: a workspace URL (generated or+ * workflow-produced meshes) and a `serve-file` URL (meshes the user imported+ * from elsewhere on disk). Both are sliceable — the API accepts the absolute+ * path of an import because it recorded that the user picked it themselves.+ */+function sliceableSourcePath(outputUrl: string | undefined): string | undefined {+ if (!outputUrl) return undefined++ if (outputUrl.startsWith('/workspace/')) {+ const workspacePath = outputUrl.slice('/workspace/'.length)+ return SLICEABLE_SOURCE.test(workspacePath) ? workspacePath : undefined+ }++ if (outputUrl.startsWith(SERVE_FILE_PREFIX)) {+ const absolutePath = decodeURIComponent(outputUrl.slice(SERVE_FILE_PREFIX.length))+ return SLICEABLE_SOURCE.test(absolutePath) ? absolutePath : undefined+ }++ return undefined+}++/**+ * Whether a generation output can be opened in OrcaSlicer: it must be a mesh in+ * a format the slicer route converts, served either from the workspace or as a+ * user-selected import.+ */+export function canOpenInOrcaSlicer(outputUrl: string | undefined): boolean {+ return sliceableSourcePath(outputUrl) !== undefined+}++/**+ * Build the `orcaslicer://open?file=...` deeplink for a generated mesh.+ *+ * @param apiUrl Modly backend origin, e.g. `http://localhost:8765`+ * @param outputUrl workspace or serve-file URL of the mesh+ * @throws if `outputUrl` is not sliceable — guard with {@link canOpenInOrcaSlicer}+ */+export function buildOrcaSlicerDeepLink(apiUrl: string, outputUrl: string): string {+ const sourcePath = sliceableSourcePath(outputUrl)+ if (!sourcePath) throw new Error(`Not sliceable: ${outputUrl}`)+ const token = encodeWorkspacePathToken(sourcePath)+ const base = apiUrl.replace(/\/+$/, '')+ const modelUrl = `${base}/export/slicer/${SLICER_FORMAT}/${token}/model.${SLICER_FORMAT}`+ return `orcaslicer://open?file=${encodeURIComponent(modelUrl)}`+}diff --git a/apps/forge-desktop/src/areas/models/ModelsPage.tsx b/apps/forge-desktop/src/areas/models/ModelsPage.tsxnew file mode 100644index 000000000..7688474c1--- /dev/null+++ b/apps/forge-desktop/src/areas/models/ModelsPage.tsx@@ -0,0 +1,824 @@+import { useEffect, useMemo, useRef, useState } from 'react'+import { createPortal } from 'react-dom'+import { useExtensionsStore } from '@shared/stores/extensionsStore'+import { useNavStore } from '@shared/stores/navStore'+import type { AnyExtension, ModelExtension, SharedWeightGroupState } from '@shared/types/electron.d'+import { deleteModelsThenUninstallExtension, formatModelName, installModelAndRefresh, installModelQueue } from './utils'+import { ExtensionCard } from './components/ExtensionCard'+import type { ExtensionNode } from './components/ExtensionCard'+import { ExtensionDrawer } from './components/ExtensionDrawer'+import { ICONS, nodeHasManagedWeights, type DownloadMap } from './components/extensionShared'++// ─── Filters & sorts ──────────────────────────────────────────────────────────++type FilterId = 'all' | 'process' | 'model' | 'official'+type SortId = 'name' | 'type'++const FILTERS: { id: FilterId; label: string }[] = [+ { id: 'all', label: 'All' },+ { id: 'process', label: 'Processors' },+ { id: 'model', label: 'Models' },+ { id: 'official', label: 'Official' },+]++const SORTS: { id: SortId; label: string }[] = [+ { id: 'name', label: 'Name (A–Z)' },+ { id: 'type', label: 'Type' },+]++// ─── Page ─────────────────────────────────────────────────────────────────────++export default function ModelsPage(): JSX.Element {+ // Extensions store+ const modelExtensions = useExtensionsStore((s) => s.modelExtensions)+ const processExtensions = useExtensionsStore((s) => s.processExtensions)+ const extLoading = useExtensionsStore((s) => s.loading)+ const installProgress = useExtensionsStore((s) => s.installProgress)+ const installError = useExtensionsStore((s) => s.installError)+ const loadErrors = useExtensionsStore((s) => s.loadErrors)+ const loadExtensions = useExtensionsStore((s) => s.loadExtensions)+ const installFromGH = useExtensionsStore((s) => s.installFromGitHub)+ const installFromLocal = useExtensionsStore((s) => s.installFromLocal)+ const uninstallExt = useExtensionsStore((s) => s.uninstall)+ const reloadExtensions = useExtensionsStore((s) => s.reload)+ const clearInstall = useExtensionsStore((s) => s.clearInstallState)++ const allExtensions: AnyExtension[] = useMemo(+ () => [...modelExtensions, ...processExtensions],+ [modelExtensions, processExtensions],+ )++ // Model weight state (needed for node install status + uninstall cleanup)+ const [installedNodeIds, setInstalledNodeIds] = useState<string[]>([])+ const [localDataIds, setLocalDataIds] = useState<string[]>([])+ const [sharedGroupStates, setSharedGroupStates] = useState<Record<string, SharedWeightGroupState[]>>({})+ const [downloading, setDownloading] = useState<DownloadMap>({})++ // Uninstall modal state+ const [uninstallTarget, setUninstallTarget] = useState<string | null>(null)+ const [uninstallError, setUninstallError] = useState<string | null>(null)+ const [modelsToDelete, setModelsToDelete] = useState<Set<string>>(new Set())++ // Search / filter / sort / detail drawer+ const [search, setSearch] = useState('')+ const [filter, setFilter] = useState<FilterId>('all')+ const [sort, setSort] = useState<SortId>('name')+ const [sortOpen, setSortOpen] = useState(false)+ const [selectedId, setSelectedId] = useState<string | null>(null)+ const searchRef = useRef<HTMLInputElement>(null)++ // Another page asked to open an extension (e.g. a weight variant picked but not installed)+ const extensionToOpen = useNavStore((s) => s.extensionToOpen)+ const clearExtensionToOpen = useNavStore((s) => s.clearExtensionToOpen)+ useEffect(() => {+ if (!extensionToOpen) return+ setSelectedId(extensionToOpen)+ clearExtensionToOpen()+ }, [extensionToOpen, clearExtensionToOpen])++ // GitHub extension install form+ const [showGHForm, setShowGHForm] = useState(false)+ const [ghUrl, setGhUrl] = useState('')+ const [ghErr, setGhErr] = useState<string | null>(null)++ const installedRefreshRevision = useRef(0)+ const installQueues = useRef(new Set<string>())++ // ── Init ──────────────────────────────────────────────────────────────────++ // Check each model node individually via filesystem IPC — reliable regardless of API state+ async function refreshInstalledIds(exts: ModelExtension[]) {+ const revision = ++installedRefreshRevision.current+ const ids: string[] = []+ const localIds: string[] = []+ const sharedStates: Record<string, SharedWeightGroupState[]> = {}+ for (const ext of exts) {+ sharedStates[ext.id] = await window.electron.model.sharedGroups(ext.id)+ for (const node of ext.nodes) {+ if (!nodeHasManagedWeights(node)) continue+ const fullId = `${ext.id}/${node.id}`+ const [ok, hasLocalData] = await Promise.all([+ window.electron.model.isDownloaded(fullId),+ window.electron.model.hasLocalData(fullId),+ ])+ if (ok) ids.push(fullId)+ if (hasLocalData) localIds.push(fullId)+ }+ }+ if (revision !== installedRefreshRevision.current) return+ setInstalledNodeIds(ids)+ setLocalDataIds(localIds)+ setSharedGroupStates(sharedStates)+ await useExtensionsStore.getState().refreshInstalledWeightVariants()+ }++ useEffect(() => {+ loadExtensions().then(async () => {+ const exts = useExtensionsStore.getState().modelExtensions+ const active = await window.electron.model.activeDownloads()+ if (active.length > 0) {+ setDownloading((prev) => {+ const next = { ...prev }+ for (const { modelId, ...progress } of active) if (!next[modelId]) next[modelId] = progress+ return next+ })+ }+ refreshInstalledIds(exts)+ })+ window.electron.model.onWeightsChanged(() => {+ void refreshInstalledIds(useExtensionsStore.getState().modelExtensions)+ })+ window.electron.model.onProgress(({ modelId: id, variantId, percent, file, fileIndex, totalFiles, status, bytesDownloaded, totalBytes, stalledSeconds, paused, cancelled }) => {+ if (cancelled) {+ setDownloading((prev) => { const n = { ...prev }; delete n[id]; return n })+ return+ }+ setDownloading((prev) => {+ const current = prev[id]+ return {+ ...prev,+ [id]: {+ percent: paused ? (current?.percent ?? percent) : percent,+ file: file ?? current?.file,+ fileIndex: fileIndex ?? current?.fileIndex,+ totalFiles: totalFiles ?? current?.totalFiles,+ status,+ bytesDownloaded: bytesDownloaded ?? current?.bytesDownloaded,+ totalBytes: totalBytes ?? current?.totalBytes,+ stalledSeconds: stalledSeconds ?? current?.stalledSeconds,+ paused,+ variantId: variantId ?? current?.variantId,+ },+ }+ })+ if (percent === 100) {+ const exts = useExtensionsStore.getState().modelExtensions+ refreshInstalledIds(exts).then(() => {+ setDownloading((prev) => { const n = { ...prev }; delete n[id]; return n })+ })+ }+ })+ return () => {+ window.electron.model.offProgress()+ window.electron.model.offWeightsChanged()+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps -- register the progress listener once on mount+ }, [])++ useEffect(() => {+ if (installError) setGhErr(installError)+ }, [installError])++ // "/" focuses the search field+ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ if (e.key !== '/') return+ const el = document.activeElement+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) return+ e.preventDefault()+ searchRef.current?.focus()+ }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ }, [])++ // ── Node install / download controls ──────────────────────────────────────++ async function handleInstallNode(node: ExtensionNode, fullId: string, variantId?: string) {+ if (!nodeHasManagedWeights(node)) return { success: true }+ setDownloading((prev) => ({ ...prev, [fullId]: { ...(prev[fullId] ?? { percent: 0 }), variantId, paused: false, status: 'Starting…' } }))+ try {+ const result = await installModelAndRefresh(+ () => window.electron.model.download(fullId, variantId),+ () => refreshInstalledIds(useExtensionsStore.getState().modelExtensions),+ )+ if (!result.success && !result.paused && !result.cancelled) {+ setGhErr(result.error ?? 'Download failed')+ }+ if (!result.paused) setDownloading((prev) => { const next = { ...prev }; delete next[fullId]; return next })+ return result+ } catch (err) {+ const error = String(err)+ setGhErr(error)+ setDownloading((prev) => { const next = { ...prev }; delete next[fullId]; return next })+ return { success: false, error }+ }+ }++ async function handleInstallAll(ext: AnyExtension) {+ if (ext.type !== 'model' || installQueues.current.has(ext.id)) return+ installQueues.current.add(ext.id)+ try {+ const nodes = new Map(ext.nodes.filter(nodeHasManagedWeights).map((node) => [`${ext.id}/${node.id}`, node]))+ await installModelQueue(+ nodes.keys(),+ (id) => window.electron.model.isDownloaded(id),+ (id) => handleInstallNode(nodes.get(id)!, id),+ )+ } finally {+ installQueues.current.delete(ext.id)+ }+ }++ async function handlePauseDownload(fullId: string) {+ setDownloading((prev) => prev[fullId] ? ({ ...prev, [fullId]: { ...prev[fullId], paused: true, status: 'Pausing…' } }) : prev)+ await window.electron.model.pauseDownload(fullId)+ }++ async function handleCancelDownload(fullId: string) {+ setDownloading((prev) => { const n = { ...prev }; delete n[fullId]; return n })+ const result = await window.electron.model.cancelDownload(fullId)+ if (!result.success) setGhErr(result.error ?? 'Could not cancel download')+ await refreshInstalledIds(useExtensionsStore.getState().modelExtensions)+ }++ async function handleUninstallNode(fullId: string) {+ await window.electron.model.delete(fullId)+ refreshInstalledIds(useExtensionsStore.getState().modelExtensions)+ }++ async function handleDeleteSharedGroup(extensionId: string, groupId: string) {+ const result = await window.electron.model.deleteSharedGroup(extensionId, groupId)+ await refreshInstalledIds(useExtensionsStore.getState().modelExtensions)+ return result+ }++ async function handleDeleteWeightVariant(fullId: string, variantId: string) {+ const result = await window.electron.model.deleteWeightVariant(fullId, variantId)+ await refreshInstalledIds(useExtensionsStore.getState().modelExtensions)+ return result+ }++ // ── GitHub extension install ───────────────────────────────────────────────++ async function handleGHInstall() {+ const url = ghUrl.trim()+ if (!url) { setGhErr('GitHub URL required'); return }+ if (!url.includes('github.com')) { setGhErr('Must be a GitHub URL'); return }+ setGhErr(null)+ clearInstall()+ const result = await installFromGH(url)+ if (result.success) {+ setShowGHForm(false)+ setGhUrl('')+ } else {+ setGhErr(result.error ?? 'Installation failed')+ }+ }++ // ── Local extension install ──────────────────────────────────────────++ async function handleLocalInstall() {+ setGhErr(null)+ clearInstall()+ const result = await installFromLocal()+ if ('cancelled' in result && result.cancelled) return // user dismissed dialog+ if (!result.success) setGhErr(result.error ?? 'Installation failed')+ }++ // ── Uninstall extension ──────────────────────────────────────────++ function openUninstallModal(extId: string) {+ const ext = allExtensions.find((e) => e.id === extId)+ if (ext?.type === 'model') {+ const localModels = ext.nodes.filter((n) => localDataIds.includes(`${extId}/${n.id}`))+ const hasSharedLocalData = (sharedGroupStates[extId] ?? []).some((group) => group.hasLocalData)+ setModelsToDelete(ext.weightGroups?.length && (localModels.length > 0 || hasSharedLocalData)+ ? new Set([`${extId}/*`])+ : new Set(localModels.map((n) => `${extId}/${n.id}`)))+ } else {+ setModelsToDelete(new Set())+ }+ setUninstallTarget(extId)+ }++ async function handleUninstallExtension(extId: string) {+ const result = await deleteModelsThenUninstallExtension(+ extId,+ modelsToDelete,+ (modelId) => modelId === `${extId}/*`+ ? window.electron.model.deleteExtensionWeights(extId)+ : window.electron.model.delete(modelId),+ uninstallExt,+ )+ if (!result.success) {+ // Keep the dialog open so the failure is visible (locked folder, etc.)+ setUninstallError(result.error ?? 'Could not delete the extension folder.')+ return+ }+ setUninstallError(null)+ setUninstallTarget(null)+ setModelsToDelete(new Set())+ setSelectedId((id) => (id === extId ? null : id))+ refreshInstalledIds(useExtensionsStore.getState().modelExtensions)+ }++ // ── Helpers ────────────────────────────────────────────────────────────────++ const isInstalling = installProgress !== null &&+ installProgress.step !== 'done' &&+ installProgress.step !== 'error'++ const isBusy = isInstalling || Object.keys(downloading).length > 0++ const counts = useMemo(() => ({+ all: allExtensions.length,+ process: allExtensions.filter((e) => e.type === 'process').length,+ model: allExtensions.filter((e) => e.type === 'model').length,+ official: allExtensions.filter((e) => e.trusted).length,+ }), [allExtensions])++ const filteredExtensions = useMemo(() => {+ const q = search.trim().toLowerCase()+ const list = allExtensions.filter((e) => {+ if (q) {+ const haystack = `${e.name} ${e.description ?? ''} ${e.author ?? ''}`.toLowerCase()+ if (!haystack.includes(q)) return false+ }+ if (filter === 'process') return e.type === 'process'+ if (filter === 'model') return e.type === 'model'+ if (filter === 'official') return e.trusted+ return true+ })+ const sorters: Record<SortId, (a: AnyExtension, b: AnyExtension) => number> = {+ name: (a, b) => a.name.localeCompare(b.name),+ type: (a, b) => a.type.localeCompare(b.type) || a.name.localeCompare(b.name),+ }+ return [...list].sort(sorters[sort])+ }, [allExtensions, search, filter, sort])++ const processList = filteredExtensions.filter((e) => e.type === 'process')+ const modelList = filteredExtensions.filter((e) => e.type === 'model')+ const grouped = filter === 'all' || filter === 'official'++ const selectedExt = selectedId ? allExtensions.find((e) => e.id === selectedId) ?? null : null++ function extLoadError(ext: AnyExtension): string | undefined {+ return loadErrors[ext.id] ??+ ext.nodes.map((n) => loadErrors[`${ext.id}/${n.id}`]).find(Boolean)+ }++ function installProgressLabel(): string {+ if (!installProgress) return ''+ switch (installProgress.step) {+ case 'downloading': return `Downloading… ${installProgress.percent ?? 0}%`+ case 'extracting': return 'Extracting…'+ case 'validating': return 'Validating…'+ case 'setting_up': return 'Setting up environment…'+ case 'done': return 'Installed!'+ default: return ''+ }+ }++ const cardHandlers = {+ installedIds: installedNodeIds,+ downloading,+ disabled: isBusy,+ onInstall: handleInstallNode,+ onInstallAll: handleInstallAll,+ onPauseDownload: handlePauseDownload,+ onCancelDownload: handleCancelDownload,+ onOpen: (ext: AnyExtension) => setSelectedId(ext.id),+ }++ // ── Render ────────────────────────────────────────────────────────────────++ return (+ <div className="relative h-full flex flex-col overflow-hidden">++ {/* ── Page head ────────────────────────────────────────────────────── */}+ <div className="flex items-start justify-between gap-6 px-7 pt-6 pb-4 shrink-0">+ <div>+ <h1 className="text-[21px] font-semibold text-zinc-100 tracking-tight">Extensions</h1>+ <p className="mt-1 text-[13px] text-zinc-500">+ <b className="font-semibold text-zinc-200">{counts.all}</b> installed+ {' · '}+ <b className="font-semibold text-zinc-200">{counts.process}</b> processors,{' '}+ <b className="font-semibold text-zinc-200">{counts.model}</b> models+ </p>+ </div>+ <div className="flex gap-2.5 shrink-0">+ <button+ onClick={() => {+ setShowGHForm((v) => !v)+ setGhErr(null)+ clearInstall()+ }}+ className="inline-flex items-center gap-2 px-3.5 py-2 rounded-[9px] text-xs font-medium border border-zinc-700/60 bg-white/[0.025] text-zinc-200 hover:bg-white/[0.06] hover:border-zinc-600 transition-colors whitespace-nowrap"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" className="opacity-85">+ <path d="M12 0C5.37 0 0 5.37 0 12c0 5.3 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61-.546-1.387-1.333-1.756-1.333-1.756-1.09-.745.083-.729.083-.729 1.205.085 1.84 1.237 1.84 1.237 1.07 1.835 2.807 1.305 3.492.997.108-.776.418-1.305.762-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.468-2.38 1.235-3.22-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.3 1.23A11.51 11.51 0 0112 5.803c1.02.005 2.047.138 3.006.404 2.29-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.91 1.235 3.22 0 4.61-2.805 5.625-5.475 5.92.43.372.823 1.102.823 2.222 0 1.606-.015 2.896-.015 3.286 0 .322.216.694.825.576C20.565 21.796 24 17.298 24 12c0-6.63-5.37-12-12-12z"/>+ </svg>+ {showGHForm ? 'Cancel' : 'Install from GitHub'}+ </button>+ <button+ onClick={handleLocalInstall}+ disabled={isInstalling}+ title="Link a local extension folder"+ className="inline-flex items-center gap-2 px-3.5 py-2 rounded-[9px] text-xs font-medium border border-zinc-700/60 bg-white/[0.025] text-zinc-200 hover:bg-white/[0.06] hover:border-zinc-600 transition-colors whitespace-nowrap disabled:opacity-40 disabled:cursor-not-allowed"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" className="opacity-85">+ <path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z" />+ </svg>+ Link local folder+ </button>+ </div>+ </div>++ {/* ── Toolbar ──────────────────────────────────────────────────────── */}+ <div className="flex items-center gap-3 px-7 pb-4 flex-wrap shrink-0">+ {/* Search */}+ <label className="flex-1 min-w-[220px] h-10 flex items-center gap-2.5 px-3.5 rounded-[10px] bg-zinc-900/70 border border-zinc-800 focus-within:border-accent/40 focus-within:bg-zinc-900 transition-colors">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" className="text-zinc-600 shrink-0">+ <circle cx="11" cy="11" r="7" /><path d="m20 20-3.2-3.2" />+ </svg>+ <input+ ref={searchRef}+ type="text"+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Search extensions, authors…"+ className="flex-1 bg-transparent text-[13px] text-zinc-200 placeholder-zinc-600 focus:outline-none"+ />+ {search ? (+ <button onClick={() => setSearch('')} className="text-zinc-600 hover:text-zinc-400 transition-colors">+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">+ <line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />+ </svg>+ </button>+ ) : (+ <kbd className="px-1.5 py-0.5 rounded-[5px] border border-zinc-700/60 font-mono text-[10.5px] text-zinc-600">/</kbd>+ )}+ </label>++ {/* Type filter */}+ <div className="flex items-center gap-0.5 p-[3px] rounded-[10px] bg-zinc-900/70 border border-zinc-800">+ {FILTERS.map((f) => (+ <button+ key={f.id}+ onClick={() => setFilter(f.id)}+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-[7px] text-xs font-medium transition-colors ${+ filter === f.id ? 'bg-zinc-800 text-zinc-100 shadow-sm' : 'text-zinc-500 hover:text-zinc-200'+ }`}+ >+ {f.label}+ <span className={`px-1.5 py-px rounded-full font-mono text-[10px] bg-white/5 ${filter === f.id ? 'text-zinc-400' : 'text-zinc-600'}`}>+ {counts[f.id]}+ </span>+ </button>+ ))}+ </div>++ {/* Sort */}+ <div className="relative">+ <button+ onClick={() => setSortOpen((o) => !o)}+ onBlur={() => setTimeout(() => setSortOpen(false), 140)}+ className="h-10 flex items-center gap-2 px-3.5 rounded-[10px] bg-zinc-900/70 border border-zinc-800 text-xs font-medium text-zinc-500 hover:text-zinc-200 hover:border-zinc-700 transition-colors"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">+ <path d="M7 5v14M7 19l-3-3M7 5l3 3M17 19V5M17 5l-3 3M17 19l3-3" />+ </svg>+ {SORTS.find((s) => s.id === sort)!.label}+ </button>+ {sortOpen && (+ <div className="absolute right-0 top-11 z-30 w-44 rounded-xl bg-zinc-900 border border-zinc-700/60 p-1 shadow-2xl shadow-black/50">+ {SORTS.map((s) => (+ <button+ key={s.id}+ onMouseDown={() => { setSort(s.id); setSortOpen(false) }}+ className={`flex items-center justify-between w-full px-2.5 py-2 rounded-lg text-xs transition-colors ${+ sort === s.id ? 'text-zinc-100' : 'text-zinc-500 hover:text-zinc-200 hover:bg-white/5'+ }`}+ >+ {s.label}+ {sort === s.id && (+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className="text-accent-light">+ <path d="m5 12 4.5 4.5L19 7" />+ </svg>+ )}+ </button>+ ))}+ </div>+ )}+ </div>++ {/* Reload */}+ <button+ onClick={reloadExtensions}+ disabled={extLoading}+ title="Reload extensions"+ className="h-10 w-10 grid place-items-center rounded-[10px] bg-zinc-900/70 border border-zinc-800 text-zinc-500 hover:text-zinc-200 hover:border-zinc-700 transition-colors disabled:opacity-40"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"+ className={extLoading ? 'animate-spin' : ''}>+ <polyline points="23 4 23 10 17 10" />+ <path d="M20.49 15a9 9 0 11-2.12-9.36L23 10" />+ </svg>+ </button>+ </div>++ {/* ── GitHub install form ──────────────────────────────────────────── */}+ {showGHForm && (+ <div className="px-7 pb-4 shrink-0 animate-fade-in">+ <div className="flex flex-col gap-3 p-4 rounded-xl bg-zinc-900/80 border border-zinc-800">+ <div className="flex gap-2">+ <input+ type="text"+ value={ghUrl}+ onChange={(e) => { setGhUrl(e.target.value); setGhErr(null); clearInstall() }}+ onKeyDown={(e) => e.key === 'Enter' && !isInstalling && handleGHInstall()}+ placeholder="https://github.com/owner/repo"+ autoFocus+ disabled={isInstalling}+ className="flex-1 px-3 py-2 text-xs rounded-lg bg-zinc-800 border border-zinc-700/60 text-zinc-200 placeholder:text-zinc-600 focus:outline-none focus:border-zinc-500 transition-colors disabled:opacity-50"+ />+ <button+ onClick={handleGHInstall}+ disabled={!ghUrl.trim() || isInstalling}+ className="flex items-center gap-1.5 px-3.5 py-2 rounded-lg bg-accent hover:bg-accent-dark text-white text-xs font-semibold disabled:opacity-40 disabled:cursor-not-allowed transition-colors"+ >+ {isInstalling ? (+ <div className="w-3 h-3 rounded-full border-2 border-white/40 border-t-white animate-spin" />+ ) : (+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">+ <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/>+ <polyline points="7 10 12 15 17 10"/>+ <line x1="12" y1="15" x2="12" y2="3"/>+ </svg>+ )}+ {isInstalling ? installProgressLabel() : 'Install'}+ </button>+ </div>++ {isInstalling && installProgress?.step === 'downloading' && (+ <div className="h-1 rounded-full bg-zinc-800 overflow-hidden">+ <div+ className="h-full rounded-full bg-accent transition-all duration-300"+ style={{ width: `${installProgress.percent ?? 0}%` }}+ />+ </div>+ )}++ {isInstalling && installProgress?.step === 'setting_up' && (+ <div className="flex flex-col gap-2 px-3 py-2.5 rounded-lg bg-zinc-800/60 border border-zinc-700/40">+ <div className="flex items-center justify-between gap-3">+ <div className="flex items-center gap-2 min-w-0">+ <div className="w-3 h-3 rounded-full border-2 border-accent/40 border-t-accent animate-spin shrink-0" />+ <span className="text-[10px] text-zinc-400 truncate">+ {installProgress.message ?? 'Setting up environment…'}+ </span>+ </div>+ <span className="text-[9px] text-zinc-600 shrink-0">May take a few minutes</span>+ </div>+ {/* Indeterminate progress bar */}+ <div className="h-0.5 rounded-full bg-zinc-700 overflow-hidden">+ <div className="h-full w-1/3 rounded-full bg-accent animate-[slide_1.5s_ease-in-out_infinite]" />+ </div>+ </div>+ )}++ {installProgress?.step === 'done' && (+ <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-emerald-950/30 border border-emerald-800/30">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" className="text-emerald-400 shrink-0">+ <polyline points="20 6 9 17 4 12"/>+ </svg>+ <p className="text-[11px] text-emerald-400">Extension installed successfully!</p>+ </div>+ )}++ {ghErr && (+ <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-red-950/30 border border-red-800/30">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-red-400 shrink-0">+ <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>+ </svg>+ <p className="text-[11px] text-red-400">{ghErr}</p>+ </div>+ )}++ <p className="text-[10px] text-zinc-600">+ The repo must contain a <span className="font-mono text-zinc-500">manifest.json</span> and a <span className="font-mono text-zinc-500">generator.py</span> at its root.+ </p>+ </div>+ </div>+ )}++ {/* ── Extensions list ──────────────────────────────────────────────── */}+ <div className="flex-1 min-h-0 overflow-y-auto px-7 pb-9">+ {allExtensions.length === 0 && !extLoading ? (+ <div className="flex flex-col items-center justify-center gap-3 py-16 rounded-2xl border border-dashed border-zinc-800 bg-zinc-900/20">+ <div className="w-8 h-8 text-zinc-700">{ICONS.cube}</div>+ <div className="text-center">+ <p className="text-sm font-medium text-zinc-400">No extensions installed</p>+ <p className="text-xs text-zinc-600 mt-1">+ Install from GitHub or drop into the Modly extensions directory.+ </p>+ </div>+ </div>+ ) : extLoading ? (+ <div className="flex items-center justify-center py-16">+ <div className="w-5 h-5 rounded-full border-2 border-zinc-700 border-t-zinc-400 animate-spin" />+ </div>+ ) : filteredExtensions.length === 0 ? (+ <div className="flex flex-col items-center justify-center gap-2 py-16">+ <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="text-zinc-700">+ <circle cx="11" cy="11" r="8" /><path d="m21 21-4.35-4.35" />+ </svg>+ <p className="text-sm text-zinc-500">No extension matches <span className="text-zinc-300">“{search}”</span></p>+ </div>+ ) : grouped ? (+ <>+ {processList.length > 0 && (+ <section className="mt-1">+ <div className="flex items-center gap-2.5 mb-3.5 px-0.5">+ <span className="w-6 h-6 p-[5px] rounded-[7px] grid place-items-center bg-emerald-500/10 text-emerald-400 ring-1 ring-inset ring-emerald-500/25">+ {ICONS.cube}+ </span>+ <h2 className="text-[13px] font-semibold text-zinc-200 tracking-wide">Processors</h2>+ <span className="font-mono text-[11px] text-zinc-600">{processList.length}</span>+ <span className="flex-1 h-px bg-zinc-800" />+ </div>+ <div className="grid gap-3.5" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(296px, 1fr))' }}>+ {processList.map((ext) => (+ <ExtensionCard key={ext.id} ext={ext} loadError={extLoadError(ext)} {...cardHandlers} />+ ))}+ </div>+ </section>+ )}+ {modelList.length > 0 && (+ <section className={processList.length > 0 ? 'mt-8' : 'mt-1'}>+ <div className="flex items-center gap-2.5 mb-3.5 px-0.5">+ <span className="w-6 h-6 p-[5px] rounded-[7px] grid place-items-center bg-accent/15 text-accent-light ring-1 ring-inset ring-accent/30">+ {ICONS.spark}+ </span>+ <h2 className="text-[13px] font-semibold text-zinc-200 tracking-wide">Models</h2>+ <span className="font-mono text-[11px] text-zinc-600">{modelList.length}</span>+ <span className="flex-1 h-px bg-zinc-800" />+ </div>+ <div className="grid gap-3.5" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(296px, 1fr))' }}>+ {modelList.map((ext) => (+ <ExtensionCard key={ext.id} ext={ext} loadError={extLoadError(ext)} {...cardHandlers} />+ ))}+ </div>+ </section>+ )}+ </>+ ) : (+ <div className="grid gap-3.5 mt-1" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(296px, 1fr))' }}>+ {filteredExtensions.map((ext) => (+ <ExtensionCard key={ext.id} ext={ext} loadError={extLoadError(ext)} {...cardHandlers} />+ ))}+ </div>+ )}+ </div>++ {/* ── Detail drawer ────────────────────────────────────────────────── */}+ {selectedExt && (+ <ExtensionDrawer+ ext={selectedExt}+ installedIds={installedNodeIds}+ localDataIds={localDataIds}+ downloading={downloading}+ sharedGroups={sharedGroupStates[selectedExt.id] ?? []}+ loadError={extLoadError(selectedExt)}+ disabled={isBusy}+ onInstall={handleInstallNode}+ onInstallAll={handleInstallAll}+ onPauseDownload={handlePauseDownload}+ onCancelDownload={handleCancelDownload}+ onUninstallNode={handleUninstallNode}+ onDeleteSharedGroup={handleDeleteSharedGroup}+ onDeleteWeightVariant={handleDeleteWeightVariant}+ onUninstall={(extId) => openUninstallModal(extId)}+ onRepaired={() => reloadExtensions()}+ onSynced={() => reloadExtensions()}+ onClose={() => setSelectedId(null)}+ />+ )}++ {/* ── Confirm uninstall extension ──────────────────────────────────── */}+ {uninstallTarget && (() => {+ const ext = allExtensions.find((e) => e.id === uninstallTarget)+ const installedModels = ext?.type === 'model'+ ? ext.nodes.filter((n) => localDataIds.includes(`${uninstallTarget}/${n.id}`))+ : []+ const sharedExtensionHasData = ext?.type === 'model' && Boolean(ext.weightGroups?.length) && (+ installedModels.length > 0+ || (sharedGroupStates[uninstallTarget] ?? []).some((group) => group.hasLocalData)+ )++ return createPortal(+ <div+ className="fixed inset-0 z-[9999] flex items-center justify-center"+ onMouseDown={(e) => { if (e.target === e.currentTarget) { setUninstallTarget(null); setModelsToDelete(new Set()); setUninstallError(null) } }}+ >+ <div className="absolute inset-0 bg-zinc-950/70 backdrop-blur-sm animate-fade-in" />+ <div className="relative w-96 rounded-2xl bg-zinc-900 border border-accent/20 shadow-2xl shadow-accent/5 overflow-hidden animate-slide-up-center">+ <div className="px-5 py-5 flex flex-col gap-4">+ <div className="flex items-start gap-3">+ <div className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0 bg-accent/10 border border-accent/20">+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-accent-light">+ <polyline points="3 6 5 6 21 6" />+ <path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6" />+ <path d="M10 11v6M14 11v6" />+ <path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2" />+ </svg>+ </div>+ <div className="flex flex-col gap-1 pt-0.5">+ <h2 className="text-base font-semibold text-zinc-100 leading-tight">+ Uninstall “{ext?.name ?? uninstallTarget}”?+ </h2>+ <p className="text-xs text-zinc-500 leading-relaxed">+ The extension folder will be permanently deleted.+ </p>+ </div>+ </div>++ {sharedExtensionHasData ? (+ <div className="flex flex-col gap-2 px-1">+ <p className="text-[11px] font-medium text-zinc-400">+ Also delete downloaded model weights:+ </p>+ <label className="flex items-center gap-2.5 px-3 py-2 rounded-lg bg-zinc-800/60 border border-zinc-700/40 cursor-pointer hover:border-zinc-600/60 transition-colors">+ <input+ type="checkbox"+ checked={modelsToDelete.has(`${uninstallTarget}/*`)}+ onChange={() => {+ setModelsToDelete((prev) => {+ const next = new Set(prev)+ const id = `${uninstallTarget}/*`+ if (next.has(id)) next.delete(id)+ else next.add(id)+ return next+ })+ }}+ className="accent-accent w-3.5 h-3.5 rounded"+ />+ <span className="text-xs text-zinc-200">All shared and node-specific weights</span>+ </label>+ </div>+ ) : installedModels.length > 0 && (+ <div className="flex flex-col gap-2 px-1">+ <p className="text-[11px] font-medium text-zinc-400">+ Also delete downloaded model weights:+ </p>+ {installedModels.map((v) => {+ const id = `${uninstallTarget}/${v.id}`+ const checked = modelsToDelete.has(id)+ return (+ <label+ key={v.id}+ className="flex items-center gap-2.5 px-3 py-2 rounded-lg bg-zinc-800/60 border border-zinc-700/40 cursor-pointer hover:border-zinc-600/60 transition-colors"+ >+ <input+ type="checkbox"+ checked={checked}+ onChange={() => {+ setModelsToDelete((prev) => {+ const next = new Set(prev)+ if (checked) next.delete(id)+ else next.add(id)+ return next+ })+ }}+ className="accent-accent w-3.5 h-3.5 rounded"+ />+ <span className="text-xs text-zinc-200">{formatModelName(id)}</span>+ </label>+ )+ })}+ </div>+ )}++ {uninstallError && (+ <div className="flex items-start gap-2 px-3 py-2.5 rounded-lg bg-red-950/30 border border-red-800/30">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-red-400 shrink-0 mt-0.5">+ <circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />+ </svg>+ <p className="text-[11px] text-red-400 break-words">{uninstallError}</p>+ </div>+ )}++ <div className="flex gap-2.5">+ <button+ onClick={() => { setUninstallTarget(null); setModelsToDelete(new Set()); setUninstallError(null) }}+ className="flex-1 py-2.5 rounded-xl bg-zinc-800 hover:bg-zinc-700/80 text-zinc-400 hover:text-zinc-200 text-sm font-medium transition-colors border border-zinc-700/50"+ >+ Cancel+ </button>+ <button+ onClick={() => handleUninstallExtension(uninstallTarget)}+ className="flex-1 py-2.5 rounded-xl bg-accent hover:bg-accent-dark text-white text-sm font-semibold transition-colors shadow-lg shadow-accent/20"+ >+ Uninstall+ </button>+ </div>+ </div>+ </div>+ </div>,+ document.body+ )+ })()}+ </div>+ )+}diff --git a/apps/forge-desktop/src/areas/models/components/DownloadingCard.tsx b/apps/forge-desktop/src/areas/models/components/DownloadingCard.tsxnew file mode 100644index 000000000..698a8e5d0--- /dev/null+++ b/apps/forge-desktop/src/areas/models/components/DownloadingCard.tsx@@ -0,0 +1,32 @@+import { formatModelName } from '../utils'++interface Props {+ modelId: string+ percent: number+}++export function DownloadingCard({ modelId, percent }: Props): JSX.Element {+ return (+ <div className="flex items-center gap-4 px-4 py-3 rounded-xl bg-zinc-900/60 border border-zinc-800">+ <div className="w-8 h-8 rounded-lg bg-accent/15 flex items-center justify-center shrink-0">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-accent-light animate-bounce">+ <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4" />+ <polyline points="7 10 12 15 17 10" />+ <line x1="12" y1="15" x2="12" y2="3" />+ </svg>+ </div>+ <div className="flex-1 min-w-0">+ <div className="flex items-center justify-between mb-1.5">+ <p className="text-xs font-medium text-zinc-200 truncate">{formatModelName(modelId)}</p>+ <span className="text-[10px] text-zinc-500 tabular-nums ml-2 shrink-0">{percent}%</span>+ </div>+ <div className="h-1 bg-zinc-800 rounded-full overflow-hidden">+ <div+ className="h-full bg-accent rounded-full transition-all duration-500"+ style={{ width: `${percent}%` }}+ />+ </div>+ </div>+ </div>+ )+}diff --git a/apps/forge-desktop/src/areas/models/components/ExtensionCard.tsx b/apps/forge-desktop/src/areas/models/components/ExtensionCard.tsxnew file mode 100644index 000000000..5ceb729a8--- /dev/null+++ b/apps/forge-desktop/src/areas/models/components/ExtensionCard.tsx@@ -0,0 +1,170 @@+import type { AnyExtension } from '@shared/types/electron.d'+import type { ExtensionNode } from '@shared/types/electron.d'+export type { AnyExtension as Extension }+export type { ExtensionNode } from '@shared/types/electron.d'++import {+ DownloadMap,+ ICONS,+ IOBadge,+ NodeInstallControl,+ StatusBadge,+ TypePill,+ extInstallSummary,+ getNodeState,+} from './extensionShared'++interface Props {+ ext: AnyExtension+ installedIds: string[]+ downloading: DownloadMap+ loadError?: string+ disabled?: boolean+ onInstall: (node: ExtensionNode, fullId: string) => void+ onInstallAll: (ext: AnyExtension) => void+ onPauseDownload: (fullId: string) => void+ onCancelDownload: (fullId: string) => void+ onOpen: (ext: AnyExtension) => void+}++export function ExtensionCard({+ ext, installedIds, downloading, loadError, disabled,+ onInstall, onInstallAll, onPauseDownload, onCancelDownload, onOpen,+}: Props): JSX.Element {+ const isModel = ext.type === 'model'+ const isLocal = typeof ext.source === 'string' && ext.source.startsWith('local://')+ const { total, done, installing, hasAvailable } = extInstallSummary(ext, installedIds, downloading)++ const handleOpen = (e: React.MouseEvent) => {+ if ((e.target as HTMLElement).closest('button')) return+ onOpen(ext)+ }+ const handleKey = (e: React.KeyboardEvent) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault()+ onOpen(ext)+ }+ }++ let status: JSX.Element+ if (loadError) {+ status = <StatusBadge tone="amber">Load error</StatusBadge>+ } else if (installing) {+ status = <StatusBadge tone="violet">Installing…</StatusBadge>+ } else if (!isModel) {+ status = <StatusBadge tone="green">Ready</StatusBadge>+ } else if (done === total) {+ status = <StatusBadge tone="green">All nodes ready</StatusBadge>+ } else {+ status = <StatusBadge tone="amber">{done}/{total} nodes installed</StatusBadge>+ }++ return (+ <div+ role="button"+ tabIndex={0}+ onClick={handleOpen}+ onKeyDown={handleKey}+ aria-label={`${ext.name} — open details`}+ className="relative flex flex-col min-h-[218px] p-4 rounded-2xl bg-zinc-900/60 border border-zinc-800 overflow-hidden cursor-pointer transition-all duration-150 hover:bg-zinc-900 hover:border-zinc-700 hover:-translate-y-0.5 hover:shadow-[0_14px_30px_-14px_rgba(0,0,0,0.7)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"+ >+ {/* Header */}+ <div className="flex items-start gap-3">+ <div className={`shrink-0 w-10 h-10 p-2.5 rounded-[11px] bg-zinc-800 ring-1 ring-inset ring-zinc-700/50 ${isModel ? 'text-accent-light' : 'text-emerald-400'}`}>+ {isModel ? ICONS.spark : ICONS.cube}+ </div>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="text-sm font-semibold text-zinc-100 truncate">{ext.name}</span>+ <TypePill type={ext.type} />+ </div>+ <div className="flex items-center gap-1.5 mt-1 text-[11px] text-zinc-600 flex-wrap">+ {ext.version && <span className="font-mono text-zinc-500">v{ext.version}</span>}+ {ext.version && ext.author && <span className="opacity-50">·</span>}+ {ext.author && <span>{ext.author}</span>}+ {ext.trusted && (+ <>+ <span className="opacity-50">·</span>+ <span className="inline-flex items-center gap-1 text-zinc-500">+ <span className="w-[11px] h-[11px] text-accent-light">{ICONS.shield}</span>+ Official+ </span>+ </>+ )}+ {isLocal && (+ <>+ <span className="opacity-50">·</span>+ <span className="text-orange-400/80">Local</span>+ </>+ )}+ </div>+ </div>+ </div>++ {/* Description */}+ <p className="mt-3 text-xs leading-5 text-zinc-500 line-clamp-2 min-h-[2.5rem]">+ {ext.description?.trim() || '—'}+ </p>++ {/* Load error */}+ {loadError && (+ <div className="mt-2 px-2.5 py-1.5 rounded-lg bg-red-950/30 border border-red-800/30">+ <p className="text-[10px] text-red-400 line-clamp-1 break-all">{loadError}</p>+ </div>+ )}++ {/* Nodes */}+ {ext.nodes.length > 0 && (+ <div className="mt-3 flex flex-col gap-1.5">+ {ext.nodes.map((node) => {+ const fullId = `${ext.id}/${node.id}`+ const state = getNodeState(ext.id, node, installedIds, downloading)+ return (+ <div+ key={node.id}+ className="flex items-center justify-between gap-2.5 px-2.5 py-1.5 rounded-lg bg-white/[0.02] border border-zinc-800"+ >+ <div className="flex flex-col gap-1 min-w-0 items-start">+ <span className="text-xs font-medium text-zinc-200 truncate max-w-full">+ {node.name}+ {isModel && node.weightVariants && (+ <span className="font-normal text-zinc-500"> · {node.weightVariants.options.length} variants</span>+ )}+ </span>+ <IOBadge node={node} />+ </div>+ {isModel && (+ <div className="shrink-0">+ <NodeInstallControl+ state={state}+ disabled={disabled}+ onInstall={() => onInstall(node, fullId)}+ onPause={() => onPauseDownload(fullId)}+ onResume={() => onInstall(node, fullId)}+ onCancel={() => onCancelDownload(fullId)}+ />+ </div>+ )}+ </div>+ )+ })}+ </div>+ )}++ {/* Footer */}+ <div className="mt-auto pt-3 flex items-center justify-between gap-2">+ {status}+ {isModel && hasAvailable && !installing && (+ <button+ onClick={(e) => { e.stopPropagation(); onInstallAll(ext) }}+ disabled={disabled}+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold bg-accent/15 text-accent-light ring-1 ring-inset ring-accent/30 hover:bg-accent hover:text-white transition-colors disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-accent/15 disabled:hover:text-accent-light"+ >+ <span className="w-3 h-3">{ICONS.download}</span>+ Install all+ </button>+ )}+ </div>+ </div>+ )+}diff --git a/apps/forge-desktop/src/areas/models/components/ExtensionDrawer.tsx b/apps/forge-desktop/src/areas/models/components/ExtensionDrawer.tsxnew file mode 100644index 000000000..949d7de3e--- /dev/null+++ b/apps/forge-desktop/src/areas/models/components/ExtensionDrawer.tsx@@ -0,0 +1,491 @@+import { useEffect, useState } from 'react'+import type { AnyExtension, ExtensionNode, SharedWeightGroupState } from '@shared/types/electron.d'+import { useExtensionsStore } from '@shared/stores/extensionsStore'+import { useNavStore } from '@shared/stores/navStore'+import {+ DownloadMap,+ ICONS,+ IOBadge,+ NodeInstallControl,+ NodeUiState,+ TypePill,+ extInstallSummary,+ formatBytes,+ getNodeState,+} from './extensionShared'+import { finishExtensionRepair, isExtensionRepairable } from '../utils'++interface Props {+ ext: AnyExtension+ installedIds: string[]+ localDataIds: string[]+ downloading: DownloadMap+ sharedGroups: SharedWeightGroupState[]+ loadError?: string+ disabled?: boolean+ onInstall: (node: ExtensionNode, fullId: string, variantId?: string) => void+ onInstallAll: (ext: AnyExtension) => void+ onPauseDownload: (fullId: string) => void+ onCancelDownload: (fullId: string) => void+ onUninstallNode: (fullId: string) => void+ onDeleteSharedGroup: (extensionId: string, groupId: string) => Promise<{ success: boolean; error?: string }>+ onDeleteWeightVariant: (fullId: string, variantId: string) => Promise<{ success: boolean; error?: string }>+ onUninstall: (extId: string) => void+ onRepaired: () => void | Promise<void>+ onSynced: () => void+ onClose: () => void+}++export function ExtensionDrawer({+ ext, installedIds, localDataIds, downloading, sharedGroups, loadError, disabled,+ onInstall, onInstallAll, onPauseDownload, onCancelDownload,+ onUninstallNode, onDeleteSharedGroup, onDeleteWeightVariant, onUninstall, onRepaired, onSynced, onClose,+}: Props): JSX.Element {+ const navigate = useNavStore((s) => s.navigate)+ const installedWeightVariants = useExtensionsStore((s) => s.installedWeightVariants)+ const [repairing, setRepairing] = useState(false)+ const [repairError, setRepairError] = useState<string | null>(null)+ const [syncing, setSyncing] = useState(false)+ const [syncError, setSyncError] = useState<string | null>(null)+ const [variantError, setVariantError] = useState<string | null>(null)++ const isModel = ext.type === 'model'+ // Built-ins are corrupted-flagged too (builtin-sync repairs them on restart),+ // but they can't be deleted — show the banner without the delete action.+ const isCorrupted = !!ext.corrupted+ const canRepair = isExtensionRepairable(ext)+ const corruptedMsg =+ ext.manifestError === 'invalid'+ ? 'This extension folder has a manifest that cannot be parsed. Fix the JSON syntax in its manifest.json, or delete the folder and reinstall.'+ : ext.manifestError === 'incomplete'+ ? 'Setup or runtime registration was interrupted. Click Repair to rebuild and validate the extension, or delete it and reinstall.'+ : 'This extension folder is incomplete (its manifest is missing) — usually the leftover of an interrupted install. Delete the folder, then install the extension again.'+ const isLocal = typeof ext.source === 'string' && ext.source.startsWith('local://')+ const localPath = isLocal ? ext.source!.replace('local://', '') : null+ const { total, done, installing, hasAvailable } = extInstallSummary(ext, installedIds, downloading)++ useEffect(() => {+ const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ }, [onClose])++ async function handleRepair() {+ setRepairing(true)+ setRepairError(null)+ const result = await window.electron.extensions.repair(ext.id)+ setRepairError(await finishExtensionRepair(result, onRepaired))+ setRepairing(false)+ }++ async function handleSync() {+ setSyncing(true)+ setSyncError(null)+ try {+ const result = await window.electron.extensions.reload()+ if (!result.success) setSyncError(result.error ?? 'Sync failed')+ else onSynced()+ } catch (e) {+ setSyncError(String(e))+ } finally {+ setSyncing(false)+ }+ }++ async function handleDeleteSharedGroup(group: SharedWeightGroupState) {+ const dependents = group.dependentModelIds.join(', ')+ if (!window.confirm(+ `Remove shared weights "${group.id}"? The following nodes will become unavailable: ${dependents}`,+ )) return+ setSyncError(null)+ const result = await onDeleteSharedGroup(ext.id, group.id)+ if (!result.success) setSyncError(result.error ?? 'Could not remove shared model weights.')+ }+++ async function handleDeleteWeightVariant(fullId: string, variantId: string) {+ setVariantError(null)+ const result = await onDeleteWeightVariant(fullId, variantId)+ if (!result.success) setVariantError(result.error ?? 'Could not remove these weights')+ }++ const error = variantError ?? syncError ?? repairError ?? loadError++ return (+ <>+ {/* Overlay */}+ <div+ className="absolute inset-0 z-40 bg-zinc-950/50 backdrop-blur-[2px] animate-fade-in"+ onClick={onClose}+ />++ {/* Drawer */}+ <aside+ role="dialog"+ aria-modal="true"+ aria-label={ext.name}+ className="absolute inset-y-0 right-0 z-50 w-[418px] max-w-[92%] flex flex-col bg-zinc-950 border-l border-zinc-700/60 shadow-[-30px_0_60px_rgba(0,0,0,0.5)] animate-drawer-in"+ >+ {/* Head */}+ <div className="relative px-5 pt-5 pb-4 border-b border-zinc-800/80 shrink-0">+ <button+ onClick={onClose}+ title="Close"+ className="absolute right-4 top-4 w-[30px] h-[30px] grid place-items-center rounded-lg text-zinc-600 hover:text-zinc-200 hover:bg-zinc-800 transition-colors"+ >+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round">+ <path d="M5 5l14 14M19 5 5 19" />+ </svg>+ </button>+ <div className="flex items-center gap-3.5 pr-8">+ <div className={`shrink-0 w-[52px] h-[52px] p-3 rounded-[13px] bg-zinc-800 ring-1 ring-inset ring-zinc-700/50 ${isModel ? 'text-accent-light' : 'text-emerald-400'}`}>+ {isModel ? ICONS.spark : ICONS.cube}+ </div>+ <div className="min-w-0">+ <h3 className="text-lg font-semibold text-zinc-100 leading-tight truncate">{ext.name}</h3>+ <div className="flex items-center gap-2 mt-1.5 text-xs text-zinc-600 flex-wrap">+ <TypePill type={ext.type} />+ {ext.version && <span className="font-mono text-zinc-500">v{ext.version}</span>}+ {ext.trusted && (+ <span className="inline-flex items-center gap-1 text-accent-light">+ <span className="w-[11px] h-[11px]">{ICONS.shield}</span>+ Official+ </span>+ )}+ {isLocal && <span className="text-orange-400/80">Local</span>}+ </div>+ </div>+ </div>+ </div>++ {/* Body */}+ <div className="flex-1 min-h-0 overflow-y-auto px-5 py-5">+ {/* Corrupted install */}+ {isCorrupted && (+ <div className="mb-5 flex items-start gap-2.5 px-3 py-3 rounded-lg bg-amber-950/30 border border-amber-800/40">+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-amber-400 shrink-0 mt-0.5">+ <path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />+ <line x1="12" y1="9" x2="12" y2="13" /><line x1="12" y1="17" x2="12.01" y2="17" />+ </svg>+ <div className="min-w-0">+ <p className="text-[12px] font-semibold text-amber-400">Corrupted installation</p>+ <p className="text-[11px] leading-5 text-amber-400/80 mt-1">+ {ext.builtin ? 'This built-in extension folder is damaged — restart Modly to let it re-sync.' : corruptedMsg}+ </p>+ </div>+ </div>+ )}++ {/* Error */}+ {error && (+ <div className="mb-5 flex items-start gap-2 px-3 py-2.5 rounded-lg bg-red-950/30 border border-red-800/30">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-red-400 shrink-0 mt-0.5">+ <circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />+ </svg>+ <p className="text-[11px] text-red-400 break-all">{error}</p>+ </div>+ )}++ {/* Description */}+ <div className="mb-6">+ <div className="text-[10.5px] font-semibold uppercase tracking-[0.07em] text-zinc-600 mb-2.5">Description</div>+ <p className="text-[13px] leading-6 text-zinc-400">{ext.description?.trim() || 'No description provided.'}</p>+ </div>++ {/* Nodes */}+ {isModel && sharedGroups.length > 0 && (+ <div className="mb-6">+ <div className="text-[10.5px] font-semibold uppercase tracking-[0.07em] text-zinc-600 mb-2.5">+ Shared weights+ </div>+ <div className="flex flex-col gap-2">+ {sharedGroups.map((group) => (+ <div key={group.id} className="px-3.5 py-3 rounded-[10px] bg-zinc-900/70 border border-zinc-800">+ <div className="flex items-center justify-between gap-3">+ <div className="min-w-0">+ <div className="text-[13px] font-semibold text-zinc-200 truncate">{group.id}</div>+ <div className="text-[11px] text-zinc-600 mt-0.5 truncate">+ Shared by {group.dependentModelIds.length} node{group.dependentModelIds.length === 1 ? '' : 's'}+ </div>+ </div>+ <div className="flex items-center gap-2 shrink-0">+ <span className={`text-[11px] font-semibold ${group.downloaded ? 'text-emerald-400' : 'text-amber-400'}`}>+ {group.downloaded ? 'Shared · Installed' : 'Shared · Required'}+ </span>+ {group.hasLocalData && (+ <button+ onClick={() => handleDeleteSharedGroup(group)}+ disabled={disabled || isCorrupted}+ title="Remove shared weights from all dependent nodes"+ className="p-1 rounded-md text-zinc-600 hover:text-red-400 hover:bg-red-950/40 transition-colors disabled:opacity-30 disabled:cursor-not-allowed"+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">+ <polyline points="3 6 5 6 21 6" />+ <path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6" />+ </svg>+ </button>+ )}+ </div>+ </div>+ </div>+ ))}+ </div>+ </div>+ )}++ <div className="mb-6">+ <div className="text-[10.5px] font-semibold uppercase tracking-[0.07em] text-zinc-600 mb-2.5">+ {isModel ? `Nodes · ${done}/${total} installed` : `Actions · ${total}`}+ </div>+ <div className="flex flex-col gap-2">+ {ext.nodes.map((node) => {+ const fullId = `${ext.id}/${node.id}`+ const state = getNodeState(ext.id, node, installedIds, downloading)+ const dl = state.kind === 'downloading' ? state.dl : null+ const variants = isModel ? node.weightVariants : undefined+ // A download started without a variant (Install all) fetches the default one.+ const dlVariantId = dl && variants ? (dl.variantId ?? variants.default) : undefined+ const dlVariant = variants?.options.find((option) => option.id === dlVariantId)+ const installedLabels = variants?.options+ .filter((option) => installedWeightVariants[fullId]?.includes(option.id))+ .map((option) => option.label) ?? []+ const sub =+ state.kind === 'ready' ? 'Available on the node graph'+ : state.kind === 'installed' ? (installedLabels.length > 0 ? `${installedLabels.join(', ')} installed` : 'Installed')+ : state.kind === 'available' ? 'Not installed'+ : dl?.paused ? 'Download paused'+ : `Downloading${dlVariant ? ` ${dlVariant.label}` : ''}… ${dl?.percent ?? 0}%`++ return (+ <div key={node.id} className="px-3.5 py-3 rounded-[10px] bg-zinc-900/70 border border-zinc-800">+ <div className="flex items-center justify-between gap-3">+ <div className="min-w-0">+ <div className="text-[13px] font-semibold text-zinc-200 truncate">{node.name}</div>+ <div className="text-[11px] text-zinc-600 mt-0.5 truncate">{sub}</div>+ </div>+ <div className="flex flex-col items-end gap-2 shrink-0">+ <IOBadge node={node} />+ {isModel && (+ <div className="flex items-center gap-1.5">+ {!variants && (+ <NodeInstallControl+ state={state}+ disabled={disabled || isCorrupted}+ onInstall={() => onInstall(node, fullId)}+ onPause={() => onPauseDownload(fullId)}+ onResume={() => onInstall(node, fullId)}+ onCancel={() => onCancelDownload(fullId)}+ />+ )}+ {localDataIds.includes(fullId) && state.kind !== 'downloading' && (+ <button+ onClick={() => onUninstallNode(fullId)}+ disabled={disabled || isCorrupted}+ title={state.kind === 'installed' ? 'Remove model weights' : 'Remove partial model data'}+ className="p-1 rounded-md text-zinc-600 hover:text-red-400 hover:bg-red-950/40 transition-colors disabled:opacity-30 disabled:cursor-not-allowed"+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">+ <polyline points="3 6 5 6 21 6" />+ <path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6" />+ </svg>+ </button>+ )}+ </div>+ )}+ </div>+ </div>++ {/* Weight variants — each one installs and deletes on its own */}+ {variants && (+ <div className="mt-3 pt-2.5 border-t border-zinc-800/80 flex flex-col gap-1.5">+ {variants.options.map((option) => {+ const installed = installedWeightVariants[fullId]?.includes(option.id) ?? false+ const variantDl = dlVariantId === option.id ? dl : null+ const variantState: NodeUiState = variantDl+ ? { kind: 'downloading', dl: variantDl }+ : installed ? { kind: 'installed' } : { kind: 'available' }+ return (+ <div key={option.id} className="flex items-center justify-between gap-3 min-h-[24px]">+ <div className="min-w-0 flex items-baseline gap-2">+ <span className="font-mono text-[11.5px] text-zinc-300 truncate">{option.label}</span>+ {option.sizeGb !== undefined && (+ <span className="text-[10px] text-zinc-600 shrink-0">{option.sizeGb} GB</span>+ )}+ {option.vramGb !== undefined && (+ <span className="text-[10px] text-zinc-600 shrink-0">~{option.vramGb} GB VRAM</span>+ )}+ {option.id === variants.default && (+ <span className="text-[10px] text-zinc-600 shrink-0">default</span>+ )}+ </div>+ <div className="flex items-center gap-1.5 shrink-0">+ <NodeInstallControl+ state={variantState}+ // One download per node: another variant waits for this one.+ disabled={disabled || isCorrupted || Boolean(dl && !variantDl)}+ onInstall={() => onInstall(node, fullId, option.id)}+ onPause={() => onPauseDownload(fullId)}+ onResume={() => onInstall(node, fullId, option.id)}+ onCancel={() => onCancelDownload(fullId)}+ />+ {installed && !dl && (+ <button+ onClick={() => handleDeleteWeightVariant(fullId, option.id)}+ disabled={disabled || isCorrupted}+ title={`Remove ${option.label} weights`}+ className="p-1 rounded-md text-zinc-600 hover:text-red-400 hover:bg-red-950/40 transition-colors disabled:opacity-30 disabled:cursor-not-allowed"+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">+ <polyline points="3 6 5 6 21 6" />+ <path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6" />+ </svg>+ </button>+ )}+ </div>+ </div>+ )+ })}+ </div>+ )}++ {/* Download detail */}+ {dl && (+ <div className="mt-3 flex flex-col gap-1">+ <div className="flex items-center justify-between gap-2 text-[10px] text-zinc-600">+ <span className="truncate">{dl.paused ? 'Paused' : (dl.file ?? dl.status ?? 'Downloading…')}</span>+ <span className="font-mono shrink-0">+ {dl.fileIndex && dl.totalFiles ? `${dl.fileIndex}/${dl.totalFiles} · ${dl.percent}%` : `${dl.percent}%`}+ </span>+ </div>+ <div className="flex items-center justify-between gap-2 text-[10px]">+ <span className="text-zinc-600 truncate">+ {dl.totalBytes && dl.totalBytes > 0+ ? `${formatBytes(dl.bytesDownloaded)} / ${formatBytes(dl.totalBytes)}`+ : formatBytes(dl.bytesDownloaded)}+ </span>+ {(dl.stalledSeconds ?? 0) >= 30 && (+ <span className="text-amber-400 shrink-0">No progress {dl.stalledSeconds}s</span>+ )}+ </div>+ </div>+ )}+ </div>+ )+ })}+ </div>+ </div>++ {/* Details */}+ <div>+ <div className="text-[10.5px] font-semibold uppercase tracking-[0.07em] text-zinc-600 mb-2.5">Details</div>+ <dl className="grid grid-cols-[1fr_auto] gap-x-3.5 gap-y-2.5 text-xs">+ <dt className="text-zinc-600">Author</dt>+ <dd className="text-zinc-400 text-right font-mono text-[11.5px]">{ext.author ?? '—'}</dd>+ <dt className="text-zinc-600">Version</dt>+ <dd className="text-zinc-400 text-right font-mono text-[11.5px]">{ext.version ? `v${ext.version}` : '—'}</dd>+ <dt className="text-zinc-600">Source</dt>+ <dd className="text-zinc-400 text-right font-mono text-[11.5px] max-w-[230px] truncate" style={{ direction: 'rtl' }} title={localPath ?? ext.source ?? undefined}>+ {localPath ?? ext.source ?? (ext.builtin ? 'Built-in' : '—')}+ </dd>+ <dt className="text-zinc-600">Nodes</dt>+ <dd className="text-zinc-400 text-right font-mono text-[11.5px]">{ext.nodes.length}</dd>+ </dl>+ </div>+ </div>++ {/* Footer */}+ <div className="px-5 py-4 border-t border-zinc-800/80 flex items-center gap-2.5 shrink-0">+ {isCorrupted && !ext.builtin ? (+ <button+ onClick={() => onUninstall(ext.id)}+ disabled={disabled}+ className="flex-1 inline-flex items-center justify-center gap-2 px-3.5 py-2.5 rounded-[9px] text-xs font-semibold bg-red-600/90 text-white hover:bg-red-600 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">+ <polyline points="3 6 5 6 21 6" />+ <path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6" />+ <path d="M10 11v6M14 11v6" />+ </svg>+ Delete broken folder+ </button>+ ) : isModel && hasAvailable ? (+ <button+ onClick={() => onInstallAll(ext)}+ disabled={disabled || installing}+ className="flex-1 inline-flex items-center justify-center gap-2 px-3.5 py-2.5 rounded-[9px] text-xs font-semibold bg-accent text-white hover:bg-accent-dark transition-colors disabled:opacity-40 disabled:cursor-not-allowed"+ >+ <span className="w-3.5 h-3.5">{ICONS.download}</span>+ {installing ? 'Installing…' : 'Install all nodes'}+ </button>+ ) : (+ <button+ onClick={() => { onClose(); navigate('workflows') }}+ className="flex-1 inline-flex items-center justify-center gap-2 px-3.5 py-2.5 rounded-[9px] text-xs font-semibold bg-accent text-white hover:bg-accent-dark transition-colors"+ >+ Use in workflow+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">+ <path d="M9 6l6 6-6 6" />+ </svg>+ </button>+ )}++ {canRepair && (+ <button+ onClick={handleRepair}+ disabled={repairing || disabled}+ title="Repair — re-run the extension environment setup"+ className="inline-flex items-center gap-1.5 px-3.5 py-2.5 rounded-[9px] text-xs font-medium border border-zinc-700/60 text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"+ >+ {repairing ? (+ <span className="w-3 h-3 rounded-full border-2 border-zinc-500/40 border-t-zinc-300 animate-spin" />+ ) : (+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">+ <path d="M23 4v6h-6" /><path d="M20.49 15a9 9 0 11-2.12-9.36L23 10" />+ </svg>+ )}+ {repairing ? 'Repairing…' : 'Repair'}+ </button>+ )}++ {isLocal && (+ <button+ onClick={handleSync}+ disabled={syncing || disabled}+ title="Sync — reload extension from local folder"+ className="p-2.5 rounded-[9px] border border-zinc-700/60 text-zinc-500 hover:text-orange-400 hover:bg-orange-950/30 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" className={syncing ? 'animate-spin' : ''}>+ <polyline points="23 4 23 10 17 10" />+ <path d="M20.49 15a9 9 0 11-2.12-9.36L23 10" />+ </svg>+ </button>+ )}++ {!ext.builtin && !isCorrupted && (+ <button+ onClick={() => onUninstall(ext.id)}+ disabled={disabled}+ title={isLocal ? 'Unlink local extension (removes symlink only, keeps source folder)' : 'Uninstall extension'}+ className="p-2.5 rounded-[9px] border border-zinc-700/60 text-zinc-600 hover:text-red-400 hover:border-red-800/50 hover:bg-red-950/30 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"+ >+ {isLocal ? (+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <path d="M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71" />+ <path d="M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71" />+ <line x1="2" y1="2" x2="22" y2="22" />+ </svg>+ ) : (+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">+ <polyline points="3 6 5 6 21 6" />+ <path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6" />+ <path d="M10 11v6M14 11v6" />+ <path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2" />+ </svg>+ )}+ </button>+ )}+ </div>+ </aside>+ </>+ )+}diff --git a/apps/forge-desktop/src/areas/models/components/ModelCard.tsx b/apps/forge-desktop/src/areas/models/components/ModelCard.tsxnew file mode 100644index 000000000..753b60087--- /dev/null+++ b/apps/forge-desktop/src/areas/models/components/ModelCard.tsx@@ -0,0 +1,63 @@+import { LocalModel } from '../models'+import { formatModelName } from '../utils'++interface Props {+ model: LocalModel+ onDelete: () => void+ onGenerate: () => void+ disabled?: boolean+}++export function ModelCard({ model, onDelete, onGenerate, disabled }: Props): JSX.Element {+ return (+ <div className="relative flex flex-col gap-2 px-3.5 py-4 rounded-2xl border transition-all min-h-[110px] bg-zinc-900/60 border-zinc-800 hover:border-zinc-700">+ {/* Open in explorer */}+ <button+ onClick={() => window.electron.model.showInFolder(model.id)}+ title="Show in explorer"+ className="absolute top-2.5 right-2.5 flex items-center justify-center w-6 h-6 rounded-lg text-zinc-600 hover:text-zinc-300 hover:bg-zinc-700/60 transition-all"+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z" />+ </svg>+ </button>++ {/* Name */}+ <p className="text-xs font-semibold leading-tight truncate text-zinc-200 pr-6">+ {formatModelName(model.id)}+ </p>++ {/* Size */}+ <span className="text-[11px] font-medium text-zinc-400">+ {model.size_gb > 0 ? `${model.size_gb} GB` : '—'}+ </span>++ {/* Actions */}+ <div className="flex items-center gap-1.5 mt-auto">+ <button+ onClick={onGenerate}+ title="Use this model"+ className="flex-1 flex items-center justify-center gap-1 px-2 py-1.5 rounded-lg bg-accent/20 border border-accent/25 text-accent-light hover:bg-accent/30 hover:border-accent/40 transition-all text-[10px] font-semibold"+ >+ <svg width="9" height="9" viewBox="0 0 24 24" fill="currentColor">+ <polygon points="5 3 19 12 5 21 5 3" />+ </svg>+ Generate+ </button>+ <button+ onClick={onDelete}+ disabled={disabled}+ title={disabled ? 'Cannot delete while an install is in progress' : 'Uninstall'}+ className="flex items-center justify-center w-7 h-7 rounded-lg bg-red-950/40 border border-red-900/30 text-red-500 hover:bg-red-900/50 hover:text-red-300 hover:border-red-700/50 transition-all shrink-0 disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-red-950/40 disabled:hover:text-red-500 disabled:hover:border-red-900/30"+ >+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">+ <polyline points="3 6 5 6 21 6" />+ <path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6" />+ <path d="M10 11v6M14 11v6" />+ <path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2" />+ </svg>+ </button>+ </div>+ </div>+ )+}diff --git a/apps/forge-desktop/src/areas/models/components/extensionShared.tsx b/apps/forge-desktop/src/areas/models/components/extensionShared.tsxnew file mode 100644index 000000000..dfd91b047--- /dev/null+++ b/apps/forge-desktop/src/areas/models/components/extensionShared.tsx@@ -0,0 +1,223 @@+import type { AnyExtension, ExtensionNode } from '@shared/types/electron.d'++// ─── Shared types ─────────────────────────────────────────────────────────────++export interface DownloadInfo {+ percent: number+ file?: string+ fileIndex?: number+ totalFiles?: number+ status?: string+ bytesDownloaded?: number+ totalBytes?: number+ stalledSeconds?: number+ paused?: boolean+ variantId?: string // set when the download targets one weight variant of the node+}++export type DownloadMap = Record<string, DownloadInfo>++export type NodeUiState =+ | { kind: 'ready' } // no weights required+ | { kind: 'available' } // weights not downloaded yet+ | { kind: 'downloading'; dl: DownloadInfo }+ | { kind: 'installed' }++export function nodeHasManagedWeights(node: ExtensionNode): boolean {+ return Boolean(node.hfRepo || node.hasModelSources || node.weightGroups?.length)+}++export function getNodeState(+ extId: string,+ node: ExtensionNode,+ installedIds: string[],+ downloading: DownloadMap,+): NodeUiState {+ const fullId = `${extId}/${node.id}`+ if (!nodeHasManagedWeights(node)) return { kind: 'ready' }+ const dl = downloading[fullId]+ if (dl) return { kind: 'downloading', dl }+ if (installedIds.includes(fullId)) return { kind: 'installed' }+ return { kind: 'available' }+}++export function extInstallSummary(+ ext: AnyExtension,+ installedIds: string[],+ downloading: DownloadMap,+): { total: number; done: number; installing: boolean; hasAvailable: boolean } {+ const states = ext.nodes.map((n) => getNodeState(ext.id, n, installedIds, downloading))+ return {+ total: states.length,+ done: states.filter((s) => s.kind === 'installed' || s.kind === 'ready').length,+ installing: states.some((s) => s.kind === 'downloading'),+ hasAvailable: states.some((s) => s.kind === 'available'),+ }+}++export function formatBytes(bytes?: number): string {+ if (!bytes || bytes <= 0) return '0 B'+ const units = ['B', 'KB', 'MB', 'GB']+ let value = bytes+ let idx = 0+ while (value >= 1024 && idx < units.length - 1) {+ value /= 1024+ idx += 1+ }+ return `${value >= 10 || idx === 0 ? value.toFixed(0) : value.toFixed(1)} ${units[idx]}`+}++// ─── Small visual bits ────────────────────────────────────────────────────────++export function TypePill({ type }: { type: 'model' | 'process' }): JSX.Element {+ return type === 'process' ? (+ <span className="shrink-0 px-1.5 py-0.5 rounded-[5px] text-[10px] font-semibold uppercase tracking-wider bg-emerald-500/10 text-emerald-400 ring-1 ring-inset ring-emerald-500/25">+ Process+ </span>+ ) : (+ <span className="shrink-0 px-1.5 py-0.5 rounded-[5px] text-[10px] font-semibold uppercase tracking-wider bg-accent/15 text-accent-light ring-1 ring-inset ring-accent/30">+ Model+ </span>+ )+}++export function IOBadge({ node }: { node: ExtensionNode }): JSX.Element {+ const inputs = node.inputs?.length ? node.inputs : [node.input]+ return (+ <span className="flex items-center gap-1 font-mono text-[10px] text-zinc-600 shrink-0">+ {inputs.map((inp, i) => (+ <span key={i} className="px-1.5 py-0.5 rounded-[5px] bg-white/5 text-zinc-400">{inp}</span>+ ))}+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" className="text-zinc-600 shrink-0">+ <path d="M5 12h13M13 6l6 6-6 6" />+ </svg>+ <span className="px-1.5 py-0.5 rounded-[5px] bg-white/5 text-zinc-400">{node.output}</span>+ </span>+ )+}++const LED_TONES = {+ green: 'bg-emerald-400 shadow-[0_0_0_3px_rgba(52,211,153,0.12)]',+ amber: 'bg-amber-400 shadow-[0_0_0_3px_rgba(251,191,36,0.12)]',+ violet: 'bg-accent-light shadow-[0_0_0_3px_rgba(139,92,246,0.16)] animate-pulse',+} as const++const TEXT_TONES = {+ green: 'text-emerald-400',+ amber: 'text-amber-400',+ violet: 'text-accent-light',+} as const++export function StatusBadge({ tone, children }: { tone: keyof typeof LED_TONES; children: React.ReactNode }): JSX.Element {+ return (+ <span className={`inline-flex items-center gap-2 text-[11.5px] font-medium ${TEXT_TONES[tone]}`}>+ <span className={`w-[7px] h-[7px] rounded-full ${LED_TONES[tone]}`} />+ {children}+ </span>+ )+}++export const ICONS = {+ cube: (+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" className="w-full h-full">+ <path d="M12 2 3 7v10l9 5 9-5V7l-9-5Z" />+ <path d="m3 7 9 5 9-5M12 12v10" />+ </svg>+ ),+ spark: (+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className="w-full h-full">+ <path d="M12 3v18M3 12h18M6 6l12 12M18 6 6 18" />+ </svg>+ ),+ shield: (+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-full h-full">+ <path d="M12 3 5 6v5c0 4 3 6.5 7 8 4-1.5 7-4 7-8V6l-7-3Z" />+ <path d="m9.3 11.5 1.8 1.8 3.6-3.6" />+ </svg>+ ),+ download: (+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-full h-full">+ <path d="M12 3v12M7 11l5 5 5-5M5 20h14" />+ </svg>+ ),+ check: (+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className="w-full h-full">+ <path d="m5 12 4.5 4.5L19 7" />+ </svg>+ ),+}++// ─── Per-node install control (shared between card and drawer) ────────────────++interface NodeControlProps {+ state: NodeUiState+ disabled?: boolean+ onInstall: () => void+ onPause: () => void+ onResume: () => void+ onCancel: () => void+}++export function NodeInstallControl({ state, disabled, onInstall, onPause, onResume, onCancel }: NodeControlProps): JSX.Element | null {+ if (state.kind === 'ready') return null++ if (state.kind === 'installed') {+ return (+ <span className="inline-flex items-center gap-1.5 text-[11px] font-semibold text-emerald-400">+ <span className="w-3 h-3">{ICONS.check}</span>+ Installed+ </span>+ )+ }++ if (state.kind === 'downloading') {+ const { dl } = state+ const paused = dl.paused ?? false+ return (+ <span className="flex items-center gap-1.5">+ <span className="flex flex-col items-end gap-1">+ <span className="block w-[84px] h-1 rounded-full bg-zinc-800 overflow-hidden">+ <span+ className={`block h-full rounded-full transition-all duration-300 ${paused ? 'bg-zinc-500' : 'bg-gradient-to-r from-accent to-accent-light'}`}+ style={{ width: `${dl.percent}%` }}+ />+ </span>+ <span className={`font-mono text-[10px] ${paused ? 'text-zinc-500' : 'text-accent-light'}`}>+ {paused ? 'Paused' : `${dl.percent}%`}+ </span>+ </span>+ <button+ onClick={(e) => { e.stopPropagation(); paused ? onResume() : onPause() }}+ title={paused ? 'Resume download' : 'Pause download'}+ className="p-1 rounded-md text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800 transition-colors"+ >+ {paused ? (+ <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3" /></svg>+ ) : (+ <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="4" width="4" height="16" rx="1" /><rect x="14" y="4" width="4" height="16" rx="1" /></svg>+ )}+ </button>+ <button+ onClick={(e) => { e.stopPropagation(); onCancel() }}+ title="Cancel download"+ className="p-1 rounded-md text-zinc-500 hover:text-red-400 hover:bg-red-950/40 transition-colors"+ >+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">+ <line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />+ </svg>+ </button>+ </span>+ )+ }++ return (+ <button+ onClick={(e) => { e.stopPropagation(); onInstall() }}+ disabled={disabled}+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-[7px] text-[11px] font-semibold bg-accent/15 text-accent-light ring-1 ring-inset ring-accent/30 hover:bg-accent hover:text-white transition-colors disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-accent/15 disabled:hover:text-accent-light"+ >+ <span className="w-3 h-3">{ICONS.download}</span>+ Install+ </button>+ )+}diff --git a/apps/forge-desktop/src/areas/models/models.ts b/apps/forge-desktop/src/areas/models/models.tsnew file mode 100644index 000000000..af779b7c1--- /dev/null+++ b/apps/forge-desktop/src/areas/models/models.ts@@ -0,0 +1,5 @@+export interface LocalModel {+ id: string+ name: string+ size_gb: number+}diff --git a/apps/forge-desktop/src/areas/models/utils.test.mjs b/apps/forge-desktop/src/areas/models/utils.test.mjsnew file mode 100644index 000000000..531cfe92c--- /dev/null+++ b/apps/forge-desktop/src/areas/models/utils.test.mjs@@ -0,0 +1,152 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-modelutils-test-')), 'utils.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('src/areas/models/utils.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++const {+ deleteModelsThenUninstallExtension,+ finishExtensionRepair,+ formatModelName,+ isExtensionRepairable,+} = loadModule()++test('formatModelName turns a hyphenated id into a Title-cased label', () => {+ assert.equal(formatModelName('trellis'), 'Trellis')+ assert.equal(formatModelName('stable-fast-3d'), 'Stable Fast 3d')+ assert.equal(formatModelName('hunyuan-3d-2'), 'Hunyuan 3d 2')+})++test('formatModelName only capitalizes word-initial chars (digits left as-is)', () => {+ // \b\w upper-cases the first char of each space-separated word; the "d" after+ // a digit is mid-word and stays lower-case.+ assert.equal(formatModelName('a-b-c'), 'A B C')+ assert.equal(formatModelName(''), '')+})++test('only model extensions with a usable manifest expose Repair', () => {+ const model = {+ type: 'model',+ id: 'pixal3d',+ name: 'Pixal3D',+ trusted: false,+ builtin: false,+ nodes: [],+ }++ assert.equal(isExtensionRepairable(model), true)+ assert.equal(isExtensionRepairable({+ ...model,+ corrupted: true,+ manifestError: 'incomplete',+ }), true)+ assert.equal(isExtensionRepairable({+ ...model,+ corrupted: true,+ manifestError: 'invalid',+ }), false)+ assert.equal(isExtensionRepairable({+ ...model,+ builtin: true,+ corrupted: true,+ manifestError: 'incomplete',+ }), false)+ assert.equal(isExtensionRepairable({+ ...model,+ type: 'process',+ entry: 'processor.js',+ }), false)+})++test('Repair completion refreshes extension state even when setup fails', async () => {+ let refreshCount = 0+ const error = await finishExtensionRepair(+ { success: false, error: 'setup failed' },+ async () => {+ refreshCount += 1+ },+ )++ assert.equal(refreshCount, 1)+ assert.equal(error, 'setup failed')+})++test('failed selected-weight deletion aborts extension uninstall and preserves its error', async () => {+ const deleteCalls = []+ let uninstallCalls = 0++ const result = await deleteModelsThenUninstallExtension(+ 'pixal3d',+ new Set([+ 'pixal3d/generate',+ 'pixal3d/refine',+ 'pixal3d/export',+ ]),+ async (modelId) => {+ deleteCalls.push(modelId)+ return modelId === 'pixal3d/refine'+ ? { success: false, error: 'Model weights are locked.' }+ : { success: true }+ },+ async () => {+ uninstallCalls += 1+ return { success: true }+ },+ )++ assert.deepEqual(deleteCalls, ['pixal3d/generate', 'pixal3d/refine'])+ assert.equal(uninstallCalls, 0)+ assert.deepEqual(result, { success: false, error: 'Model weights are locked.' })+})++for (const result of [{ success: false, paused: true }, { success: false, cancelled: true }, { success: false, error: 'failed' }]) {+ test(`install queue stops after ${JSON.stringify(result)} without reactivating a shared sibling`, async () => {+ const { installModelQueue } = loadModule()+ const installed = []+ const actual = await installModelQueue(['a', 'b'], async () => false, async (id) => {+ installed.push(id)+ return result+ })+ assert.deepEqual(installed, ['a'])+ assert.deepEqual(actual, result)+ })+}++test('install queue rechecks readiness so completed shared siblings are not downloaded twice', async () => {+ const { installModelQueue } = loadModule()+ const ready = new Set(), calls = []+ await installModelQueue(['a', 'b'], async (id) => ready.has(id), async (id) => {+ calls.push(id)+ ready.add('a'); ready.add('b')+ return { success: true }+ })+ assert.deepEqual(calls, ['a'])+})++test('partial success is refreshed on failure, pause, cancel and rejected IPC', async () => {+ const { installModelAndRefresh } = loadModule()+ for (const result of [{ success: false, error: 'adapter' }, { success: false, paused: true }, { success: false, cancelled: true }]) {+ let refreshed = false+ await installModelAndRefresh(async () => result, async () => { refreshed = true })+ assert.equal(refreshed, true)+ }+ let refreshed = false+ await assert.rejects(installModelAndRefresh(async () => { throw new Error('IPC') }, async () => { refreshed = true }), /IPC/)+ assert.equal(refreshed, true)+})diff --git a/apps/forge-desktop/src/areas/models/utils.ts b/apps/forge-desktop/src/areas/models/utils.tsnew file mode 100644index 000000000..33c3cf4d9--- /dev/null+++ b/apps/forge-desktop/src/areas/models/utils.ts@@ -0,0 +1,79 @@+import type { AnyExtension } from '@shared/types/electron.d'++export function formatModelName(id: string): string {+ return id+ .replace(/-/g, ' ')+ .replace(/\b\w/g, (c) => c.toUpperCase())+}++export function isExtensionRepairable(extension: AnyExtension): boolean {+ if (extension.type !== 'model') return false+ if (!extension.corrupted) return true+ return !extension.builtin && extension.manifestError === 'incomplete'+}++export async function finishExtensionRepair(+ result: { success: boolean; error?: string },+ refreshExtensions: () => void | Promise<void>,+): Promise<string | null> {+ // Quarantine begins before setup, so even a failed Repair changes which+ // extensions may appear in renderer/workflow state.+ await refreshExtensions()+ return result.success ? null : (result.error ?? 'Repair failed')+}++interface ActionResult {+ success: boolean+ error?: string+}++export async function deleteModelsThenUninstallExtension(+ extensionId: string,+ modelIds: Iterable<string>,+ deleteModel: (modelId: string) => Promise<ActionResult>,+ uninstallExtension: (extensionId: string) => Promise<ActionResult>,+): Promise<ActionResult> {+ for (const modelId of modelIds) {+ const result = await deleteModel(modelId)+ if (!result.success) {+ return {+ success: false,+ error: result.error ?? 'Could not delete selected model weights.',+ }+ }+ }++ return uninstallExtension(extensionId)+}++export interface ModelInstallResult {+ success: boolean+ error?: string+ paused?: boolean+ cancelled?: boolean+}++export async function installModelAndRefresh(+ install: () => Promise<ModelInstallResult>,+ refresh: () => Promise<void>,+): Promise<ModelInstallResult> {+ try {+ return await install()+ } finally {+ // A failed private source can leave a completed base usable by siblings.+ await refresh()+ }+}++export async function installModelQueue(+ modelIds: Iterable<string>,+ isReady: (id: string) => Promise<boolean>,+ install: (id: string) => Promise<ModelInstallResult>,+): Promise<ModelInstallResult> {+ for (const id of modelIds) {+ if (await isReady(id)) continue+ const result = await install(id)+ if (!result.success) return result+ }+ return { success: true }+}diff --git a/apps/forge-desktop/src/areas/settings/SettingsPage.tsx b/apps/forge-desktop/src/areas/settings/SettingsPage.tsxnew file mode 100644index 000000000..d81999404--- /dev/null+++ b/apps/forge-desktop/src/areas/settings/SettingsPage.tsx@@ -0,0 +1,136 @@+import { useState } from 'react'+import { StorageSection } from './components/StorageSection'+import { AboutSection } from './components/AboutSection'+import { LogsSection } from './components/LogsSection'+import { IntegrationsSection } from './components/IntegrationsSection'+import { AgentSection } from './components/AgentSection'+import { ApplicationSection } from './components/ApplicationSection'+import { AccessibilitySection } from './components/AccessibilitySection'++type Section = 'application' | 'storage' | 'integrations' | 'accessibility' | 'agent' | 'logs' | 'about'++const SECTIONS: { id: Section; label: string; icon: JSX.Element }[] = [+ {+ id: 'application',+ label: 'Application',+ icon: (+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">+ <circle cx="12" cy="12" r="3" />+ <path d="M19.07 4.93a10 10 0 0 1 0 14.14M4.93 4.93a10 10 0 0 0 0 14.14" />+ <path d="M15.54 8.46a5 5 0 0 1 0 7.07M8.46 8.46a5 5 0 0 0 0 7.07" />+ </svg>+ )+ },+ {+ id: 'storage',+ label: 'Storage',+ icon: (+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">+ <ellipse cx="12" cy="5" rx="9" ry="3" />+ <path d="M3 5v14c0 1.66 4.03 3 9 3s9-1.34 9-3V5" />+ <line x1="3" y1="12" x2="21" y2="12" />+ </svg>+ )+ },+ {+ id: 'integrations',+ label: 'Integrations',+ icon: (+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">+ <rect x="2" y="7" width="20" height="14" rx="2" ry="2"/>+ <path d="M16 21V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v16"/>+ </svg>+ )+ },+ {+ id: 'accessibility',+ label: 'Accessibility',+ icon: (+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">+ <circle cx="12" cy="4" r="2" />+ <path d="M19 9l-7 1-7-1" />+ <path d="M12 10v6" />+ <path d="M9 22l3-6 3 6" />+ </svg>+ )+ },+ {+ id: 'agent',+ label: 'Agent',+ icon: (+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">+ <path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96-.44 2.5 2.5 0 0 1-2.96-3.08 3 3 0 0 1-.34-5.58 2.5 2.5 0 0 1 1.32-4.24 2.5 2.5 0 0 1 1.98-3A2.5 2.5 0 0 1 9.5 2Z"/>+ <path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96-.44 2.5 2.5 0 0 0 2.96-3.08 3 3 0 0 0 .34-5.58 2.5 2.5 0 0 0-1.32-4.24 2.5 2.5 0 0 0-1.98-3A2.5 2.5 0 0 0 14.5 2Z"/>+ </svg>+ )+ },+ {+ id: 'logs',+ label: 'Logs',+ icon: (+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">+ <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />+ <polyline points="14 2 14 8 20 8" />+ <line x1="16" y1="13" x2="8" y2="13" />+ <line x1="16" y1="17" x2="8" y2="17" />+ <polyline points="10 9 9 9 8 9" />+ </svg>+ )+ },+ {+ id: 'about',+ label: 'About',+ icon: (+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">+ <circle cx="12" cy="12" r="10" />+ <line x1="12" y1="8" x2="12" y2="12" />+ <line x1="12" y1="16" x2="12.01" y2="16" />+ </svg>+ )+ }+]++// ─── Page shell ───────────────────────────────────────────────────────────────++export default function SettingsPage(): JSX.Element {+ const [section, setSection] = useState<Section>('application')++ return (+ <div className="flex h-full">++ {/* Left nav */}+ <nav className="w-52 shrink-0 border-r border-zinc-800 bg-surface-400 py-5 px-3 flex flex-col gap-0.5">+ <p className="text-[10px] font-semibold text-zinc-600 uppercase tracking-wider px-3 mb-3">Settings</p>+ {SECTIONS.map((s) => (+ <button+ key={s.id}+ onClick={() => setSection(s.id)}+ className={`+ flex items-center gap-2.5 px-3 py-2.5 rounded-lg text-[13px] text-left transition-colors+ ${section === s.id+ ? 'bg-accent/15 text-accent-light'+ : 'text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800/60'}+ `}+ >+ <span className={section === s.id ? 'text-accent-light' : 'text-zinc-600'}>{s.icon}</span>+ {s.label}+ </button>+ ))}+ </nav>++ {/* Content */}+ <div className="flex-1 overflow-y-auto bg-surface-400">+ <div className="p-8">+ {section === 'application' && <ApplicationSection />}+ {section === 'storage' && <StorageSection />}+ {section === 'integrations' && <IntegrationsSection />}+ {section === 'accessibility' && <AccessibilitySection />}+ {section === 'agent' && <AgentSection />}+ {section === 'logs' && <LogsSection />}+ {section === 'about' && <AboutSection />}+ </div>+ </div>++ </div>+ )+}diff --git a/apps/forge-desktop/src/areas/settings/components/AboutSection.tsx b/apps/forge-desktop/src/areas/settings/components/AboutSection.tsxnew file mode 100644index 000000000..6ecbda131--- /dev/null+++ b/apps/forge-desktop/src/areas/settings/components/AboutSection.tsx@@ -0,0 +1,39 @@+import { useEffect, useState } from 'react'+import { Section, Card, Row, LinkButton } from '@shared/ui'++export function AboutSection(): JSX.Element {+ const [version, setVersion] = useState<string>('')++ useEffect(() => {+ window.electron.app.info().then(({ version }) => setVersion(version))+ }, [])++ return (+ <Section title="About" subtitle="Application information and useful resources.">+ <div className="grid grid-cols-2 gap-4">++ <Card>+ <Row label="Modly" description="Local 3D mesh generation app.">+ <span className="text-xs font-mono text-zinc-400">{version ? `v${version}` : '—'}</span>+ </Row>+ <Row label="Documentation" description="Guides and API reference.">+ <LinkButton label="Open" href="https://modly3d.app" />+ </Row>+ <Row label="GitHub" description="Source code and issues.">+ <LinkButton label="Open" href="https://github.com/lightningpixel/modly" />+ </Row>+ </Card>++ <Card>+ <Row label="Discord" description="Community support.">+ <LinkButton label="Join" href="https://discord.gg/FjzjRgweVk" />+ </Row>+ <Row label="Open-source licenses" description="Third-party licenses used in this app.">+ <LinkButton label="View" href="https://github.com/lightningpixel/modly/blob/main/LICENSE" />+ </Row>+ </Card>++ </div>+ </Section>+ )+}diff --git a/apps/forge-desktop/src/areas/settings/components/AccessibilitySection.tsx b/apps/forge-desktop/src/areas/settings/components/AccessibilitySection.tsxnew file mode 100644index 000000000..423e63356--- /dev/null+++ b/apps/forge-desktop/src/areas/settings/components/AccessibilitySection.tsx@@ -0,0 +1,42 @@+import { useAppStore } from '@shared/stores/appStore'+import { Section, Card, Row, Toggle, SegmentedControl } from '@shared/ui'++export function AccessibilitySection(): JSX.Element {+ const { useAtkinsonFont, setUseAtkinsonFont, uiScale, setUiScale } = useAppStore()++ return (+ <Section title="Accessibility" subtitle="Make Modly easier to read and use.">+ <div className="grid grid-cols-2 gap-4">++ <Card title="Display Font" description="Use a more legible typeface, helpful for dyslexia and low vision.">+ <Row+ label="Atkinson Hyperlegible"+ description="Replace the default font with a typeface designed for readability."+ >+ <Toggle value={useAtkinsonFont} onChange={setUseAtkinsonFont} />+ </Row>+ </Card>++ <Card title="Interface Scale" description="Zoom the whole interface up or down.">+ <Row+ label="Scale"+ description="Applies to all text, icons, and spacing."+ >+ <SegmentedControl+ ariaLabel="Interface scale"+ value={uiScale}+ onChange={setUiScale}+ options={[+ { value: 'small', label: 'Small' },+ { value: 'medium', label: 'Medium' },+ { value: 'large', label: 'Large' },+ { value: 'very-large', label: 'Very Large' },+ ]}+ />+ </Row>+ </Card>++ </div>+ </Section>+ )+}diff --git a/apps/forge-desktop/src/areas/settings/components/AgentSection.tsx b/apps/forge-desktop/src/areas/settings/components/AgentSection.tsxnew file mode 100644index 000000000..9376ecb47--- /dev/null+++ b/apps/forge-desktop/src/areas/settings/components/AgentSection.tsx@@ -0,0 +1,478 @@+import { useState, useEffect, useCallback } from 'react'+import {+ useAgentStore, PROVIDERS,+ type ThinkingMode, type ProviderId, type ExternalConfig,+} from '@shared/stores/agentStore'+import { useAppStore } from '@shared/stores/appStore'+import { consumeSse, type SseEvent } from '@shared/services/llmDownloads'+import { SseProgressBar } from '@shared/components/ui/SseProgressBar'+import { ModelLibraryModal } from '@shared/components/ui/ModelLibraryModal'+import type { LlmModel } from '@shared/stores/llmModelsStore'+import { formatBytes } from '@shared/utils/format'+import { Section, Card, SegmentedControl } from '@shared/ui'++// ─── Helpers ──────────────────────────────────────────────────────────────────++/** A labelled block inside a Card, for controls that need the full width. */+function Block({ label, description, hint, action, children }: {+ label?: string+ description?: string+ hint?: string+ action?: React.ReactNode+ children?: React.ReactNode+}): JSX.Element {+ return (+ <div className="px-4 py-3 flex flex-col gap-2">+ {(label || action) && (+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ {label && <p className="text-xs font-medium text-zinc-300">{label}</p>}+ {description && <p className="text-[11px] text-zinc-500 mt-0.5">{description}</p>}+ </div>+ {action && <div className="shrink-0">{action}</div>}+ </div>+ )}+ {children}+ {hint && <p className="text-[11px] text-zinc-500 leading-relaxed">{hint}</p>}+ </div>+ )+}++function Badge({ tone, children }: { tone: 'accent' | 'warn' | 'muted'; children: React.ReactNode }): JSX.Element {+ const cls = tone === 'accent'+ ? 'bg-accent/15 text-accent-light border-accent/30'+ : tone === 'warn'+ ? 'bg-amber-500/10 text-amber-400 border-amber-500/30'+ : 'bg-zinc-800 text-zinc-400 border-zinc-700'+ const dot = tone === 'accent' ? 'bg-accent-light' : tone === 'warn' ? 'bg-amber-400' : null+ return (+ <span className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md border text-[10.5px] font-medium ${cls}`}>+ {dot && <span className={`w-1.5 h-1.5 rounded-full ${dot}`} />}+ {children}+ </span>+ )+}++function CopyButton({ text }: { text: string }): JSX.Element {+ const [copied, setCopied] = useState(false)+ useEffect(() => {+ if (!copied) return+ const t = setTimeout(() => setCopied(false), 1500)+ return () => clearTimeout(t)+ }, [copied])+ return (+ <button+ onClick={() => { void navigator.clipboard.writeText(text); setCopied(true) }}+ className="inline-flex items-center gap-1.5 text-[11px] text-zinc-500 hover:text-zinc-200 transition-colors"+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <rect x="9" y="9" width="13" height="13" rx="2" />+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />+ </svg>+ {copied ? 'Copied' : 'Copy'}+ </button>+ )+}++function StepTitle({ n, children }: { n: number; children: React.ReactNode }): JSX.Element {+ return (+ <p className="text-xs font-medium text-zinc-300">+ <span className="mr-2 text-accent-light">{n}</span>{children}+ </p>+ )+}++const inputCls = 'w-full bg-zinc-800 border border-zinc-700 text-zinc-200 text-xs rounded-lg px-3 py-2 focus:outline-none focus:border-accent/50'+const secondaryBtnCls = 'px-2.5 py-1 rounded-md text-[11px] font-medium bg-zinc-800 hover:bg-zinc-700 text-zinc-300 transition-colors disabled:opacity-50'+const primaryBtnCls = 'px-3 py-1.5 rounded-lg bg-accent hover:bg-accent-dark text-white text-xs font-medium transition-colors'++type McpClient = 'claude' | 'codex' | 'opencode'++const MCP_CLIENTS: { value: McpClient; label: string; path: string; config: string }[] = [+ {+ value: 'claude',+ label: 'Claude Desktop',+ path: '~/.config/claude/claude_desktop_config.json',+ config: `{\n "mcpServers": {\n "modly": {\n "command": "modly-mcp"\n }\n }\n}`,+ },+ {+ value: 'codex',+ label: 'Codex CLI',+ path: '~/.codex/config.toml',+ config: `[mcp_servers.modly]\ncommand = "modly-mcp"`,+ },+ {+ value: 'opencode',+ label: 'OpenCode',+ path: '~/.config/opencode/config.json',+ config: `{\n "$schema": "https://opencode.ai/config.json",\n "mcp": {\n "modly": {\n "type": "local",\n "command": ["modly-mcp"]\n }\n }\n}`,+ },+]++const MCP_INSTALL = 'npm install -g modly-cli-mcp'++const THINKING_OPTIONS: { value: ThinkingMode; label: string; desc: string }[] = [+ { value: 'auto', label: 'Auto', desc: 'The model decides whether to think' },+ { value: 'on', label: 'Enabled', desc: 'Forces thinking on every response' },+ { value: 'off', label: 'Disabled', desc: 'Disables thinking (faster responses)' },+]++// ─── Component ────────────────────────────────────────────────────────────────++export function AgentSection(): JSX.Element {+ const {+ provider, localModel, external, defaultThinking,+ setProvider, setExternal, setDefaultThinking,+ } = useAgentStore()+ const apiUrl = useAppStore((s) => s.apiUrl)++ // Local engine+ const [engineInstalled, setEngineInstalled] = useState<boolean | null>(null)+ const [engineInstall, setEngineInstall] = useState<SseEvent | null>(null)+ const [engineError, setEngineError] = useState<string | null>(null)+ const [models, setModels] = useState<LlmModel[]>([])+ const [showLibrary, setShowLibrary] = useState(false)+ const [maxModels, setMaxModels] = useState<string>('auto')+ const [resolvedMax, setResolvedMax] = useState<number | null>(null)+ const [vramGb, setVramGb] = useState<number | null>(null)++ // External provider drafts+ const extCfg = external[provider]+ const [keyDraft, setKeyDraft] = useState(extCfg?.apiKey ?? '')+ const [extModelDraft, setExtModelDraft] = useState(extCfg?.model ?? '')+ const [baseUrlDraft, setBaseUrlDraft] = useState(extCfg?.baseUrl ?? '')+ const [extModels, setExtModels] = useState<string[]>([])+ const [extTesting, setExtTesting] = useState(false)+ const [extResult, setExtResult] = useState<'ok' | 'error' | null>(null)++ const [mcpClient, setMcpClient] = useState<McpClient>('claude')++ const refreshLocal = useCallback(async () => {+ try {+ const [s, m, c] = await Promise.all([+ fetch(`${apiUrl}/llm/status`).then((r) => r.json()),+ fetch(`${apiUrl}/llm/models?downloaded=true`).then((r) => r.json()),+ fetch(`${apiUrl}/llm/config`).then((r) => r.json()),+ ])+ setEngineInstalled(Boolean(s.binary_installed))+ setModels(m.models ?? [])+ setMaxModels(String(c.max_models ?? 'auto'))+ setResolvedMax(c.resolved_max_models ?? null)+ setVramGb(c.vram_gb ?? null)+ } catch {+ setEngineInstalled(null)+ }+ }, [apiUrl])++ async function installEngine() {+ setEngineInstall({ percent: 0, status: 'Starting…' })+ setEngineError(null)+ try {+ await consumeSse(`${apiUrl}/llm/binary/install`, (e) => {+ if (e.error) setEngineError(e.error)+ else setEngineInstall(e)+ })+ } catch (e) {+ setEngineError(e instanceof Error ? e.message : String(e))+ } finally {+ setEngineInstall(null)+ void refreshLocal()+ }+ }++ async function changeMaxModels(value: string) {+ setMaxModels(value)+ try {+ const res = await fetch(`${apiUrl}/llm/config`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ max_models: value === 'auto' ? 'auto' : Number(value) }),+ })+ const data = await res.json()+ setResolvedMax(data.resolved_max_models ?? null)+ } catch { /* API unreachable — keep the optimistic value, refreshLocal will resync */ }+ }++ useEffect(() => { void refreshLocal() }, [refreshLocal])++ // Sync drafts when switching provider+ useEffect(() => {+ const cfg = useAgentStore.getState().external[provider]+ setKeyDraft(cfg?.apiKey ?? '')+ setExtModelDraft(cfg?.model ?? '')+ setBaseUrlDraft(cfg?.baseUrl ?? '')+ setExtModels([])+ setExtResult(null)+ }, [provider])++ function saveExternal() {+ const cfg: ExternalConfig = { apiKey: keyDraft.trim(), model: extModelDraft.trim() }+ if (provider === 'custom') cfg.baseUrl = baseUrlDraft.trim().replace(/\/$/, '')+ setExternal(provider, cfg)+ }++ async function handleTestExternal() {+ setExtTesting(true)+ setExtResult(null)+ try {+ const base = provider === 'custom' ? baseUrlDraft.trim().replace(/\/$/, '') : PROVIDERS[provider].baseUrl+ // POST, not a query string: a GET would put the API key in the uvicorn+ // access log, which ends up in runtime.log and in users' bug reports.+ const res = await fetch(`${apiUrl}/agent/external/models`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ base_url: base, api_key: keyDraft.trim() }),+ })+ const data: { models?: string[] } = await res.json()+ const found = (data.models ?? []).length > 0+ setExtModels(data.models ?? [])+ setExtResult(found ? 'ok' : 'error')+ } catch {+ setExtResult('error')+ } finally {+ setExtTesting(false)+ }+ }++ const selectedModel = models.find((m) => m.id === localModel)+ const client = MCP_CLIENTS.find((c) => c.value === mcpClient) ?? MCP_CLIENTS[0]++ return (+ <Section title="Agent" subtitle="Configure the LLM powering the chat — fully local by default.">+ <div className="grid grid-cols-1 xl:grid-cols-2 gap-4 items-start">++ {/* ── Left column ── */}+ <div className="flex flex-col gap-4 min-w-0">++ <Card title="Provider" description="Which model answers in the chat.">+ <Block label="LLM provider" hint="Local runs entirely on this machine via llama.cpp. External providers require an API key.">+ <select+ value={provider}+ onChange={(e) => setProvider(e.target.value as ProviderId)}+ className={`${inputCls} cursor-pointer`}+ >+ {(Object.keys(PROVIDERS) as ProviderId[]).map((p) => (+ <option key={p} value={p}>{PROVIDERS[p].label}</option>+ ))}+ </select>+ </Block>+ </Card>++ {provider === 'local' ? (+ <Card+ title="Local engine"+ description="llama.cpp runtime and the models it can load."+ aside={+ engineInstalled === null ? <Badge tone="muted">API unreachable</Badge>+ : engineInstalled ? <Badge tone="accent">Engine installed</Badge>+ : <Badge tone="warn">Engine missing</Badge>+ }+ >+ {engineInstalled === false && (+ <Block>+ {engineInstall ? (+ <SseProgressBar event={engineInstall} />+ ) : (+ <button onClick={() => void installEngine()} className={`self-start ${primaryBtnCls}`}>+ Install engine+ </button>+ )}+ {engineError && <p className="text-[11px] text-red-400">{engineError}</p>}+ </Block>+ )}+ {engineInstalled === null && (+ <Block>+ <button onClick={() => void refreshLocal()} className={`self-start ${secondaryBtnCls}`}>Retry</button>+ </Block>+ )}++ <Block+ label="Models"+ description="GGUF weights available to the agent."+ action={<button onClick={() => setShowLibrary(true)} className={secondaryBtnCls}>Browse…</button>}+ >+ {selectedModel ? (+ <div className="flex items-center gap-3 px-3 py-2 rounded-lg bg-surface-500 border border-zinc-800">+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="text-zinc-500 shrink-0">+ <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />+ <polyline points="3.27 6.96 12 12.01 20.73 6.96" /><line x1="12" y1="22.08" x2="12" y2="12" />+ </svg>+ <div className="min-w-0 flex-1 flex items-baseline gap-2">+ <span className="text-xs font-medium text-zinc-200 truncate">{selectedModel.name}</span>+ <span className="text-[10px] text-zinc-500 font-mono truncate">+ {[+ selectedModel.size_bytes ? formatBytes(selectedModel.size_bytes) : null,+ selectedModel.quant,+ selectedModel.vram_estimate_mb ? `~${(selectedModel.vram_estimate_mb / 1000).toFixed(1)} GB VRAM` : null,+ ].filter(Boolean).join(' · ')}+ </span>+ </div>+ <Badge tone="accent">In use</Badge>+ </div>+ ) : (+ <p className="px-3 py-2 rounded-lg bg-surface-500 border border-zinc-800 text-[11px] text-zinc-500">+ {models.length === 0+ ? 'No model yet — open Browse… to add or download one.'+ : 'No model selected — open Browse… and select one.'}+ </p>+ )}+ </Block>++ <Block+ label="Simultaneous models"+ hint="How many local models may stay loaded at once (one llama-server process each). Auto sizes it from your GPU's VRAM — on 8 GB cards keep 1 so 3D generation always has room."+ >+ <select+ value={maxModels}+ onChange={(e) => void changeMaxModels(e.target.value)}+ className={`${inputCls} cursor-pointer`}+ >+ <option value="auto">+ Auto{resolvedMax != null ? ` — ${resolvedMax} model${resolvedMax > 1 ? 's' : ''}${vramGb != null ? ` (${vramGb} GB VRAM)` : ''}` : ''}+ </option>+ {[1, 2, 3, 4].map((n) => (+ <option key={n} value={String(n)}>{n}</option>+ ))}+ </select>+ </Block>+ </Card>+ ) : (+ <Card title={PROVIDERS[provider].label} description="Connection used for the chat.">+ {provider === 'custom' && (+ <Block label="Base URL" hint="Any OpenAI-compatible endpoint (llama-server, vLLM, LM Studio…). Without the trailing /chat/completions.">+ <input+ value={baseUrlDraft}+ onChange={(e) => { setBaseUrlDraft(e.target.value); setExtResult(null) }}+ placeholder="http://192.168.1.20:8080/v1"+ className={inputCls}+ />+ </Block>+ )}++ <Block+ label={PROVIDERS[provider].noKey ? 'API key (optional)' : 'API key'}+ hint={PROVIDERS[provider].noKey+ ? 'Not needed for a local Ollama — models already pulled with it are reused as-is.'+ : 'Stored locally on this machine only.'}+ >+ <div className="flex gap-2">+ <input+ type="password"+ value={keyDraft}+ onChange={(e) => { setKeyDraft(e.target.value); setExtResult(null) }}+ placeholder={PROVIDERS[provider].noKey ? '' : 'sk-…'}+ className={inputCls}+ />+ <button onClick={handleTestExternal} disabled={extTesting} className={`shrink-0 ${secondaryBtnCls}`}>+ {extTesting ? 'Testing…' : 'Test'}+ </button>+ </div>+ {extResult === 'ok' && (+ <p className="text-[11px] text-emerald-400">Connected — {extModels.length} model{extModels.length > 1 ? 's' : ''} available</p>+ )}+ {extResult === 'error' && (+ <p className="text-[11px] text-red-400">+ {provider === 'ollama'+ ? 'Could not list models — is Ollama running?'+ : `Could not list models — check the key${provider === 'custom' ? ' and URL' : ''}`}+ </p>+ )}+ </Block>++ <Block label="Model" hint="Model name used for the chat.">+ {extModels.length > 0 ? (+ <select value={extModelDraft} onChange={(e) => setExtModelDraft(e.target.value)} className={`${inputCls} cursor-pointer`}>+ {/* Without it the browser shows the first model while the draft+ * stays '' — Save then persisted an empty model name. */}+ {!extModelDraft && <option value="" disabled>Select a model…</option>}+ {!extModels.includes(extModelDraft) && extModelDraft && <option value={extModelDraft}>{extModelDraft}</option>}+ {extModels.map((m) => <option key={m} value={m}>{m}</option>)}+ </select>+ ) : (+ <input+ value={extModelDraft}+ onChange={(e) => setExtModelDraft(e.target.value)}+ placeholder={provider === 'anthropic' ? 'claude-sonnet-5' : provider === 'openai' ? 'gpt-5.2' : provider === 'ollama' ? 'qwen2.5:3b' : 'model name'}+ className={inputCls}+ />+ )}+ </Block>++ <Block>+ <button onClick={saveExternal} className={`self-start ${primaryBtnCls}`}>Save</button>+ </Block>+ </Card>+ )}++ <Card title="Thinking" description="Default mode — can be changed on the fly in the chat via the brain icon.">+ <div className="px-4 py-3 flex flex-col gap-3">+ {THINKING_OPTIONS.map((opt) => (+ <label key={opt.value} className="flex items-start gap-3 cursor-pointer group">+ <input+ type="radio"+ name="thinking"+ value={opt.value}+ checked={defaultThinking === opt.value}+ onChange={() => setDefaultThinking(opt.value)}+ className="mt-0.5 accent-violet-500"+ />+ <div>+ <p className="text-xs font-medium text-zinc-300 group-hover:text-zinc-100 transition-colors">{opt.label}</p>+ <p className="text-[11px] text-zinc-500">{opt.desc}</p>+ </div>+ </label>+ ))}+ </div>+ </Card>+ </div>++ {/* ── Right column ── */}+ <div className="flex flex-col gap-4 min-w-0">+ <Card+ title="MCP server"+ description={<>Control Modly from Claude Desktop, Codex or OpenCode. Community package by <span className="text-zinc-300">DrHepa</span>.</>}+ aside={<Badge tone="muted">Community</Badge>}+ >+ <Block>+ <StepTitle n={1}>Install the package</StepTitle>+ <div className="flex items-center justify-between gap-3 px-3 py-2 rounded-lg bg-surface-500 border border-zinc-800">+ <code className="text-[11px] font-mono text-zinc-300 truncate">+ <span className="text-zinc-600 mr-2">$</span>{MCP_INSTALL}+ </code>+ <CopyButton text={MCP_INSTALL} />+ </div>+ </Block>++ <Block>+ <StepTitle n={2}>Add it to your client</StepTitle>+ <div>+ <SegmentedControl+ value={mcpClient}+ onChange={setMcpClient}+ options={MCP_CLIENTS.map(({ value, label }) => ({ value, label }))}+ ariaLabel="MCP client"+ />+ </div>+ <div className="rounded-lg bg-surface-500 border border-zinc-800 overflow-hidden">+ <div className="flex items-center justify-between gap-3 px-3 py-2 border-b border-zinc-800/80">+ <p className="text-[11px] text-zinc-300 truncate">+ {client.label}+ <span className="ml-2 font-mono text-[10px] text-zinc-600">{client.path}</span>+ </p>+ <CopyButton text={client.config} />+ </div>+ <pre className="px-3 py-3 text-[11px] font-mono text-zinc-400 leading-relaxed overflow-x-auto whitespace-pre">+ {client.config}+ </pre>+ </div>+ </Block>+ </Card>+ </div>+ </div>++ {showLibrary && (+ <ModelLibraryModal onClose={() => { setShowLibrary(false); void refreshLocal() }} />+ )}+ </Section>+ )+}diff --git a/apps/forge-desktop/src/areas/settings/components/ApplicationSection.tsx b/apps/forge-desktop/src/areas/settings/components/ApplicationSection.tsxnew file mode 100644index 000000000..63984cb73--- /dev/null+++ b/apps/forge-desktop/src/areas/settings/components/ApplicationSection.tsx@@ -0,0 +1,19 @@+import { useAppStore } from '@shared/stores/appStore'+import { Section, Card, Row, Toggle } from '@shared/ui'++export function ApplicationSection(): JSX.Element {+ const { showRamIndicator, setShowRamIndicator } = useAppStore()++ return (+ <Section title="Application" subtitle="General application settings.">+ <Card title="Interface">+ <Row+ label="RAM indicator"+ description="Show live memory usage in the top bar."+ >+ <Toggle value={showRamIndicator} onChange={setShowRamIndicator} />+ </Row>+ </Card>+ </Section>+ )+}diff --git a/apps/forge-desktop/src/areas/settings/components/IntegrationsSection.tsx b/apps/forge-desktop/src/areas/settings/components/IntegrationsSection.tsxnew file mode 100644index 000000000..cf7679086--- /dev/null+++ b/apps/forge-desktop/src/areas/settings/components/IntegrationsSection.tsx@@ -0,0 +1,112 @@+import { useEffect, useState } from 'react'+import { Section, Card, Row } from '@shared/ui'++export function IntegrationsSection(): JSX.Element {+ const [token, setToken] = useState('')+ const [visible, setVisible] = useState(false)+ const [status, setStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle')++ useEffect(() => {+ window.electron.settings.get().then((s) => {+ setToken(s.hfToken ?? '')+ })+ }, [])++ async function handleSave() {+ setStatus('saving')+ try {+ await window.electron.settings.set({ hfToken: token.trim() })+ setStatus('saved')+ setTimeout(() => setStatus('idle'), 2500)+ } catch {+ setStatus('error')+ setTimeout(() => setStatus('idle'), 3000)+ }+ }++ async function handleClear() {+ setToken('')+ setStatus('saving')+ try {+ await window.electron.settings.set({ hfToken: '' })+ setStatus('saved')+ setTimeout(() => setStatus('idle'), 2500)+ } catch {+ setStatus('error')+ setTimeout(() => setStatus('idle'), 3000)+ }+ }++ return (+ <Section title="Integrations" subtitle="API keys and tokens for external services.">+ <div className="grid grid-cols-2 gap-4">+ <Card+ title="HuggingFace Hub"+ description="Required to download gated models such as Stable Fast 3D. Generate a token at huggingface.co/settings/tokens."+ >+ <Row label="Access Token" description="Must have at least 'Read' permission.">+ <div className="flex items-center gap-2 w-full">+ <div className="relative flex-1">+ <input+ type={visible ? 'text' : 'password'}+ value={token}+ onChange={(e) => { setToken(e.target.value); setStatus('idle') }}+ onKeyDown={(e) => e.key === 'Enter' && handleSave()}+ placeholder="hf_…"+ spellCheck={false}+ className="w-full px-3 py-1.5 pr-8 rounded-lg bg-zinc-800 border border-zinc-700/60 text-xs font-mono text-zinc-200 placeholder:text-zinc-600 focus:outline-none focus:border-zinc-500 transition-colors"+ />+ <button+ type="button"+ onClick={() => setVisible((v) => !v)}+ title={visible ? 'Hide token' : 'Show token'}+ className="absolute right-2 top-1/2 -translate-y-1/2 text-zinc-600 hover:text-zinc-400 transition-colors"+ >+ {visible ? (+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">+ <path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94"/>+ <path d="M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19"/>+ <line x1="1" y1="1" x2="23" y2="23"/>+ </svg>+ ) : (+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">+ <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>+ <circle cx="12" cy="12" r="3"/>+ </svg>+ )}+ </button>+ </div>++ {token && (+ <button+ onClick={handleClear}+ title="Remove token"+ className="text-zinc-600 hover:text-red-400 transition-colors shrink-0"+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">+ <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>+ </svg>+ </button>+ )}++ <button+ onClick={handleSave}+ disabled={status === 'saving'}+ className={`shrink-0 px-3 py-1.5 rounded-lg text-xs font-semibold transition-all disabled:opacity-50 ${+ status === 'saved' ? 'bg-emerald-500/15 text-emerald-400' :+ status === 'error' ? 'bg-red-500/15 text-red-400' :+ 'bg-accent/15 hover:bg-accent/25 text-accent-light'+ }`}+ >+ {status === 'saving' ? 'Saving…' :+ status === 'saved' ? 'Saved' :+ status === 'error' ? 'Failed' :+ 'Save'}+ </button>+ </div>+ </Row>+ </Card>+ </div>+ </Section>+ )+}diff --git a/apps/forge-desktop/src/areas/settings/components/LogsSection.tsx b/apps/forge-desktop/src/areas/settings/components/LogsSection.tsxnew file mode 100644index 000000000..22fdbab5f--- /dev/null+++ b/apps/forge-desktop/src/areas/settings/components/LogsSection.tsx@@ -0,0 +1,140 @@+import { useEffect, useState, useCallback } from 'react'++const LOG_FILES = [+ { id: 'errors.log', label: 'Errors', description: 'All errors from Electron and Python' },+ { id: 'runtime.log', label: 'Runtime', description: 'FastAPI / Python output' },+ { id: 'modly.log', label: 'App', description: 'General Electron logs' },+]++function formatSession(id: string): string {+ // id format: 2026-03-20T10-23-45+ try {+ const iso = id.replace(/T(\d{2})-(\d{2})-(\d{2})$/, 'T$1:$2:$3')+ const d = new Date(iso)+ return d.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' })+ } catch {+ return id+ }+}++export function LogsSection(): JSX.Element {+ const [sessions, setSessions] = useState<string[]>([])+ const [activeSession, setActiveSession] = useState<string | null>(null) // null = current+ const [activeFile, setActiveFile] = useState('errors.log')+ const [logs, setLogs] = useState<Record<string, string>>({})+ const [loading, setLoading] = useState(true)+ const [copied, setCopied] = useState(false)++ const loadSessions = useCallback(async () => {+ const list = await window.electron.log.listSessions()+ setSessions(list)+ }, [])++ const loadLogs = useCallback(async (session: string | null) => {+ setLoading(true)+ const result = await window.electron.log.readAll(session ?? undefined)+ setLogs(result)+ setLoading(false)+ }, [])++ useEffect(() => {+ loadSessions()+ loadLogs(null)+ }, [loadSessions, loadLogs])++ const handleSessionChange = (value: string) => {+ const session = value === 'current' ? null : value+ setActiveSession(session)+ loadLogs(session)+ }++ const handleRefresh = () => {+ loadSessions()+ loadLogs(activeSession)+ }++ const content = logs[activeFile] ?? ''++ const handleCopy = () => {+ navigator.clipboard.writeText(content).then(() => {+ setCopied(true)+ setTimeout(() => setCopied(false), 2000)+ })+ }++ return (+ <div className="flex flex-col gap-6">+ <div>+ <h2 className="text-sm font-semibold text-zinc-100">Logs</h2>+ <p className="text-xs text-zinc-500 mt-0.5">Application log files — share these when reporting issues.</p>+ </div>++ {/* Session selector */}+ <div className="flex items-center gap-3">+ <label className="text-xs text-zinc-500 shrink-0">Session</label>+ <select+ value={activeSession ?? 'current'}+ onChange={(e) => handleSessionChange(e.target.value)}+ className="flex-1 bg-zinc-800/80 border border-zinc-700/60 text-zinc-200 text-xs rounded-lg px-3 py-2 outline-none focus:border-zinc-600"+ >+ <option value="current">Current session</option>+ {sessions.map((s) => (+ <option key={s} value={s}>{formatSession(s)}</option>+ ))}+ </select>+ </div>++ {/* File tabs */}+ <div className="flex items-center gap-1 border-b border-zinc-800">+ {LOG_FILES.map((f) => (+ <button+ key={f.id}+ onClick={() => setActiveFile(f.id)}+ title={f.description}+ className={`px-4 py-2 text-xs font-medium transition-colors border-b-2 -mb-px ${+ activeFile === f.id+ ? 'border-accent text-accent-light'+ : 'border-transparent text-zinc-500 hover:text-zinc-300'+ }`}+ >+ {f.label}+ </button>+ ))}++ <div className="ml-auto flex items-center gap-2 pb-1">+ <button+ onClick={handleRefresh}+ disabled={loading}+ className="flex items-center gap-1.5 px-3 py-1.5 text-[11px] text-zinc-400 hover:text-zinc-200 disabled:opacity-40 transition-colors"+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className={loading ? 'animate-spin' : ''}>+ <polyline points="23 4 23 10 17 10" />+ <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10" />+ </svg>+ Refresh+ </button>+ <button+ onClick={handleCopy}+ disabled={!content}+ className="px-3 py-1.5 text-[11px] font-semibold rounded-lg bg-zinc-700/60 hover:bg-zinc-700 text-zinc-200 disabled:opacity-40 transition-colors"+ >+ {copied ? 'Copied!' : 'Copy all'}+ </button>+ </div>+ </div>++ {/* Log content */}+ {loading ? (+ <div className="flex items-center justify-center h-48 text-zinc-600 text-xs">Loading…</div>+ ) : content ? (+ <pre className="text-[11px] font-mono text-zinc-400 bg-zinc-900/60 border border-zinc-800 rounded-xl px-4 py-3 max-h-[480px] overflow-y-auto whitespace-pre-wrap break-words select-text leading-relaxed">+ {content}+ </pre>+ ) : (+ <div className="flex items-center justify-center h-48 text-zinc-600 text-xs border border-zinc-800 rounded-xl">+ No entries in {activeFile}+ </div>+ )}+ </div>+ )+}diff --git a/apps/forge-desktop/src/areas/settings/components/PerformanceSection.tsx b/apps/forge-desktop/src/areas/settings/components/PerformanceSection.tsxnew file mode 100644index 000000000..b84586b84--- /dev/null+++ b/apps/forge-desktop/src/areas/settings/components/PerformanceSection.tsx@@ -0,0 +1,51 @@+import { useState } from 'react'+import { Section, Card, Row, Select, Toggle } from '@shared/ui'++export function PerformanceSection(): JSX.Element {+ const [gpu, setGpu] = useState('auto')+ const [vram, setVram] = useState('8')+ const [workers, setWorkers] = useState('1')+ const [fp16, setFp16] = useState(true)++ return (+ <Section title="Performance" subtitle="Configure GPU usage and memory limits.">+ <div className="grid grid-cols-2 gap-4">++ <Card title="Device" description="Select which compute device to use for AI inference.">+ <Row label="GPU device" description="Device used for model inference.">+ <Select value={gpu} onChange={setGpu} options={[+ { value: 'auto', label: 'Auto-detect' },+ { value: 'mps', label: 'Apple GPU (MPS)' },+ { value: 'cuda0', label: 'NVIDIA GPU 0' },+ { value: 'cuda1', label: 'NVIDIA GPU 1' },+ { value: 'cpu', label: 'CPU (slow)' },+ ]} />+ </Row>+ <Row label="FP16 precision" description="Half-precision for faster inference.">+ <Toggle value={fp16} onChange={setFp16} />+ </Row>+ </Card>++ <Card title="Memory" description="Control memory allocation per generation job.">+ <Row label="VRAM limit" description="Max GPU memory per generation.">+ <Select value={vram} onChange={setVram} options={[+ { value: '4', label: '4 GB' },+ { value: '6', label: '6 GB' },+ { value: '8', label: '8 GB' },+ { value: '12', label: '12 GB' },+ { value: '0', label: 'No limit' },+ ]} />+ </Row>+ <Row label="Parallel workers" description="Concurrent generation jobs.">+ <Select value={workers} onChange={setWorkers} options={[+ { value: '1', label: '1 (default)' },+ { value: '2', label: '2' },+ { value: '4', label: '4' },+ ]} />+ </Row>+ </Card>++ </div>+ </Section>+ )+}diff --git a/apps/forge-desktop/src/areas/settings/components/StorageSection.tsx b/apps/forge-desktop/src/areas/settings/components/StorageSection.tsxnew file mode 100644index 000000000..7c949adc8--- /dev/null+++ b/apps/forge-desktop/src/areas/settings/components/StorageSection.tsx@@ -0,0 +1,355 @@+import { useEffect, useState } from 'react'+import { Section, Card, Row, PathRow } from '@shared/ui'++// ─── MoveFolderModal ──────────────────────────────────────────────────────────++function MoveFolderModal({ title, currentDir, items, itemLabel, moveLabel, moveDesc, deleteLabel, deleteDesc, status, onCancel, onMove, onDelete }: {+ title: string+ currentDir: string+ items: string[]+ itemLabel: string+ moveLabel: string+ moveDesc: string+ deleteLabel: string+ deleteDesc: string+ status: 'idle' | 'busy' | 'error'+ onCancel: () => void+ onMove: () => void+ onDelete: () => void+}): JSX.Element {+ return (+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">+ <div className="w-[440px] rounded-2xl border border-zinc-700/60 bg-zinc-900 shadow-2xl overflow-hidden">++ <div className="px-6 pt-5 pb-4">+ <h3 className="text-sm font-semibold text-zinc-100">{title}</h3>+ <p className="text-xs text-zinc-500 mt-1">+ {items.length} {itemLabel}{items.length > 1 ? 's' : ''} already at:+ </p>+ <p className="mt-2.5 px-3 py-2 bg-zinc-800/70 rounded-lg text-[11px] font-mono text-zinc-400 truncate border border-zinc-700/50">+ {currentDir}+ </p>+ <p className="text-xs text-zinc-500 mt-3">What should happen to them?</p>+ </div>++ <div className="px-6 pb-5 flex flex-col gap-2">+ {status === 'error' && (+ <p className="text-[11px] text-red-400 mb-0.5">Something went wrong. Please try again.</p>+ )}++ <button+ onClick={onMove}+ disabled={status === 'busy'}+ className="w-full px-4 py-3 rounded-xl bg-accent/10 hover:bg-accent/20 border border-accent/30 hover:border-accent/50 text-left transition-all disabled:opacity-40"+ >+ <p className="text-xs font-semibold text-accent-light">{moveLabel}</p>+ <p className="text-[11px] text-zinc-500 mt-0.5">{moveDesc}</p>+ </button>++ <button+ onClick={onDelete}+ disabled={status === 'busy'}+ className="w-full px-4 py-3 rounded-xl bg-zinc-800/50 hover:bg-red-950/30 border border-zinc-700/50 hover:border-red-800/50 text-left transition-all disabled:opacity-40"+ >+ <p className="text-xs font-semibold text-red-400">{deleteLabel}</p>+ <p className="text-[11px] text-zinc-500 mt-0.5">{deleteDesc}</p>+ </button>++ <button+ onClick={onCancel}+ disabled={status === 'busy'}+ className="w-full px-4 py-2.5 mt-0.5 rounded-xl text-xs font-medium text-zinc-300 bg-zinc-800 hover:bg-zinc-700 border border-zinc-700 hover:border-zinc-600 transition-colors disabled:opacity-40"+ >+ {status === 'busy' ? 'Please wait…' : 'Cancel'}+ </button>+ </div>++ </div>+ </div>+ )+}++// ─── StorageSection ───────────────────────────────────────────────────────────++export function StorageSection(): JSX.Element {+ const [modelsDir, setModelsDir] = useState('')+ const [workspaceDir, setWorkspaceDir] = useState('')+ const [workflowsDir, setWorkflowsDir] = useState('')+ const [cacheStatus, setCacheStatus] = useState<'idle' | 'clearing' | 'done' | 'error'>('idle')++ const [pendingModelsDir, setPendingModelsDir] = useState<string | null>(null)+ const [existingModels, setExistingModels] = useState<string[]>([])+ const [modelsActionStatus, setModelsActionStatus] = useState<'idle' | 'busy' | 'error'>('idle')++ const [pendingWorkspaceDir, setPendingWorkspaceDir] = useState<string | null>(null)+ const [existingWorkspaces, setExistingWorkspaces] = useState<string[]>([])+ const [workspaceActionStatus, setWorkspaceActionStatus] = useState<'idle' | 'busy' | 'error'>('idle')++ const [pendingWorkflowsDir, setPendingWorkflowsDir] = useState<string | null>(null)+ const [existingWorkflows, setExistingWorkflows] = useState<string[]>([])+ const [workflowsActionStatus, setWorkflowsActionStatus] = useState<'idle' | 'busy' | 'error'>('idle')++ useEffect(() => {+ window.electron.settings.get().then((s) => {+ setModelsDir(s.modelsDir)+ setWorkspaceDir(s.workspaceDir)+ setWorkflowsDir(s.workflowsDir)+ })+ }, [])++ async function applyModelsDir(path: string) {+ setModelsDir(path)+ await window.electron.settings.set({ modelsDir: path })+ await window.electron.api.updatePaths({ modelsDir: path })+ }++ async function applyWorkspaceDir(path: string) {+ setWorkspaceDir(path)+ await window.electron.settings.set({ workspaceDir: path })+ await window.electron.api.updatePaths({ workspaceDir: path })+ }++ async function applyWorkflowsDir(path: string) {+ setWorkflowsDir(path)+ await window.electron.settings.set({ workflowsDir: path })+ }++ async function handleBrowseModels() {+ const newPath = await window.electron.fs.selectDirectory(modelsDir)+ if (!newPath || newPath === modelsDir) return++ const models = await window.electron.fs.listDir(modelsDir)+ if (models.length > 0) {+ setExistingModels(models)+ setPendingModelsDir(newPath)+ return+ }++ await applyModelsDir(newPath)+ }++ async function handleBrowseWorkspace() {+ const newPath = await window.electron.fs.selectDirectory(workspaceDir)+ if (!newPath || newPath === workspaceDir) return++ const items = await window.electron.fs.listDir(workspaceDir)+ if (items.length > 0) {+ setExistingWorkspaces(items)+ setPendingWorkspaceDir(newPath)+ return+ }++ await applyWorkspaceDir(newPath)+ }++ async function handleBrowseWorkflows() {+ const newPath = await window.electron.fs.selectDirectory(workflowsDir)+ if (!newPath || newPath === workflowsDir) return++ const items = await window.electron.fs.listDir(workflowsDir)+ if (items.length > 0) {+ setExistingWorkflows(items)+ setPendingWorkflowsDir(newPath)+ return+ }++ await applyWorkflowsDir(newPath)+ }++ async function handleMoveModels() {+ if (!pendingModelsDir) return+ setModelsActionStatus('busy')+ const result = await window.electron.fs.moveDirectory({ src: modelsDir, dest: pendingModelsDir })+ if (result.success) {+ await applyModelsDir(pendingModelsDir)+ closeModelsModal()+ } else {+ setModelsActionStatus('error')+ }+ }++ async function handleDeleteModels() {+ if (!pendingModelsDir) return+ setModelsActionStatus('busy')+ const result = await window.electron.fs.deleteDirectory(modelsDir)+ if (result.success) {+ await applyModelsDir(pendingModelsDir)+ closeModelsModal()+ } else {+ setModelsActionStatus('error')+ }+ }++ function closeModelsModal() {+ setPendingModelsDir(null)+ setExistingModels([])+ setModelsActionStatus('idle')+ }++ async function handleMoveWorkspace() {+ if (!pendingWorkspaceDir) return+ setWorkspaceActionStatus('busy')+ const result = await window.electron.fs.moveDirectory({ src: workspaceDir, dest: pendingWorkspaceDir })+ if (result.success) {+ await applyWorkspaceDir(pendingWorkspaceDir)+ closeWorkspaceModal()+ } else {+ setWorkspaceActionStatus('error')+ }+ }++ async function handleDeleteWorkspace() {+ if (!pendingWorkspaceDir) return+ setWorkspaceActionStatus('busy')+ const result = await window.electron.fs.deleteDirectory(workspaceDir)+ if (result.success) {+ await applyWorkspaceDir(pendingWorkspaceDir)+ closeWorkspaceModal()+ } else {+ setWorkspaceActionStatus('error')+ }+ }++ function closeWorkspaceModal() {+ setPendingWorkspaceDir(null)+ setExistingWorkspaces([])+ setWorkspaceActionStatus('idle')+ }++ async function handleMoveWorkflows() {+ if (!pendingWorkflowsDir) return+ setWorkflowsActionStatus('busy')+ const result = await window.electron.fs.moveDirectory({ src: workflowsDir, dest: pendingWorkflowsDir })+ if (result.success) {+ await applyWorkflowsDir(pendingWorkflowsDir)+ closeWorkflowsModal()+ } else {+ setWorkflowsActionStatus('error')+ }+ }++ async function handleDeleteWorkflows() {+ if (!pendingWorkflowsDir) return+ setWorkflowsActionStatus('busy')+ const result = await window.electron.fs.deleteDirectory(workflowsDir)+ if (result.success) {+ await applyWorkflowsDir(pendingWorkflowsDir)+ closeWorkflowsModal()+ } else {+ setWorkflowsActionStatus('error')+ }+ }++ function closeWorkflowsModal() {+ setPendingWorkflowsDir(null)+ setExistingWorkflows([])+ setWorkflowsActionStatus('idle')+ }++ async function handleClearCache() {+ setCacheStatus('clearing')+ const result = await window.electron.cache.clear()+ if (!result.success) console.error('[cache:clear] renderer:', result.error)+ setCacheStatus(result.success ? 'done' : 'error')+ setTimeout(() => setCacheStatus('idle'), 2500)+ }++ return (+ <Section title="Storage" subtitle="Manage where models and outputs are saved on disk.">+ <div className="grid grid-cols-2 gap-4">++ <Card title="Directories" description="Paths used to store model weights and generated files.">+ <PathRow+ label="Models"+ description="Where downloaded AI model weights are stored."+ value={modelsDir}+ onBrowse={handleBrowseModels}+ />+ <PathRow+ label="Workspace"+ description="Where generated 3D files are saved."+ value={workspaceDir}+ onBrowse={handleBrowseWorkspace}+ />+ <PathRow+ label="Workflows"+ description="Where workflow definitions are saved."+ value={workflowsDir}+ onBrowse={handleBrowseWorkflows}+ />+ </Card>++ <Card title="Cache" description="Temporary files created during generation processing.">+ <Row label="Temp files" description="Intermediate files accumulated over time.">+ <button+ onClick={handleClearCache}+ disabled={cacheStatus === 'clearing'}+ className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-all disabled:opacity-50 ${+ cacheStatus === 'done' ? 'bg-green-500/15 text-green-400' :+ cacheStatus === 'error' ? 'bg-red-500/15 text-red-400' :+ 'bg-zinc-800 hover:bg-zinc-700 text-zinc-300'+ }`}+ >+ {cacheStatus === 'clearing' ? 'Clearing…' :+ cacheStatus === 'done' ? '✓ Cleared' :+ cacheStatus === 'error' ? '✗ Failed' :+ 'Clear cache'}+ </button>+ </Row>+ </Card>++ </div>++ {pendingModelsDir && (+ <MoveFolderModal+ title="Change models folder"+ currentDir={modelsDir}+ items={existingModels}+ itemLabel="model"+ moveLabel="Move to new folder"+ moveDesc="Transfer all models to the new location."+ deleteLabel="Delete models"+ deleteDesc="Remove from current folder. You'll need to re-download."+ status={modelsActionStatus}+ onCancel={closeModelsModal}+ onMove={handleMoveModels}+ onDelete={handleDeleteModels}+ />+ )}++ {pendingWorkspaceDir && (+ <MoveFolderModal+ title="Change workspace folder"+ currentDir={workspaceDir}+ items={existingWorkspaces}+ itemLabel="item"+ moveLabel="Move to new folder"+ moveDesc="Transfer all workspace files to the new location."+ deleteLabel="Delete workspace files"+ deleteDesc="Remove all files from the current folder."+ status={workspaceActionStatus}+ onCancel={closeWorkspaceModal}+ onMove={handleMoveWorkspace}+ onDelete={handleDeleteWorkspace}+ />+ )}++ {pendingWorkflowsDir && (+ <MoveFolderModal+ title="Change workflows folder"+ currentDir={workflowsDir}+ items={existingWorkflows}+ itemLabel="workflow"+ moveLabel="Move to new folder"+ moveDesc="Transfer all workflow files to the new location."+ deleteLabel="Delete workflows"+ deleteDesc="Remove all workflow files from the current folder."+ status={workflowsActionStatus}+ onCancel={closeWorkflowsModal}+ onMove={handleMoveWorkflows}+ onDelete={handleDeleteWorkflows}+ />+ )}+ </Section>+ )+}diff --git a/apps/forge-desktop/src/areas/setup/FirstRunSetup.tsx b/apps/forge-desktop/src/areas/setup/FirstRunSetup.tsxnew file mode 100644index 000000000..034a131c1--- /dev/null+++ b/apps/forge-desktop/src/areas/setup/FirstRunSetup.tsx@@ -0,0 +1,329 @@+import { useEffect, useState } from 'react'+import { useAppStore, SetupProgress } from '@shared/stores/appStore'++// ─── Logo (shared) ──────────────────────────────────────────────────────────++function ModlyLogo(): JSX.Element {+ return (+ <div className="mb-8">+ <svg width="64" height="64" viewBox="0 0 609 609" xmlns="http://www.w3.org/2000/svg">+ <defs>+ <linearGradient id="tlg-splash" x1="700" y1="5700" x2="5900" y2="750" gradientUnits="userSpaceOnUse">+ <stop offset="0%" stopColor="#c084fc"/>+ <stop offset="45%" stopColor="#9333ea"/>+ <stop offset="100%" stopColor="#4c1d95"/>+ </linearGradient>+ </defs>+ <g transform="translate(0,609) scale(0.1,-0.1)" fill="url(#tlg-splash)" stroke="none">+ <path d="M2964 5671 c-20 -9 -918 -521 -1604 -914 -173 -100 -362 -207 -420 -239 -58 -32 -118 -73 -133 -91 -58 -67 -57 -45 -57 -1067 0 -831 2 -938 16 -958 l15 -22 758 0 c417 0 761 3 764 6 12 13 -26 67 -283 399 -64 83 -120 156 -124 163 -5 7 4 32 22 60 16 26 238 396 493 822 254 426 569 951 699 1165 308 506 305 502 290 520 -7 8 -72 48 -144 87 -124 69 -135 73 -201 75 -38 2 -79 -1 -91 -6z"/>+ <path d="M3683 5328 c-18 -23 -833 -1306 -833 -1312 0 -12 83 -15 485 -21 230 -3 420 -7 421 -8 4 -5 451 -755 657 -1102 438 -739 668 -1120 691 -1143 l23 -24 71 36 c91 46 139 88 152 134 14 50 14 2403 0 2453 -20 72 -48 98 -215 193 -766 440 -1414 806 -1427 806 -9 0 -20 -6 -25 -12z"/>+ <path d="M4037 2838 c-25 -33 -443 -702 -467 -747 l-12 -24 -1384 4 c-1247 4 -1385 2 -1399 -12 -44 -44 -21 -170 42 -231 21 -20 203 -132 408 -249 385 -220 1034 -594 1310 -754 88 -51 183 -105 210 -121 28 -15 88 -49 134 -76 158 -90 177 -86 475 84 127 72 416 236 641 363 226 128 507 287 625 354 212 121 250 145 250 163 0 5 -40 73 -88 151 -49 78 -177 286 -284 462 -393 643 -407 664 -430 665 -4 0 -18 -15 -31 -32z"/>+ </g>+ </svg>+ </div>+ )+}++function AppHeader(): JSX.Element {+ return (+ <>+ <ModlyLogo />+ <h1 className="text-2xl font-semibold text-zinc-100 mb-1">Modly</h1>+ <p className="text-sm text-zinc-500 mb-10">AI-powered 3D mesh generation</p>+ </>+ )+}++// ─── Panels ─────────────────────────────────────────────────────────────────++function CheckingPanel(): JSX.Element {+ return (+ <div className="w-80 bg-surface-300 rounded-xl p-6">+ <p className="text-sm font-medium text-zinc-100">Checking environment…</p>+ <div className="mt-4 h-1 bg-zinc-800 rounded-full overflow-hidden">+ <div className="h-full bg-accent rounded-full animate-pulse" style={{ width: '30%' }} />+ </div>+ </div>+ )+}++function ChoosePathPanel({+ defaultPath,+ platform,+ arch,+ onConfirm,+}: {+ defaultPath: string+ platform: string+ arch: string+ onConfirm: (path: string) => void+}): JSX.Element {+ const [selectedPath, setSelectedPath] = useState(defaultPath || '')++ // Sync if defaultPath arrives after mount (async IPC)+ useEffect(() => {+ if (defaultPath && !selectedPath) setSelectedPath(defaultPath)+ // eslint-disable-next-line react-hooks/exhaustive-deps -- only sync when defaultPath arrives, not on user edits+ }, [defaultPath])++ async function handleBrowse() {+ const picked = await window.electron.fs.selectDirectory(selectedPath || undefined)+ if (picked) setSelectedPath(picked)+ }++ return (+ <div className="w-80 bg-surface-300 rounded-xl p-6">+ <p className="text-sm font-medium text-zinc-100 mb-1">Choose a data folder</p>+ <p className="text-xs text-zinc-500 mb-4">+ Models can be several GB each. Choose a folder with plenty of free space.+ {platform === 'darwin' && arch === 'arm64'+ ? ' Apple Silicon is supported on this build.'+ : ' A fast local SSD is recommended.'}+ </p>++ {/* Path display */}+ <div className="flex items-center gap-2 mb-4">+ <div className="flex-1 min-w-0 bg-zinc-900 rounded-lg px-3 py-2">+ <p className="text-xs font-mono text-zinc-400 truncate" title={selectedPath}>+ {selectedPath || 'No folder selected'}+ </p>+ </div>+ <button+ onClick={handleBrowse}+ className="shrink-0 px-3 py-2 bg-zinc-800 hover:bg-zinc-700 text-zinc-300 rounded-lg text-xs font-medium transition-colors"+ >+ Browse…+ </button>+ </div>++ <button+ onClick={() => onConfirm(selectedPath)}+ disabled={!selectedPath}+ className="w-full py-2 bg-accent hover:bg-accent-dark disabled:opacity-40 disabled:cursor-not-allowed rounded-lg text-sm font-medium text-white transition-colors"+ >+ Continue+ </button>+ </div>+ )+}++const STEPS = [+ { key: 'enabling-site', label: 'Preparing Python' },+ { key: 'pip', label: 'Installing pip' },+ { key: 'packages', label: 'Installing packages' },+] as const++function stepIndex(step: string): number {+ return STEPS.findIndex((s) => s.key === step)+}++function InstallingPanel({ progress }: { progress: SetupProgress | null }): JSX.Element {+ const currentIdx = progress ? stepIndex(progress.step) : -1+ const percent = progress?.percent ?? 0++ return (+ <div className="w-80 bg-surface-300 rounded-xl p-6">+ <p className="text-sm font-medium text-zinc-100 mb-4">Setting up environment…</p>++ {/* Step indicators */}+ <div className="flex gap-2 mb-4">+ {STEPS.map((step, idx) => {+ const done = idx < currentIdx+ const active = idx === currentIdx+ return (+ <div key={step.key} className="flex-1 min-w-0">+ <div+ className={`h-1 rounded-full transition-colors ${+ done ? 'bg-accent' :+ active ? 'bg-accent opacity-60 animate-pulse' :+ 'bg-zinc-700'+ }`}+ />+ <p className={`text-xs mt-1 truncate ${active ? 'text-zinc-300' : 'text-zinc-600'}`}>+ {step.label}+ </p>+ </div>+ )+ })}+ </div>++ {/* Progress bar */}+ <div className="h-1.5 bg-zinc-800 rounded-full overflow-hidden mb-3">+ <div+ className="h-full bg-accent rounded-full transition-all duration-300"+ style={{ width: `${percent}%` }}+ />+ </div>++ <div className="flex justify-between items-center">+ <p className="text-xs text-zinc-500 truncate flex-1 min-w-0">+ {progress?.currentPackage ?? (currentIdx >= 0 ? STEPS[currentIdx]?.label : 'Initialising…')}+ </p>+ <p className="text-xs text-zinc-500 ml-2 shrink-0">{percent}%</p>+ </div>+ </div>+ )+}++function StartingPanel(): JSX.Element {+ return (+ <div className="w-80 bg-surface-300 rounded-xl p-6">+ <p className="text-sm font-medium text-zinc-100">Starting backend…</p>+ <p className="text-xs text-zinc-500 mt-1">Launching the local AI server</p>+ <div className="mt-4 h-1 bg-zinc-800 rounded-full overflow-hidden">+ <div className="h-full bg-accent rounded-full animate-pulse" style={{ width: '40%' }} />+ </div>+ </div>+ )+}++function ApplyingUpdatePanel({ version }: { version: string }): JSX.Element {+ return (+ <div className="w-80 bg-surface-300 rounded-xl p-6">+ <div className="flex items-center gap-3 mb-4">+ <div className="w-8 h-8 rounded-lg bg-accent/15 border border-accent/25 flex items-center justify-center shrink-0">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-accent-light">+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>+ <polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/>+ </svg>+ </div>+ <div>+ <p className="text-sm font-medium text-zinc-100">Applying update {version}</p>+ <p className="text-xs text-zinc-500 mt-0.5">The app will restart automatically</p>+ </div>+ </div>+ <div className="h-1 bg-zinc-800 rounded-full overflow-hidden">+ <div className="h-full bg-accent rounded-full animate-pulse" style={{ width: '70%' }} />+ </div>+ </div>+ )+}++function ErrorPanel({ message }: { message: string | null }): JSX.Element {+ const lines = (message ?? 'Check the console for details').split('\n')+ const isAntivirusHint = message?.includes('antivirus') ?? false++ return (+ <div className="w-80 bg-surface-300 rounded-xl p-6">+ <p className="text-sm font-medium text-zinc-100">Something went wrong</p>+ <div className="mt-2 space-y-1 max-h-48 overflow-y-auto">+ {lines.map((line, i) =>+ line === '' ? (+ <div key={i} className="h-1" />+ ) : (+ <p key={i} className="text-xs text-zinc-500 font-mono break-all">{line}</p>+ )+ )}+ </div>+ {isAntivirusHint && (+ <div className="mt-3 p-3 bg-amber-950/40 border border-amber-700/40 rounded-lg">+ <p className="text-xs text-amber-400 font-medium">Antivirus detected</p>+ <p className="text-xs text-amber-500/80 mt-0.5">+ Add the app folder to your antivirus exclusions, then click Retry.+ </p>+ </div>+ )}+ <button+ onClick={() => window.location.reload()}+ className="mt-4 w-full py-2 bg-accent hover:bg-accent-dark rounded-lg text-sm font-medium text-white transition-colors"+ >+ Retry+ </button>+ </div>+ )+}++// ─── Main component ─────────────────────────────────────────────────────────++export default function FirstRunSetup(): JSX.Element {+ const { setupStatus, setupProgress, setupError, saveDataDir, defaultDataDir, backendStatus, backendError, platform, arch } =+ useAppStore()+ const [applyingVersion, setApplyingVersion] = useState<string | null>(null)+ const isMac = platform === 'darwin'++ useEffect(() => {+ window.electron.updater.onApplying(({ version }) => setApplyingVersion(`v${version}`))+ return () => { window.electron.updater.offApplying() }+ }, [])++ const renderPanel = () => {+ if (applyingVersion) return <ApplyingUpdatePanel version={applyingVersion} />+ switch (setupStatus) {+ case 'idle':+ case 'checking':+ return <CheckingPanel />++ case 'needed':+ return <ChoosePathPanel defaultPath={defaultDataDir} platform={platform} arch={arch} onConfirm={saveDataDir} />++ case 'installing':+ return <InstallingPanel progress={setupProgress} />++ case 'done':+ // setup done — now waiting for backend+ if (backendStatus === 'error') return <ErrorPanel message={backendError} />+ return <StartingPanel />++ case 'error':+ return <ErrorPanel message={setupError} />++ default:+ return <StartingPanel />+ }+ }++ return (+ <div className="flex flex-col h-full bg-surface-500">+ {/* Title bar */}+ <div className="flex items-center h-9 px-3 shrink-0 drag-region">+ <div className={`flex items-center gap-2 no-drag ${isMac ? 'pl-[72px]' : ''}`}>+ <svg width="18" height="18" viewBox="0 0 609 609" xmlns="http://www.w3.org/2000/svg" className="shrink-0">+ <defs>+ <linearGradient id="tlg-setup" x1="700" y1="5700" x2="5900" y2="750" gradientUnits="userSpaceOnUse">+ <stop offset="0%" stopColor="#c084fc"/>+ <stop offset="45%" stopColor="#9333ea"/>+ <stop offset="100%" stopColor="#4c1d95"/>+ </linearGradient>+ </defs>+ <g transform="translate(0,609) scale(0.1,-0.1)" fill="url(#tlg-setup)" stroke="none">+ <path d="M2964 5671 c-20 -9 -918 -521 -1604 -914 -173 -100 -362 -207 -420 -239 -58 -32 -118 -73 -133 -91 -58 -67 -57 -45 -57 -1067 0 -831 2 -938 16 -958 l15 -22 758 0 c417 0 761 3 764 6 12 13 -26 67 -283 399 -64 83 -120 156 -124 163 -5 7 4 32 22 60 16 26 238 396 493 822 254 426 569 951 699 1165 308 506 305 502 290 520 -7 8 -72 48 -144 87 -124 69 -135 73 -201 75 -38 2 -79 -1 -91 -6z"/>+ <path d="M3683 5328 c-18 -23 -833 -1306 -833 -1312 0 -12 83 -15 485 -21 230 -3 420 -7 421 -8 4 -5 451 -755 657 -1102 438 -739 668 -1120 691 -1143 l23 -24 71 36 c91 46 139 88 152 134 14 50 14 2403 0 2453 -20 72 -48 98 -215 193 -766 440 -1414 806 -1427 806 -9 0 -20 -6 -25 -12z"/>+ <path d="M4037 2838 c-25 -33 -443 -702 -467 -747 l-12 -24 -1384 4 c-1247 4 -1385 2 -1399 -12 -44 -44 -21 -170 42 -231 21 -20 203 -132 408 -249 385 -220 1034 -594 1310 -754 88 -51 183 -105 210 -121 28 -15 88 -49 134 -76 158 -90 177 -86 475 84 127 72 416 236 641 363 226 128 507 287 625 354 212 121 250 145 250 163 0 5 -40 73 -88 151 -49 78 -177 286 -284 462 -393 643 -407 664 -430 665 -4 0 -18 -15 -31 -32z"/>+ </g>+ </svg>+ <span className="text-xs font-semibold text-zinc-300">Modly</span>+ </div>+ <div className="flex-1" />+ {!isMac && (+ <div className="flex items-center gap-1 no-drag">+ <button+ onClick={() => window.electron.window.minimize()}+ className="w-7 h-7 flex items-center justify-center rounded hover:bg-zinc-700 text-zinc-500 hover:text-zinc-100 transition-colors"+ aria-label="Minimize"+ >+ <svg width="10" height="1" viewBox="0 0 10 1" fill="currentColor">+ <rect width="10" height="1" />+ </svg>+ </button>+ <button+ onClick={() => window.electron.window.close()}+ className="w-7 h-7 flex items-center justify-center rounded hover:bg-red-600 text-zinc-500 hover:text-white transition-colors"+ aria-label="Close"+ >+ <svg width="9" height="9" viewBox="0 0 9 9" fill="none" stroke="currentColor" strokeWidth="1.2">+ <line x1="0" y1="0" x2="9" y2="9" />+ <line x1="9" y1="0" x2="0" y2="9" />+ </svg>+ </button>+ </div>+ )}+ </div>++ {/* Content */}+ <div className="flex flex-col flex-1 items-center justify-center">+ <AppHeader />+ {renderPanel()}+ </div>+ </div>+ )+}diff --git a/apps/forge-desktop/src/areas/workflows/WorkflowsPage.tsx b/apps/forge-desktop/src/areas/workflows/WorkflowsPage.tsxnew file mode 100644index 000000000..8fc4cea61--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/WorkflowsPage.tsx@@ -0,0 +1,2211 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { createPortal } from 'react-dom'+import {+ ReactFlow,+ ReactFlowProvider,+ Background,++ addEdge,+ useNodesState,+ useEdgesState,+ useReactFlow,+ type Connection,+ type Node,+ type Edge,+ type OnConnectStartParams,+} from '@xyflow/react'+import { useWorkflowsStore, NODE_TYPES_WITHOUT_TARGET, NODE_TYPES_WITHOUT_SOURCE, FOLDER_COLORS } from '@shared/stores/workflowsStore'+import { useExtensionsStore } from '@shared/stores/extensionsStore'+import { useAppStore } from '@shared/stores/appStore'+import type { Workflow, WFNode, WFEdge, WFNodeData } from '@shared/types/electron.d'+import { buildAllWorkflowExtensions } from './mockExtensions'+import type { WorkflowExtension } from './mockExtensions'+import { useWorkflowRunStore } from './workflowRunStore'+import { validateWorkflowPreflight } from './preflight'+import ExtensionNode from './nodes/ExtensionNode'+import ImageNode from './nodes/ImageNode'+import TextNode from './nodes/TextNode'+import AddToSceneNode from './nodes/AddToSceneNode'+import Load3DMeshNode from './nodes/Load3DMeshNode'+import LoadSceneNode from './nodes/LoadSceneNode'+import PreviewImageNode from './nodes/PreviewImageNode'+import ImagePreviewNode from './nodes/ImagePreviewNode'+import WaitNode from './nodes/WaitNode'+import WhileNode from './nodes/WhileNode'+import ForEachNode from './nodes/ForEachNode'+import WorkflowEdge from './nodes/WorkflowEdge'++// ─── Constants ────────────────────────────────────────────────────────────────++const DRAG_KEY = 'modly/extension-id'+const DRAG_NODE_KEY = 'modly/node-type'+const NODE_TYPES = { extensionNode: ExtensionNode, imageNode: ImageNode, textNode: TextNode, outputNode: AddToSceneNode, meshNode: Load3DMeshNode, sceneNode: LoadSceneNode, previewNode: PreviewImageNode, imagePreviewNode: ImagePreviewNode, waitNode: WaitNode, whileNode: WhileNode, forEachNode: ForEachNode }++// Loop-container node types: resizable frames whose children form a loop body.+// (For Each iterators are plain source nodes, not containers.)+const CONTAINER_TYPES = new Set(['whileNode'])+const isContainerType = (type: string | undefined): boolean => !!type && CONTAINER_TYPES.has(type)+const EDGE_TYPES = { workflowEdge: WorkflowEdge }++const DEFAULT_EDGE_OPTS = { type: 'workflowEdge' }++// The While container whose bounds contain a flow-space point, if any. Used to+// auto-parent nodes dropped (or created) inside a While so they join its loop body.+function findWhileContainerAt(nodes: Node[], pos: { x: number; y: number }): Node | undefined {+ return nodes.find((n) => {+ if (!isContainerType(n.type)) return false+ const gw = (n.measured?.width ?? n.width ?? (n.style?.width as number)) || 0+ const gh = (n.measured?.height ?? n.height ?? (n.style?.height as number)) || 0+ return pos.x >= n.position.x && pos.x <= n.position.x + gw+ && pos.y >= n.position.y && pos.y <= n.position.y + gh+ })+}++// ─── IO badge ─────────────────────────────────────────────────────────────────++const IO_STYLES: Record<'image' | 'text' | 'mesh' | 'audio' | 'scene', string> = {+ audio: 'bg-emerald-500/15 text-emerald-400 border-emerald-500/25',+ image: 'bg-sky-500/15 text-sky-400 border-sky-500/25',+ mesh: 'bg-violet-500/15 text-violet-400 border-violet-500/25',+ text: 'bg-amber-500/15 text-amber-400 border-amber-500/25',+ scene: 'bg-pink-500/15 text-pink-400 border-pink-500/25',+}++function IoBadge({ type }: { type: 'image' | 'text' | 'mesh' | 'audio' | 'scene' }) {+ return (+ <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border ${IO_STYLES[type]}`}>+ {type}+ </span>+ )+}++// ─── Helpers ──────────────────────────────────────────────────────────────────++function newId(): string { return crypto.randomUUID() }++// Node clipboard (module-level so Ctrl+C in one workflow tab can be pasted in+// another — the canvas remounts per tab but the module survives).+const _nodeClipboard: { current: { nodes: Node[]; edges: Edge[]; pastes: number } | null } = { current: null }++function newWorkflow(): Workflow {+ const now = new Date().toISOString()+ return { id: newId(), name: 'New Workflow', description: '', nodes: [], edges: [], createdAt: now, updatedAt: now }+}++// ─── Extensions panel ────────────────────────────────────────────────────────++const PANEL_MIN = 240+const PANEL_MAX = 860++const PANEL_BUILTIN_NODES = [+ { type: 'imageNode', label: 'Image', color: '#38bdf8', icon: <><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></> },+ { type: 'textNode', label: 'Text', color: '#fbbf24', icon: <><path d="M17 6.1H3M21 12.1H3M15.1 18H3"/></> },+ { type: 'meshNode', label: 'Load 3D Mesh', color: '#a78bfa', icon: <><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/></> },+ { type: 'sceneNode', label: 'Load Scene', color: '#f472b6', icon: <><path d="M4 7h16"/><path d="M7 4h10v16H7z"/></> },+ { type: 'outputNode', label: 'Add to Scene', color: '#a78bfa', icon: <><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/></> },+ { type: 'previewNode', label: 'Preview Views', color: '#38bdf8', icon: <><rect x="3" y="3" width="8" height="8" rx="1"/><rect x="13" y="3" width="8" height="8" rx="1"/><rect x="3" y="13" width="8" height="8" rx="1"/><rect x="13" y="13" width="8" height="8" rx="1"/></> },+ { type: 'imagePreviewNode', label: 'Preview Image', color: '#38bdf8', icon: <><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></> },+ { type: 'waitNode', label: 'Wait', color: '#71717a', icon: <><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></> },+ { type: 'whileNode', label: 'While', color: '#f59e0b', icon: <><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></> },+ { type: 'forEachNode', label: 'For Each', color: '#38bdf8', icon: <><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></> },+]++function ExtGroupHeader({ title, author, expanded, onToggle, count }: { title: string; author?: string; expanded: boolean; onToggle: () => void; count: number }) {+ return (+ <button+ onClick={onToggle}+ className="flex items-center gap-2 w-full px-1 py-1.5 group"+ >+ <svg+ width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"+ className="text-zinc-600 group-hover:text-zinc-400 transition-colors shrink-0"+ style={{ transform: expanded ? 'rotate(90deg)' : 'rotate(0deg)', transition: 'transform 0.15s ease' }}+ >+ <polyline points="9 18 15 12 9 6"/>+ </svg>+ <div className="flex flex-col items-start min-w-0">+ <span className="text-[11px] font-semibold text-zinc-400 group-hover:text-zinc-200 transition-colors truncate leading-tight">{title}</span>+ {author && <span className="text-[9px] text-zinc-600 truncate leading-tight">{author}</span>}+ </div>+ <span className="ml-auto text-[9px] text-zinc-700 shrink-0">{count}</span>+ </button>+ )+}++function ExtensionsPanel({ allExtensions, open }: { allExtensions: WorkflowExtension[]; open: boolean }) {+ const [search, setSearch] = useState('')+ const [collapsed, setCollapsed] = useState<Record<string, boolean>>({})+ const [width, setWidth] = useState(288)+ const dragging = useRef(false)+ const startX = useRef(0)+ const startW = useRef(0)++ useEffect(() => {+ const onMove = (e: MouseEvent) => {+ if (!dragging.current) return+ const delta = startX.current - e.clientX+ setWidth(() => Math.min(PANEL_MAX, Math.max(PANEL_MIN, startW.current + delta)))+ }+ const onUp = () => { dragging.current = false; document.body.style.cursor = '' }+ document.addEventListener('mousemove', onMove)+ document.addEventListener('mouseup', onUp)+ return () => {+ document.removeEventListener('mousemove', onMove)+ document.removeEventListener('mouseup', onUp)+ }+ }, [])++ const cols = width >= 580 ? 3 : width >= 370 ? 2 : 1+ const gridClass = cols === 3 ? 'grid-cols-3' : cols === 2 ? 'grid-cols-2' : 'grid-cols-1'+ const query = search.trim().toLowerCase()++ const toggleGroup = (id: string) => setCollapsed((c) => ({ ...c, [id]: !c[id] }))+ const isExpanded = (id: string, hasMatches: boolean) => (query && hasMatches) || !collapsed[id]++ // Base group+ const filteredBuiltinNodes = PANEL_BUILTIN_NODES.filter((n) => !query || n.label.toLowerCase().includes(query))+ const filteredBuiltinExts = allExtensions.filter((e) => e.builtin && (!query || e.name.toLowerCase().includes(query)))+ const baseCount = filteredBuiltinNodes.length + filteredBuiltinExts.length+ const baseVisible = !query || baseCount > 0++ // Non-builtin groups: grouped by extensionId+ const nonBuiltinMap = useMemo(() => {+ const map = new Map<string, { extensionName: string; nodes: WorkflowExtension[] }>()+ for (const ext of allExtensions) {+ if (ext.builtin) continue+ if (!map.has(ext.extensionId)) map.set(ext.extensionId, { extensionName: ext.extensionName, nodes: [] })+ map.get(ext.extensionId)!.nodes.push(ext)+ }+ return map+ }, [allExtensions])++ return (+ <div+ style={{ width: open ? width : 0 }}+ className="flex overflow-hidden border-l border-zinc-800 transition-[width] duration-300 ease-in-out shrink-0"+ >+ <div className="flex shrink-0" style={{ width }}>++ {/* Resize handle */}+ <div+ onMouseDown={(e) => {+ dragging.current = true; startX.current = e.clientX; startW.current = width+ document.body.style.cursor = 'col-resize'; e.preventDefault()+ }}+ className="w-1 shrink-0 hover:bg-zinc-600 active:bg-accent/60 cursor-col-resize transition-colors self-stretch"+ />++ <div className="flex flex-col flex-1 min-w-0 bg-zinc-950/30">++ {/* Header */}+ <div className="px-4 py-3 border-b border-zinc-800">+ <h2 className="text-xs font-semibold text-zinc-300">Extensions</h2>+ <p className="text-[10px] text-zinc-600 mt-0.5">Drag onto canvas</p>+ </div>++ {/* Search */}+ <div className="px-3 pt-2.5 pb-2 border-b border-zinc-800">+ <div className="flex items-center gap-2 px-2.5 py-1.5 rounded-lg bg-zinc-800/60 border border-zinc-700/60 focus-within:border-zinc-600">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-500 shrink-0">+ <circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>+ </svg>+ <input+ type="text"+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Search…"+ className="flex-1 bg-transparent text-[11px] text-zinc-200 placeholder-zinc-600 focus:outline-none min-w-0"+ />+ {search && (+ <button onClick={() => setSearch('')} className="text-zinc-600 hover:text-zinc-400 transition-colors">+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>+ </svg>+ </button>+ )}+ </div>+ </div>++ {/* Groups */}+ <div className="flex-1 overflow-y-auto px-3 py-2 flex flex-col gap-0.5">++ {/* ── Base group ── */}+ {baseVisible && (+ <div>+ <ExtGroupHeader+ title="Base"+ expanded={isExpanded('base', baseCount > 0)}+ onToggle={() => toggleGroup('base')}+ count={baseCount}+ />+ {isExpanded('base', baseCount > 0) && (+ <div className={`grid ${gridClass} gap-2 mt-1.5 mb-3`}>+ {filteredBuiltinNodes.map(({ type, label, color, icon }) => (+ <div+ key={type}+ draggable+ onDragStart={(e) => { e.dataTransfer.setData(DRAG_NODE_KEY, type); e.dataTransfer.effectAllowed = 'copy' }}+ className="flex flex-col gap-2 px-3 py-3 rounded-lg border border-zinc-800 bg-zinc-900 transition-colors cursor-grab hover:bg-zinc-800/60 hover:border-zinc-700 active:cursor-grabbing"+ >+ <div className="flex items-center gap-2">+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" className="shrink-0">{icon}</svg>+ <p className="text-xs font-semibold text-zinc-200 truncate">{label}</p>+ </div>+ </div>+ ))}+ {filteredBuiltinExts.map((ext) => (+ <div+ key={ext.id}+ draggable+ onDragStart={(e) => { e.dataTransfer.setData(DRAG_KEY, ext.id); e.dataTransfer.effectAllowed = 'copy' }}+ className="flex flex-col gap-2 px-3 py-3 rounded-lg border border-zinc-800 bg-zinc-900 transition-colors cursor-grab hover:bg-zinc-800/60 hover:border-zinc-700 active:cursor-grabbing"+ >+ <p className="text-xs font-semibold text-zinc-200 truncate">{ext.name}</p>+ <div className="flex items-center gap-1 mt-auto">+ <IoBadge type={ext.input} />+ <svg width="7" height="7" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-600 shrink-0">+ <path d="M5 12h14M13 6l6 6-6 6"/>+ </svg>+ <IoBadge type={ext.output} />+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ )}++ {/* ── Non-builtin extension groups ── */}+ {[...nonBuiltinMap.entries()].map(([extId, { extensionName, nodes }]) => {+ const filtered = nodes.filter((e) => !query || e.name.toLowerCase().includes(query))+ if (query && filtered.length === 0) return null+ const displayNodes = query ? filtered : nodes+ const expanded = isExpanded(extId, filtered.length > 0)++ return (+ <div key={extId}>+ <ExtGroupHeader+ title={extensionName}+ author={displayNodes[0]?.extensionAuthor}+ expanded={expanded}+ onToggle={() => toggleGroup(extId)}+ count={displayNodes.length}+ />+ {expanded && (+ <div className={`grid ${gridClass} gap-2 mt-1.5 mb-3`}>+ {displayNodes.map((ext) => (+ <div+ key={ext.id}+ draggable+ onDragStart={(e) => { e.dataTransfer.setData(DRAG_KEY, ext.id); e.dataTransfer.effectAllowed = 'copy' }}+ className="flex flex-col gap-2 px-3 py-3 rounded-lg border border-zinc-800 bg-zinc-900 transition-colors cursor-grab hover:bg-zinc-800/60 hover:border-zinc-700 active:cursor-grabbing"+ >+ <p className="text-xs font-semibold text-zinc-200 truncate">{ext.name}</p>+ {ext.description && cols === 1 && (+ <p className="text-[10px] text-zinc-500 leading-relaxed line-clamp-2">{ext.description}</p>+ )}+ <div className="flex items-center gap-1 mt-auto">+ <IoBadge type={ext.input} />+ <svg width="7" height="7" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-600 shrink-0">+ <path d="M5 12h14M13 6l6 6-6 6"/>+ </svg>+ <IoBadge type={ext.output} />+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ )+ })}++ {/* Empty state */}+ {query && baseCount === 0 && [...nonBuiltinMap.values()].every((g) => !g.nodes.some((e) => e.name.toLowerCase().includes(query))) && (+ <p className="text-[11px] text-zinc-600 text-center pt-4">No results for "{query}"</p>+ )}++ </div>+ </div>+ </div>+ </div>+ )+}++// ─── Page ─── toggle button icon ─────────────────────────────────────────────++function PanelToggleIcon({ open }: { open: boolean }) {+ return (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"+ style={{ transition: 'transform 0.3s ease', transform: open ? 'rotate(0deg)' : 'rotate(180deg)' }}>+ <rect x="3" y="3" width="18" height="18" rx="2"/>+ <line x1="15" y1="3" x2="15" y2="21"/>+ </svg>+ )+}++// ─── Node palette (Space to open) ────────────────────────────────────────────++const BUILTIN_NODES = [+ { type: 'imageNode', label: 'Image', color: '#38bdf8', description: 'Image input' },+ { type: 'textNode', label: 'Text', color: '#fbbf24', description: 'Text input' },+ { type: 'meshNode', label: 'Load 3D Mesh', color: '#a78bfa', description: 'Load a 3D mesh file or use current model' },+ { type: 'sceneNode', label: 'Load Scene', color: '#f472b6', description: 'Load and validate a workspace scene directory' },+ { type: 'outputNode', label: 'Add to Scene', color: '#a78bfa', description: 'Output node — adds the mesh to the 3D scene' },+ { type: 'previewNode', label: 'Preview Views', color: '#38bdf8', description: 'Displays multi-view image outputs in a 2×3 grid' },+ { type: 'imagePreviewNode', label: 'Preview Image', color: '#38bdf8', description: 'Displays a single image output in the workflow' },+ { type: 'waitNode', label: 'Wait', color: '#71717a', description: 'Pauses the workflow until you click Continue' },+ { type: 'whileNode', label: 'While', color: '#f59e0b', description: 'Container: wrap nodes to loop them N times or with Continue/Retry' },+ { type: 'forEachNode', label: 'For Each', color: '#38bdf8', description: 'Iterates a folder (image / text / mesh) alphabetically, one item per run of the downstream nodes' },+]++type PaletteItem =+ | { kind: 'node'; data: typeof BUILTIN_NODES[0] }+ | { kind: 'ext'; data: WorkflowExtension }++type PaletteGroup = {+ id: string+ title: string+ author?: string+ expanded: boolean+ items: Array<PaletteItem & { flatIdx: number }>+}++function NodePalette({+ allExtensions,+ onSelect,+ onClose,+}: {+ allExtensions: WorkflowExtension[]+ onSelect: (type: string, extensionId?: string) => void+ onClose: () => void+}) {+ const [query, setQuery] = useState('')+ const [collapsed, setCollapsed] = useState<Record<string, boolean>>({})+ const [activeIndex, setActiveIndex] = useState(0)+ const inputRef = useRef<HTMLInputElement>(null)++ const q = query.trim().toLowerCase()++ const nonBuiltinMap = useMemo(() => {+ const map = new Map<string, { extensionName: string; extensionAuthor: string; nodes: WorkflowExtension[] }>()+ for (const ext of allExtensions) {+ if (ext.builtin) continue+ if (!map.has(ext.extensionId)) map.set(ext.extensionId, { extensionName: ext.extensionName, extensionAuthor: ext.extensionAuthor, nodes: [] })+ map.get(ext.extensionId)!.nodes.push(ext)+ }+ return map+ }, [allExtensions])++ const toggleGroup = (id: string) => setCollapsed((c) => ({ ...c, [id]: !c[id] }))+ const isExpanded = (id: string, hasMatches: boolean) => (!!q && hasMatches) || !collapsed[id]++ // Build groups with pre-assigned flat indices (drives keyboard nav)+ const { groups, totalItems } = useMemo(() => {+ const groups: PaletteGroup[] = []+ let flatIdx = 0++ // Base group+ const filteredBuiltinNodes = BUILTIN_NODES.filter((n) => !q || n.label.toLowerCase().includes(q) || n.description.toLowerCase().includes(q))+ const filteredBuiltinExts = allExtensions.filter((e) => e.builtin && (!q || e.name.toLowerCase().includes(q) || (e.description ?? '').toLowerCase().includes(q)))+ const baseCount = filteredBuiltinNodes.length + filteredBuiltinExts.length+ const baseVisible = !q || baseCount > 0+ const baseExp = isExpanded('base', baseCount > 0)++ if (baseVisible) {+ const items: PaletteGroup['items'] = []+ if (baseExp) {+ filteredBuiltinNodes.forEach((n) => items.push({ kind: 'node', data: n, flatIdx: flatIdx++ }))+ filteredBuiltinExts.forEach((e) => items.push({ kind: 'ext', data: e, flatIdx: flatIdx++ }))+ }+ groups.push({ id: 'base', title: 'Base', expanded: baseExp, items })+ }++ // Non-builtin groups+ for (const [extId, { extensionName, extensionAuthor, nodes }] of nonBuiltinMap) {+ const filtered = nodes.filter((e) => !q || e.name.toLowerCase().includes(q) || (e.description ?? '').toLowerCase().includes(q))+ if (q && filtered.length === 0) continue+ const displayNodes = q ? filtered : nodes+ const expanded = isExpanded(extId, filtered.length > 0)+ const items: PaletteGroup['items'] = []+ if (expanded) displayNodes.forEach((e) => items.push({ kind: 'ext', data: e, flatIdx: flatIdx++ }))+ groups.push({ id: extId, title: extensionName, author: extensionAuthor || undefined, expanded, items })+ }++ return { groups, totalItems: flatIdx }+ // eslint-disable-next-line react-hooks/exhaustive-deps -- isExpanded only reads `collapsed`, already a dep+ }, [q, allExtensions, nonBuiltinMap, collapsed])++ useEffect(() => { setActiveIndex(0) }, [query])+ useEffect(() => { inputRef.current?.focus() }, [])++ // Flat list for Enter key (derived from groups)+ const flatItems = useMemo(() => groups.flatMap((g) => g.items), [groups])++ const handleKey = useCallback((e: React.KeyboardEvent) => {+ if (e.key === 'Escape') { onClose(); return }+ if (e.key === 'ArrowDown') { e.preventDefault(); setActiveIndex((i) => Math.min(i + 1, totalItems - 1)); return }+ if (e.key === 'ArrowUp') { e.preventDefault(); setActiveIndex((i) => Math.max(i - 1, 0)); return }+ if (e.key === 'Enter') {+ e.preventDefault()+ const item = flatItems[activeIndex]+ if (!item) return+ if (item.kind === 'node') onSelect(item.data.type)+ else onSelect('extensionNode', item.data.id)+ }+ }, [activeIndex, flatItems, totalItems, onSelect, onClose])++ return (+ <div className="fixed inset-0 z-50 flex items-start justify-center pt-[15vh] bg-black/40 backdrop-blur-[2px]" onMouseDown={onClose}>+ <div+ className="w-full max-w-md bg-zinc-900 border border-zinc-700 rounded-xl shadow-2xl overflow-hidden"+ onMouseDown={(e) => e.stopPropagation()}+ >+ {/* Search input */}+ <div className="flex items-center gap-3 px-4 py-3 border-b border-zinc-800">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-500 shrink-0">+ <circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>+ </svg>+ <input+ ref={inputRef}+ type="text"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ onKeyDown={handleKey}+ placeholder="Search nodes and extensions…"+ className="flex-1 bg-transparent text-sm text-zinc-100 placeholder-zinc-600 focus:outline-none"+ />+ <kbd className="text-[10px] text-zinc-600 bg-zinc-800 px-1.5 py-0.5 rounded border border-zinc-700">Esc</kbd>+ </div>++ {/* Groups */}+ <div className="max-h-96 overflow-y-auto py-1.5">+ {groups.map((group) => (+ <div key={group.id}>++ {/* Group header */}+ <button+ onClick={() => toggleGroup(group.id)}+ className="flex items-center gap-2 w-full px-4 py-2 group hover:bg-zinc-800/30 transition-colors"+ >+ <svg+ width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"+ className="text-zinc-600 group-hover:text-zinc-400 transition-colors shrink-0"+ style={{ transform: group.expanded ? 'rotate(90deg)' : 'rotate(0deg)', transition: 'transform 0.15s ease' }}+ >+ <polyline points="9 18 15 12 9 6"/>+ </svg>+ <div className="flex items-baseline gap-2 min-w-0">+ <span className="text-[11px] font-semibold text-zinc-400 group-hover:text-zinc-200 transition-colors">{group.title}</span>+ {group.author && <span className="text-[10px] text-zinc-600 truncate">{group.author}</span>}+ </div>+ <span className="ml-auto text-[10px] text-zinc-700 shrink-0">{group.items.length}</span>+ </button>++ {/* Group items */}+ {group.expanded && group.items.map((item) => {+ const isActive = activeIndex === item.flatIdx+ if (item.kind === 'node') {+ const n = item.data+ return (+ <button+ key={n.type}+ onMouseEnter={() => setActiveIndex(item.flatIdx)}+ onClick={() => onSelect(n.type)}+ className={`w-full flex items-center gap-3 px-4 pl-9 py-2.5 transition-colors ${isActive ? 'bg-zinc-800' : 'hover:bg-zinc-800/50'}`}+ >+ <span className="w-1.5 h-1.5 rounded-full shrink-0" style={{ background: n.color }} />+ <span className="text-sm text-zinc-200">{n.label}</span>+ <span className="text-xs text-zinc-600 ml-auto">{n.description}</span>+ </button>+ )+ }+ const e = item.data+ return (+ <button+ key={e.id}+ onMouseEnter={() => setActiveIndex(item.flatIdx)}+ onClick={() => onSelect('extensionNode', e.id)}+ className={`w-full flex items-center gap-3 px-4 pl-9 py-2.5 transition-colors ${isActive ? 'bg-zinc-800' : 'hover:bg-zinc-800/50'}`}+ >+ <span className="w-1.5 h-1.5 rounded-full shrink-0 bg-violet-400" />+ <span className="text-sm text-zinc-200">{e.name}</span>+ <div className="flex items-center gap-1 ml-auto shrink-0">+ <span className="text-[10px] text-zinc-500">{e.input}</span>+ <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-700">+ <path d="M5 12h14M13 6l6 6-6 6"/>+ </svg>+ <span className="text-[10px] text-zinc-500">{e.output}</span>+ </div>+ </button>+ )+ })}++ </div>+ ))}++ {totalItems === 0 && groups.length === 0 && (+ <p className="px-4 py-6 text-sm text-zinc-600 text-center">No results for "{query}"</p>+ )}+ </div>+ </div>+ </div>+ )+}++// ─── Help modal ───────────────────────────────────────────────────────────────++function HelpModal({ onClose }: { onClose: () => void }) {+ const [helperImg, setHelperImg] = useState<string | null>(null)+ useEffect(() => {+ window.electron.fs.readScreenshotDataUrl('workflow-helper.png').then(setHelperImg).catch(() => {})+ }, [])+ useEffect(() => {+ const onKey = (e: KeyboardEvent): void => { if (e.key === 'Escape') onClose() }+ window.addEventListener('keydown', onKey)+ return () => window.removeEventListener('keydown', onKey)+ }, [onClose])+ return createPortal(+ <div+ className="fixed inset-0 z-[9999] flex items-center justify-center bg-zinc-950/70 backdrop-blur-sm"+ onMouseDown={onClose}+ >+ <div+ className="w-[520px] max-h-[80vh] rounded-2xl bg-zinc-900 border border-zinc-700/60 shadow-2xl overflow-hidden flex flex-col"+ onMouseDown={(e) => e.stopPropagation()}+ >++ {/* Header */}+ <div className="sticky top-0 flex items-center justify-between px-5 py-4 border-b border-zinc-800 bg-zinc-900 z-10">+ <div className="flex items-center gap-2.5">+ <div className="w-7 h-7 rounded-lg bg-accent/10 border border-accent/20 flex items-center justify-center shrink-0">+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-accent-light">+ <circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/>+ </svg>+ </div>+ <h2 className="text-sm font-semibold text-zinc-100">How the workflow system works</h2>+ </div>+ <button onClick={onClose} className="p-1 rounded-lg text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800 transition-colors">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>+ </svg>+ </button>+ </div>++ <div className="px-5 py-5 flex flex-col gap-5 overflow-y-auto">++ {/* Concept */}+ <section className="flex flex-col gap-2">+ <h3 className="text-[11px] font-semibold uppercase tracking-wider text-zinc-500">Concept</h3>+ <p className="text-[12px] text-zinc-300 leading-relaxed">+ A workflow is a <span className="text-zinc-100 font-medium">directed graph of nodes</span>. Each node receives data from its inputs (left handle) and produces a result on its output (right handle). Data flows from left to right — you connect nodes by dragging from one handle to another.+ </p>+ </section>++ {/* Example screenshot */}+ {helperImg && (+ <div className="rounded-xl overflow-hidden border border-zinc-800">+ <img src={helperImg} alt="Basic workflow example" className="w-full object-cover" />+ <p className="px-3 py-2 text-[10px] text-zinc-500 bg-zinc-800/50 border-t border-zinc-800">+ Example — Image → AI model → Add to Scene+ </p>+ </div>+ )}++ {/* Node types */}+ <section className="flex flex-col gap-2.5">+ <h3 className="text-[11px] font-semibold uppercase tracking-wider text-zinc-500">Node types</h3>+ <div className="flex flex-col gap-2">++ <div className="flex items-start gap-3 p-3 rounded-xl bg-zinc-800/50 border border-zinc-700/40">+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-sky-500/30 bg-sky-500/10 text-sky-400 shrink-0 mt-0.5">image</span>+ <div>+ <p className="text-[11px] font-medium text-zinc-200">Image</p>+ <p className="text-[11px] text-zinc-500 mt-0.5 leading-relaxed">Source node. Pick a local image file — it becomes the input of the first processing node.</p>+ </div>+ </div>++ <div className="flex items-start gap-3 p-3 rounded-xl bg-zinc-800/50 border border-zinc-700/40">+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-amber-500/30 bg-amber-500/10 text-amber-400 shrink-0 mt-0.5">text</span>+ <div>+ <p className="text-[11px] font-medium text-zinc-200">Text</p>+ <p className="text-[11px] text-zinc-500 mt-0.5 leading-relaxed">Source node. Pass a text prompt to extensions that accept text input.</p>+ </div>+ </div>++ <div className="flex items-start gap-3 p-3 rounded-xl bg-zinc-800/50 border border-zinc-700/40">+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-violet-500/30 bg-violet-500/10 text-violet-400 shrink-0 mt-0.5">mesh</span>+ <div>+ <p className="text-[11px] font-medium text-zinc-200">Load 3D Mesh</p>+ <p className="text-[11px] text-zinc-500 mt-0.5 leading-relaxed">Source node. Load a .glb, .obj, .stl, .ply or .splat file from disk, or use the model currently loaded in the 3D viewer.</p>+ </div>+ </div>++ <div className="flex items-start gap-3 p-3 rounded-xl bg-zinc-800/50 border border-zinc-700/40">+ <div className="flex gap-1 shrink-0 mt-0.5">+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-sky-500/30 bg-sky-500/10 text-sky-400">image</span>+ <span className="text-zinc-600 text-[9px] flex items-center">→</span>+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-violet-500/30 bg-violet-500/10 text-violet-400">mesh</span>+ </div>+ <div>+ <p className="text-[11px] font-medium text-zinc-200">Model extension <span className="text-[10px] font-normal text-zinc-500">(AI generator)</span></p>+ <p className="text-[11px] text-zinc-500 mt-0.5 leading-relaxed">Runs a locally installed AI model to convert an image into a 3D mesh. Requires the model weights to be downloaded first from the <span className="text-zinc-300 font-medium">Extensions</span> page.</p>+ </div>+ </div>++ <div className="flex items-start gap-3 p-3 rounded-xl bg-zinc-800/50 border border-zinc-700/40">+ <div className="flex gap-1 shrink-0 mt-0.5">+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-violet-500/30 bg-violet-500/10 text-violet-400">mesh</span>+ <span className="text-zinc-600 text-[9px] flex items-center">→</span>+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-violet-500/30 bg-violet-500/10 text-violet-400">mesh</span>+ </div>+ <div>+ <p className="text-[11px] font-medium text-zinc-200">Process extension <span className="text-[10px] font-normal text-zinc-500">(mesh processor)</span></p>+ <p className="text-[11px] text-zinc-500 mt-0.5 leading-relaxed">Transforms a mesh — examples: Optimize Mesh (polygon reduction), Export Mesh (save to file). No GPU required.</p>+ </div>+ </div>++ <div className="flex items-start gap-3 p-3 rounded-xl bg-zinc-800/50 border border-zinc-700/40">+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-violet-500/30 bg-violet-500/10 text-violet-400 shrink-0 mt-0.5">scene</span>+ <div>+ <p className="text-[11px] font-medium text-zinc-200">Add to Scene</p>+ <p className="text-[11px] text-zinc-500 mt-0.5 leading-relaxed">Terminal node. Receives the final mesh and loads it directly into the 3D viewer when the workflow completes.</p>+ </div>+ </div>++ </div>+ </section>++ {/* Tips */}+ <section className="flex flex-col gap-2">+ <h3 className="text-[11px] font-semibold uppercase tracking-wider text-zinc-500">Tips</h3>+ <ul className="flex flex-col gap-1.5">+ {[+ ['Space', 'Open the node palette on the canvas'],+ ['Eye icon', 'Pin a node to the Generate page side panel'],+ ['Drag handle → canvas', 'Auto-opens the palette to connect a new node'],+ ['Right-click a link', 'Delete the connection between two nodes'],+ ['Run', 'Saves & executes the workflow, result goes to the 3D scene'],+ ].map(([key, desc]) => (+ <li key={key} className="flex items-start gap-2 text-[11px] text-zinc-400">+ <span className="px-1.5 py-px rounded bg-zinc-800 border border-zinc-700 text-zinc-300 font-medium text-[10px] shrink-0 mt-px">{key}</span>+ <span>{desc}</span>+ </li>+ ))}+ </ul>+ </section>++ </div>+ </div>+ </div>,+ document.body+ )+}++// ─── Connection type helpers ──────────────────────────────────────────────────++function getNodeOutputType(node: Node | undefined, allExts: WorkflowExtension[]): string | undefined {+ if (!node) return undefined+ if (node.type === 'imageNode') return 'image'+ if (node.type === 'meshNode') return 'mesh'+ if (node.type === 'sceneNode') return 'scene'+ if (node.type === 'textNode') return 'text'+ if (node.type === 'imagePreviewNode') return 'image'+ return allExts.find((e) => e.id === (node.data as WFNodeData)?.extensionId)?.output+}++function getNodeInputType(+ node: Node | undefined,+ targetHandle: string | null | undefined,+ allExts: WorkflowExtension[],+): string | undefined {+ if (!node) return undefined+ if (node.type === 'outputNode') return 'mesh'+ if (node.type === 'previewNode') return 'image'+ if (node.type === 'imagePreviewNode') return 'image'+ const ext = allExts.find((e) => e.id === (node.data as WFNodeData)?.extensionId)+ if (ext?.inputs && ext.inputs.length > 1 && targetHandle) {+ const idx = parseInt(targetHandle.replace('input-', ''), 10)+ return ext.inputs[isNaN(idx) ? 0 : idx] ?? ext.input+ }+ return ext?.input+}++// ─── Workflow canvas (inner, requires ReactFlowProvider) ──────────────────────++function WorkflowCanvasInner({+ workflow, allExtensions, onSave, panelOpen, onTogglePanel, onOpen, onImport,+}: {+ workflow: Workflow+ allExtensions: WorkflowExtension[]+ onSave: (w: Workflow) => Promise<{ success: boolean; error?: string }>+ panelOpen: boolean+ onTogglePanel: () => void+ onOpen: () => void+ onImport: () => void+}) {+ const { screenToFlowPosition, getNode } = useReactFlow()+ const { runState, run: runWorkflow, cancel } = useWorkflowRunStore()+ const currentMeshUrl = useAppStore((s) => s.currentJob?.outputUrl)+ const showToast = useAppStore((s) => s.showToast)+ const isRunning = runState.status === 'running' || runState.status === 'paused'++ const [nodes, setNodes, onNodesChange] = useNodesState(workflow.nodes as Node[])+ const [edges, setEdges, onEdgesChange] = useEdgesState(workflow.edges as Edge[])+ const [paletteOpen, setPaletteOpen] = useState(false)+ const [helpOpen, setHelpOpen] = useState(false)++ // Pending connection: set when user drags a handle and releases on empty canvas+ const pendingConnectionRef = useRef<OnConnectStartParams | null>(null)+ const connectionCompletedRef = useRef(false)+ const [pendingDropPos, setPendingDropPos] = useState<{ x: number; y: number } | null>(null)++ const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null)+ const flushSaveRef = useRef<(() => void) | null>(null)+ const autosaveMountedRef = useRef(false)+ const preflightToastTimer = useRef<ReturnType<typeof setTimeout> | null>(null)+ const didMountRef = useRef(false)++ // ─── Undo / Redo ──────────────────────────────────────────────────────────+ type Snapshot = { nodes: Node[]; edges: Edge[] }+ const historyRef = useRef<Snapshot[]>([{ nodes: workflow.nodes as Node[], edges: workflow.edges as Edge[] }])+ const histIdxRef = useRef(0)+ const [histIdx, setHistIdx] = useState(0)+ const skipPushRef = useRef(true) // skip the initial autosave-triggered push+ const lastSavedAtRef = useRef<string>(workflow.updatedAt)++ // Re-sync when workflow switches+ useEffect(() => {+ setNodes(workflow.nodes as Node[])+ setEdges(workflow.edges as Edge[])+ historyRef.current = [{ nodes: workflow.nodes as Node[], edges: workflow.edges as Edge[] }]+ histIdxRef.current = 0+ setHistIdx(0)+ skipPushRef.current = true+ // eslint-disable-next-line react-hooks/exhaustive-deps -- re-sync only when the workflow switches; adding nodes/edges would reset the editor on every change+ }, [workflow.id])++ // Re-sync when Generate tab (or another external source) saves param changes+ useEffect(() => {+ if (workflow.updatedAt === lastSavedAtRef.current) return+ setNodes(workflow.nodes as Node[])+ setEdges(workflow.edges as Edge[])+ skipPushRef.current = true+ lastSavedAtRef.current = workflow.updatedAt+ // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on updatedAt only; adding nodes/edges would resync on every local edit+ }, [workflow.updatedAt])++ // Persist and claim the echo so the sync effect above does not treat our own+ // write as an external change. The claim is optimistic — the store is updated+ // before save() resolves — and is rolled back when the write fails, so a failed+ // save never silently replaces the canvas with the last persisted version.+ const saveAndClaim = useCallback((updated: Workflow) => {+ const prevSavedAt = lastSavedAtRef.current+ lastSavedAtRef.current = updated.updatedAt+ void onSave(updated).then((res) => {+ if (!res.success) lastSavedAtRef.current = prevSavedAt+ })+ }, [onSave])++ // Auto-save + history push debounced.+ useEffect(() => {+ if (saveTimer.current) clearTimeout(saveTimer.current)++ const flush = (pushHistory: boolean) => {+ saveTimer.current = null+ flushSaveRef.current = null+ saveAndClaim({+ ...workflow,+ nodes: nodes as WFNode[],+ edges: edges as WFEdge[],+ updatedAt: new Date().toISOString(),+ })++ if (pushHistory && !skipPushRef.current) {+ const next = historyRef.current.slice(0, histIdxRef.current + 1)+ next.push({ nodes, edges })+ if (next.length > 50) next.shift()+ historyRef.current = next+ const newIdx = next.length - 1+ histIdxRef.current = newIdx+ setHistIdx(newIdx)+ }+ skipPushRef.current = false+ }++ // Only arm the unmount flush once the user has actually edited something,+ // so merely opening and leaving the tab does not trigger a pointless write.+ if (autosaveMountedRef.current) flushSaveRef.current = () => flush(false)+ else autosaveMountedRef.current = true+ saveTimer.current = setTimeout(() => flush(true), 500)+ // No cleanup: the next edit clears the timer above, and the unmount effect+ // below flushes a pending save so switching tabs never drops an edit.+ // eslint-disable-next-line react-hooks/exhaustive-deps -- debounce on editable state; latest workflow/onSave read in the timeout+ }, [nodes, edges])++ // Switching tabs unmounts this page — flush the pending autosave instead of+ // dropping it, otherwise an edit made within the debounce window is lost.+ useEffect(() => () => {+ if (saveTimer.current) clearTimeout(saveTimer.current)+ flushSaveRef.current?.()+ }, [])++ const preflightIssues = useMemo(() => {+ const draft: Workflow = {+ ...workflow,+ nodes: nodes as WFNode[],+ edges: edges as WFEdge[],+ updatedAt: workflow.updatedAt,+ }+ return validateWorkflowPreflight(draft, allExtensions, { currentMeshUrl })+ }, [workflow, nodes, edges, allExtensions, currentMeshUrl])++ useEffect(() => {+ if (!didMountRef.current) {+ didMountRef.current = true+ return+ }+ if (preflightToastTimer.current) clearTimeout(preflightToastTimer.current)+ if (preflightIssues.length === 0) return+ preflightToastTimer.current = setTimeout(() => {+ showToast(preflightIssues[0].message)+ }, 250)+ return () => {+ if (preflightToastTimer.current) clearTimeout(preflightToastTimer.current)+ }+ }, [preflightIssues, showToast])++ const undo = useCallback(() => {+ const idx = histIdxRef.current+ if (idx <= 0) return+ const newIdx = idx - 1+ const snap = historyRef.current[newIdx]+ skipPushRef.current = true+ setNodes(snap.nodes)+ setEdges(snap.edges)+ histIdxRef.current = newIdx+ setHistIdx(newIdx)+ }, [setNodes, setEdges])++ const redo = useCallback(() => {+ const idx = histIdxRef.current+ if (idx >= historyRef.current.length - 1) return+ const newIdx = idx + 1+ const snap = historyRef.current[newIdx]+ skipPushRef.current = true+ setNodes(snap.nodes)+ setEdges(snap.edges)+ histIdxRef.current = newIdx+ setHistIdx(newIdx)+ }, [setNodes, setEdges])++ const canUndo = histIdx > 0+ const canRedo = histIdx < historyRef.current.length - 1++ const isValidConnection = useCallback((connection: Edge | Connection) => {+ const srcType = getNodeOutputType(getNode(connection.source) as Node, allExtensions)+ const tgtType = getNodeInputType(getNode(connection.target) as Node, connection.targetHandle, allExtensions)+ if (srcType && tgtType && srcType !== tgtType) return false // type mismatch (unknown types allowed)+ // Reject connections that would create a cycle: if the target can already+ // reach the source, adding source→target closes a loop.+ if (connection.source && connection.target) {+ const stack = [connection.target]+ const seen = new Set<string>()+ while (stack.length > 0) {+ const id = stack.pop()!+ if (id === connection.source) return false+ if (seen.has(id)) continue+ seen.add(id)+ for (const e of edges) if (e.source === id) stack.push(e.target)+ }+ }+ return true+ }, [getNode, allExtensions, edges])++ const onConnectStart = useCallback((_: MouseEvent | TouchEvent, params: OnConnectStartParams) => {+ pendingConnectionRef.current = params+ connectionCompletedRef.current = false+ }, [])++ const onConnect = useCallback((params: Connection) => {+ connectionCompletedRef.current = true+ setEdges((eds) => addEdge({ ...params, ...DEFAULT_EDGE_OPTS }, eds))+ }, [setEdges])++ const onConnectEnd = useCallback((event: MouseEvent | TouchEvent) => {+ if (connectionCompletedRef.current || !pendingConnectionRef.current?.nodeId) {+ pendingConnectionRef.current = null+ return+ }+ // Dropped on empty canvas — or inside a While body — opens the palette. The+ // While is a giant node, so don't treat its empty body as "dropped on a node";+ // bail only on a real node or a handle.+ const target = event.target as Element+ const nodeEl = target.closest('.react-flow__node')+ const onContainer = !!nodeEl && [...CONTAINER_TYPES].some((t) => nodeEl.classList.contains(`react-flow__node-${t}`))+ if (target.closest('.react-flow__handle') || (nodeEl && !onContainer)) {+ pendingConnectionRef.current = null+ return+ }+ const clientX = 'clientX' in event ? event.clientX : (event as TouchEvent).changedTouches[0].clientX+ const clientY = 'clientY' in event ? event.clientY : (event as TouchEvent).changedTouches[0].clientY+ setPendingDropPos({ x: clientX, y: clientY })+ setPaletteOpen(true)+ }, [])++ const onDragOver = useCallback((e: React.DragEvent) => {+ e.preventDefault(); e.dataTransfer.dropEffect = 'copy'+ }, [])++ const onDrop = useCallback((e: React.DragEvent) => {+ e.preventDefault()+ const position = screenToFlowPosition({ x: e.clientX, y: e.clientY })++ const nodeType = e.dataTransfer.getData(DRAG_NODE_KEY)+ if (nodeType) {+ const isContainer = isContainerType(nodeType)+ setNodes((nds) => {+ const parent = isContainer ? undefined : findWhileContainerAt(nds, position)+ const node: Node = {+ id: newId(), type: nodeType,+ position: parent ? { x: position.x - parent.position.x, y: position.y - parent.position.y } : position,+ data: { enabled: true, params: {} } as WFNodeData,+ ...(isContainer ? { style: { width: 420, height: 240 }, width: 420, height: 240 } : {}),+ ...(parent ? { parentId: parent.id } : {}),+ }+ // Containers must sit before their future children in the array → prepend.+ return isContainer ? [node, ...nds] : [...nds, node]+ })+ return+ }++ const extensionId = e.dataTransfer.getData(DRAG_KEY)+ if (!extensionId) return+ setNodes((nds) => {+ const parent = findWhileContainerAt(nds, position)+ const node: Node = {+ id: newId(), type: 'extensionNode',+ position: parent ? { x: position.x - parent.position.x, y: position.y - parent.position.y } : position,+ data: { extensionId, enabled: true, params: {} } as WFNodeData,+ ...(parent ? { parentId: parent.id } : {}),+ }+ return [...nds, node]+ })+ }, [screenToFlowPosition, setNodes])++ // Keyboard shortcuts (Space, Ctrl+Z, Ctrl+Y / Ctrl+Shift+Z)+ useEffect(() => {+ const onKeyDown = (e: KeyboardEvent) => {+ const tag = (e.target as HTMLElement).tagName+ if (tag === 'INPUT' || tag === 'TEXTAREA') return+ if (e.code === 'Space') {+ e.preventDefault()+ setPaletteOpen(true)+ return+ }+ if ((e.ctrlKey || e.metaKey) && !e.shiftKey && e.key === 'z') {+ e.preventDefault()+ undo()+ return+ }+ if ((e.ctrlKey || e.metaKey) && (e.key === 'y' || (e.shiftKey && e.key === 'z'))) {+ e.preventDefault()+ redo()+ }+ }+ window.addEventListener('keydown', onKeyDown)+ return () => window.removeEventListener('keydown', onKeyDown)+ }, [undo, redo])++ // Copy/paste selected nodes (Ctrl+C / Ctrl+V) — works across workflow tabs+ useEffect(() => {+ const onKeyDown = (e: KeyboardEvent) => {+ const tag = (e.target as HTMLElement).tagName+ if (tag === 'INPUT' || tag === 'TEXTAREA') return+ if (!(e.ctrlKey || e.metaKey) || e.shiftKey) return++ if (e.key === 'c') {+ const selected = nodes.filter((n) => n.selected)+ if (selected.length === 0) return+ const selIds = new Set(selected.map((n) => n.id))+ const copied = selected.map((n) => {+ // Child copied without its container → detach to absolute coordinates+ if (n.parentId && !selIds.has(n.parentId)) {+ const parent = nodes.find((p) => p.id === n.parentId)+ return {+ ...structuredClone(n),+ parentId: undefined,+ position: { x: n.position.x + (parent?.position.x ?? 0), y: n.position.y + (parent?.position.y ?? 0) },+ }+ }+ return structuredClone(n)+ })+ const copiedEdges = edges+ .filter((ed) => selIds.has(ed.source) && selIds.has(ed.target))+ .map((ed) => structuredClone(ed))+ _nodeClipboard.current = { nodes: copied, edges: copiedEdges, pastes: 0 }+ return+ }++ if (e.key === 'v') {+ const clip = _nodeClipboard.current+ if (!clip || clip.nodes.length === 0) return+ clip.pastes += 1+ const offset = 32 * clip.pastes+ const idMap = new Map(clip.nodes.map((n) => [n.id, newId()]))+ const pasted: Node[] = clip.nodes.map((n) => {+ const keepParent = n.parentId != null && idMap.has(n.parentId)+ return {+ ...structuredClone(n),+ id: idMap.get(n.id)!,+ parentId: keepParent ? idMap.get(n.parentId!) : undefined,+ // Children keep their parent-relative position; top-level nodes shift+ // a bit more on every paste so repeated pastes don't stack.+ position: keepParent ? n.position : { x: n.position.x + offset, y: n.position.y + offset },+ selected: true,+ }+ })+ const pastedEdges: Edge[] = clip.edges.map((ed) => ({+ ...structuredClone(ed),+ id: `e-${newId()}`,+ source: idMap.get(ed.source)!,+ target: idMap.get(ed.target)!,+ }))+ setNodes((nds) => [...nds.map((n) => ({ ...n, selected: false })), ...pasted])+ setEdges((eds) => [...eds, ...pastedEdges])+ }+ }+ window.addEventListener('keydown', onKeyDown)+ return () => window.removeEventListener('keydown', onKeyDown)+ }, [nodes, edges, setNodes, setEdges])++ const addNodeFromPalette = useCallback((type: string, extensionId?: string) => {+ const position = screenToFlowPosition(+ pendingDropPos ?? { x: window.innerWidth / 2, y: window.innerHeight / 2 }+ )+ const newNodeId = newId()+ const isContainer = isContainerType(type)+ setNodes((nds) => {+ const parent = isContainer ? undefined : findWhileContainerAt(nds, position)+ const node: Node = {+ id: newNodeId, type,+ position: parent ? { x: position.x - parent.position.x, y: position.y - parent.position.y } : position,+ data: { extensionId, enabled: true, params: {} } as WFNodeData,+ ...(isContainer ? { style: { width: 420, height: 240 }, width: 420, height: 240 } : {}),+ ...(parent ? { parentId: parent.id } : {}),+ }+ // Containers must sit before their future children in the array → prepend.+ return isContainer ? [node, ...nds] : [...nds, node]+ })++ // If palette was opened from a connection drag, wire the edge automatically.+ // ExtensionNodes use id'd handles (input-0 / output), not the default null+ // handle, so the new node's side must reference them or React Flow can't place+ // the edge ("Couldn't create edge for target handle id: null").+ const pending = pendingConnectionRef.current+ if (pending?.nodeId) {+ const isSource = pending.handleType === 'source'+ const isExt = type === 'extensionNode'+ // Skip wiring when the new node can't take the connection: a source-only node+ // (Image/Text/Mesh) as target, or a sink-only node (Add to Scene/Preview) as+ // source — those have no matching handle and would orphan the edge.+ const canWire = isSource ? !NODE_TYPES_WITHOUT_TARGET.has(type) : !NODE_TYPES_WITHOUT_SOURCE.has(type)+ if (canWire) {+ const edge = isSource+ ? { id: newId(), source: pending.nodeId, sourceHandle: pending.handleId ?? undefined, target: newNodeId, targetHandle: isExt ? 'input-0' : undefined }+ : { id: newId(), source: newNodeId, sourceHandle: isExt ? 'output' : undefined, target: pending.nodeId, targetHandle: pending.handleId ?? undefined }+ setEdges((eds) => addEdge({ ...edge, ...DEFAULT_EDGE_OPTS }, eds))+ }+ }++ pendingConnectionRef.current = null+ setPendingDropPos(null)+ setPaletteOpen(false)+ }, [screenToFlowPosition, setNodes, setEdges, pendingDropPos])++ // When a While container is deleted (button or keyboard), detach its children+ // to absolute coordinates so they don't get orphaned to the canvas origin.+ const onNodesDelete = useCallback((deleted: Node[]) => {+ const removedContainers = deleted.filter((n) => isContainerType(n.type))+ if (removedContainers.length === 0) return+ setNodes((nds) => nds.map((n) => {+ const container = removedContainers.find((c) => c.id === n.parentId)+ if (!container) return n+ const { parentId: _p, extent: _ext, ...rest } = n+ return { ...rest, position: { x: container.position.x + n.position.x, y: container.position.y + n.position.y } }+ }))+ }, [setNodes])++ // When a node is dropped, attach/detach it to a While container based on overlap.+ // Children get a parentId + parent-relative position (no extent, so they can be dragged back out).+ const onNodeDragStop = useCallback((_e: unknown, dragged: Node) => {+ if (isContainerType(dragged.type)) return+ setNodes((nds) => {+ const containers = nds.filter((n) => isContainerType(n.type))+ if (containers.length === 0 && !dragged.parentId) return nds++ const parent = dragged.parentId ? nds.find((n) => n.id === dragged.parentId) : undefined+ const absX = (parent?.position.x ?? 0) + dragged.position.x+ const absY = (parent?.position.y ?? 0) + dragged.position.y+ const w = dragged.measured?.width ?? dragged.width ?? 200+ const h = dragged.measured?.height ?? dragged.height ?? 80+ const cx = absX + w / 2+ const cy = absY + h / 2++ const container = containers.find((g) => {+ const gw = (g.measured?.width ?? g.width ?? (g.style?.width as number)) || 0+ const gh = (g.measured?.height ?? g.height ?? (g.style?.height as number)) || 0+ return cx >= g.position.x && cx <= g.position.x + gw && cy >= g.position.y && cy <= g.position.y + gh+ })++ const newParentId = container?.id+ if (newParentId === dragged.parentId) return nds // no change++ const next: Node[] = nds.map((n) => {+ if (n.id !== dragged.id) return n+ if (container) {+ // parentId (no extent) → child moves with the container but can still be dragged out+ return { ...n, parentId: container.id,+ position: { x: absX - container.position.x, y: absY - container.position.y } }+ }+ const { parentId: _p, extent: _ext, ...rest } = n // detach+ return { ...rest, position: { x: absX, y: absY } }+ })++ // ReactFlow requires the parent to appear before its child in the array.+ if (newParentId) {+ const cIdx = next.findIndex((n) => n.id === dragged.id)+ const pIdx = next.findIndex((n) => n.id === newParentId)+ if (pIdx > cIdx) {+ const [child] = next.splice(cIdx, 1)+ next.splice(next.findIndex((n) => n.id === newParentId) + 1, 0, child)+ }+ }+ return next+ })+ }, [setNodes])++ const handleRun = useCallback(() => {+ if (isRunning) { cancel(); return }+ if (preflightIssues.length > 0) {+ showToast(preflightIssues[0].message)+ return+ }+ // Drop the pending debounce — this save supersedes it.+ if (saveTimer.current) { clearTimeout(saveTimer.current); saveTimer.current = null; flushSaveRef.current = null }+ const wf: Workflow = { ...workflow, nodes: nodes as WFNode[], edges: edges as WFEdge[], updatedAt: new Date().toISOString() }+ saveAndClaim(wf)+ runWorkflow(wf, allExtensions)+ }, [workflow, nodes, edges, saveAndClaim, allExtensions, isRunning, runWorkflow, cancel, preflightIssues, showToast])++ return (+ <div className="flex flex-col flex-1 overflow-hidden">++ {paletteOpen && (+ <NodePalette+ allExtensions={allExtensions}+ onSelect={addNodeFromPalette}+ onClose={() => {+ pendingConnectionRef.current = null+ setPendingDropPos(null)+ setPaletteOpen(false)+ }}+ />+ )}++ {/* Header toolbar */}+ <div className="flex items-center gap-2 px-5 py-3 border-b border-zinc-800 shrink-0 bg-zinc-950/20">++ {/* Open */}+ <button+ onClick={onOpen}+ title="Open workflow"+ className="flex items-center gap-2 px-3.5 py-2 rounded-md text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 border border-zinc-800 hover:border-zinc-700 transition-colors shrink-0"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>+ </svg>+ <span className="text-sm font-medium">Open</span>+ </button>++ {/* Import */}+ <button+ onClick={onImport}+ title="Import workflow"+ className="flex items-center gap-2 px-3.5 py-2 rounded-md text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 border border-zinc-800 hover:border-zinc-700 transition-colors shrink-0"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>+ <polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/>+ </svg>+ <span className="text-sm font-medium">Import</span>+ </button>++ <div className="w-px h-6 bg-zinc-800 mx-0.5 shrink-0" />++ {/* Undo */}+ <button+ onClick={undo}+ disabled={!canUndo}+ title="Undo (Ctrl+Z)"+ className="p-2.5 rounded-lg text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800 border border-zinc-800 hover:border-zinc-700 transition-colors disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent disabled:hover:text-zinc-500 disabled:hover:border-zinc-800"+ >+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M3 7v6h6"/><path d="M3 13A9 9 0 1 0 5.7 6.3"/>+ </svg>+ </button>++ {/* Redo */}+ <button+ onClick={redo}+ disabled={!canRedo}+ title="Redo (Ctrl+Y)"+ className="p-2.5 rounded-lg text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800 border border-zinc-800 hover:border-zinc-700 transition-colors disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent disabled:hover:text-zinc-500 disabled:hover:border-zinc-800"+ >+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M21 7v6h-6"/><path d="M21 13A9 9 0 1 1 18.3 6.3"/>+ </svg>+ </button>++ <div className="flex-1" />++ <div className="flex items-center gap-1">+ {/* Run / Stop */}+ <button+ onClick={handleRun}+ className={`flex items-center gap-2 px-4 py-2 rounded-lg border transition-colors+ ${isRunning+ ? 'bg-red-500/10 border-red-500/30 text-red-400 hover:bg-red-500/20 hover:border-red-500/50'+ : 'bg-accent/10 border-accent/30 text-accent-light hover:bg-accent/20 hover:border-accent/50'}`}+ >+ {isRunning ? (+ <>+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="6" width="12" height="12" rx="1"/></svg>+ <span className="text-sm font-semibold">Stop</span>+ </>+ ) : (+ <>+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>+ <span className="text-sm font-semibold">Run</span>+ </>+ )}+ </button>++ {/* Progress indicator */}+ {isRunning && (+ <div className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-zinc-800/60 border border-zinc-700/50 max-w-[180px]">+ <svg className="animate-spin text-accent shrink-0" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <path d="M21 12a9 9 0 1 1-6.219-8.56"/>+ </svg>+ <span className="text-[11px] text-zinc-400 truncate">{runState.blockStep}</span>+ </div>+ )}++ {/* Help */}+ <button+ onClick={() => setHelpOpen(true)}+ title="How workflows work"+ className="p-2.5 rounded-lg text-zinc-600 hover:text-zinc-200 hover:bg-zinc-800 border border-zinc-800 hover:border-zinc-700 transition-colors font-semibold text-sm w-[34px] h-[34px] flex items-center justify-center"+ >+ ?+ </button>+ </div>+ </div>++ {helpOpen && <HelpModal onClose={() => setHelpOpen(false)} />}++ {/* React Flow canvas */}+ <div className="flex-1 relative" onDragOver={onDragOver} onDrop={onDrop}>++ {/* No model node warning */}+ {!nodes.some((n) => n.type === 'extensionNode' && allExtensions.find((e) => e.id === (n.data as WFNodeData).extensionId && e.type === 'model')) && (+ <div className="absolute top-3 left-1/2 -translate-x-1/2 z-10 pointer-events-none">+ <div className="flex items-center gap-1.5 px-2.5 py-1 rounded-md bg-accent/10 border border-accent/20 text-accent-light whitespace-nowrap">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor" className="shrink-0">+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>+ </svg>+ <span className="text-[10px] font-medium">No AI model node in this workflow — add one from the extensions panel to generate a 3D mesh.</span>+ </div>+ </div>+ )}++ {/* Floating panel toggle — over the canvas, below the header */}+ <button+ onClick={onTogglePanel}+ title={panelOpen ? 'Close extensions panel' : 'Open extensions panel'}+ className="absolute top-3 right-3 z-10 p-2 rounded-lg+ bg-zinc-800/90 border border-zinc-700 shadow-md+ text-zinc-400 hover:text-zinc-100 hover:bg-zinc-700 hover:border-zinc-600+ transition-colors backdrop-blur-sm"+ >+ <PanelToggleIcon open={panelOpen} />+ </button>++ <ReactFlow+ nodes={nodes}+ edges={edges}+ nodeTypes={NODE_TYPES}+ edgeTypes={EDGE_TYPES}+ onNodesChange={onNodesChange}+ onNodeDragStop={onNodeDragStop}+ onNodesDelete={onNodesDelete}+ onEdgesChange={onEdgesChange}+ onConnectStart={onConnectStart}+ onConnect={onConnect}+ isValidConnection={isValidConnection}+ onConnectEnd={onConnectEnd}+ onEdgeContextMenu={(e, edge) => { e.preventDefault(); setEdges((eds) => eds.filter((ed) => ed.id !== edge.id)) }}+ defaultEdgeOptions={DEFAULT_EDGE_OPTS}+ deleteKeyCode="Delete"+ connectionLineStyle={{ stroke: '#71717a', strokeWidth: 1.5 }}+ fitView+ fitViewOptions={{ padding: 0.3 }}+ proOptions={{ hideAttribution: true }}+ className="bg-[#0f0f10]"+ >+ <Background color="#27272a" gap={24} size={1} />+ </ReactFlow>+ </div>+ </div>+ )+}++// ─── Mini graph preview ───────────────────────────────────────────────────────+// Schematic thumbnail of a workflow's graph for the Open popup cards — plain+// SVG built from stored node positions, no React Flow instance needed.++// Node tint by role, echoing the real canvas: inputs green, processing violet,+// outputs blue, everything else neutral.+const MINI_NODE_TINTS: Record<string, { fill: string; stroke: string }> = {+ imageNode: { fill: 'rgba(52,211,153,0.22)', stroke: '#34d399' },+ textNode: { fill: 'rgba(52,211,153,0.22)', stroke: '#34d399' },+ meshNode: { fill: 'rgba(52,211,153,0.22)', stroke: '#34d399' },+ sceneNode: { fill: 'rgba(244,114,182,0.22)', stroke: '#f472b6' },+ extensionNode: { fill: 'rgba(167,139,250,0.24)', stroke: '#a78bfa' },+ outputNode: { fill: 'rgba(56,189,248,0.22)', stroke: '#38bdf8' },+ previewNode: { fill: 'rgba(56,189,248,0.22)', stroke: '#38bdf8' },+}+const MINI_NODE_DEFAULT_TINT = { fill: 'rgba(113,113,122,0.25)', stroke: '#71717a' }++function WorkflowMiniPreview({ wf }: { wf: Workflow }): JSX.Element {+ const VIEW_W = 200+ const VIEW_H = 88+ const PAD = 12++ if (wf.nodes.length === 0) {+ return (+ <div className="flex items-center justify-center w-full h-full text-zinc-700">+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">+ <rect x="3" y="3" width="7" height="5" rx="1"/><rect x="14" y="16" width="7" height="5" rx="1"/>+ <path d="M10 5.5h5a2 2 0 0 1 2 2V16"/>+ </svg>+ </div>+ )+ }++ // Children of a container store positions relative to their parent+ const byId = new Map(wf.nodes.map((n) => [n.id, n]))+ const boxes = wf.nodes.map((n) => {+ const parent = n.parentId ? byId.get(n.parentId) : undefined+ return {+ id: n.id,+ type: n.type,+ x: n.position.x + (parent?.position.x ?? 0),+ y: n.position.y + (parent?.position.y ?? 0),+ w: n.width ?? (n.style?.width as number | undefined) ?? 150,+ h: n.height ?? (n.style?.height as number | undefined) ?? 48,+ }+ })+ const boxById = new Map(boxes.map((b) => [b.id, b]))++ const minX = Math.min(...boxes.map((b) => b.x))+ const minY = Math.min(...boxes.map((b) => b.y))+ const maxX = Math.max(...boxes.map((b) => b.x + b.w))+ const maxY = Math.max(...boxes.map((b) => b.y + b.h))+ // Cap the scale so a near-empty graph doesn't blow one node up to card size+ const scale = Math.min(+ (VIEW_W - PAD * 2) / Math.max(maxX - minX, 1),+ (VIEW_H - PAD * 2) / Math.max(maxY - minY, 1),+ 0.5,+ )+ const offX = (VIEW_W - (maxX - minX) * scale) / 2+ const offY = (VIEW_H - (maxY - minY) * scale) / 2+ const tx = (x: number): number => offX + (x - minX) * scale+ const ty = (y: number): number => offY + (y - minY) * scale++ // While containers render as dashed outlines behind the flow+ const containers = boxes.filter((b) => b.type === 'whileNode')+ const plain = boxes.filter((b) => b.type !== 'whileNode')++ return (+ <svg viewBox={`0 0 ${VIEW_W} ${VIEW_H}`} className="w-full h-full" preserveAspectRatio="xMidYMid meet">+ <defs>+ <pattern id="wf-mini-grid" width="11" height="11" patternUnits="userSpaceOnUse">+ <circle cx="1" cy="1" r="0.8" fill="#27272a" />+ </pattern>+ </defs>+ <rect width={VIEW_W} height={VIEW_H} fill="url(#wf-mini-grid)" />+ {containers.map((b) => (+ <rect+ key={b.id}+ x={tx(b.x)} y={ty(b.y)}+ width={Math.max(b.w * scale, 3)} height={Math.max(b.h * scale, 3)}+ rx="3" fill="rgba(113,113,122,0.06)" stroke="#52525b" strokeWidth="0.75" strokeDasharray="2.5 2"+ />+ ))}+ {wf.edges.map((e) => {+ const s = boxById.get(e.source)+ const t = boxById.get(e.target)+ if (!s || !t) return null+ const x1 = tx(s.x + s.w), y1 = ty(s.y + s.h / 2)+ const x2 = tx(t.x), y2 = ty(t.y + t.h / 2)+ const d = Math.max(Math.abs(x2 - x1) * 0.45, 6)+ return (+ <path+ key={e.id}+ d={`M ${x1} ${y1} C ${x1 + d} ${y1}, ${x2 - d} ${y2}, ${x2} ${y2}`}+ fill="none" stroke="#5b5b66" strokeWidth="1" strokeLinecap="round" opacity="0.9"+ />+ )+ })}+ {plain.map((b) => {+ const tint = MINI_NODE_TINTS[b.type] ?? MINI_NODE_DEFAULT_TINT+ return (+ <rect+ key={b.id}+ x={tx(b.x)} y={ty(b.y)}+ width={Math.max(b.w * scale, 3)} height={Math.max(b.h * scale, 3)}+ rx="2" fill={tint.fill} stroke={tint.stroke} strokeWidth="0.75"+ />+ )+ })}+ </svg>+ )+}++// ─── Page ─────────────────────────────────────────────────────────────────────++export default function WorkflowsPage(): JSX.Element {+ const { workflows, loading, activeId, openIds, folders, folderColors, bookmarkedFolders, load, save, remove, importFile, exportFile, setActive, openWorkflow, closeWorkflow, moveOpenTab, addFolder, removeFolder, setFolderColor, toggleFolderBookmark } = useWorkflowsStore()+ const { modelExtensions, processExtensions, loadExtensions } = useExtensionsStore()++ const [panelOpen, setPanelOpen] = useState(true)+ const [tabMenu, setTabMenu] = useState<{ id: string; x: number; y: number } | null>(null)+ const [renameTarget, setRenameTarget] = useState<{ id: string; value: string } | null>(null)+ const [openListVisible, setOpenListVisible] = useState(false)+ const [openSearch, setOpenSearch] = useState('')+ const [newFolderName, setNewFolderName] = useState<string | null>(null) // null = input hidden+ const [collapsedFolders, setCollapsedFolders] = useState<Set<string>>(new Set())+ const [dragOverFolder, setDragOverFolder] = useState<string | null>(null) // '' = root area+ const [dragOverTab, setDragOverTab] = useState<string | null>(null)+ const [deleteTarget, setDeleteTarget] = useState<string | null>(null) // workflow id pending deletion+ const [colorPickerFolder, setColorPickerFolder] = useState<string | null>(null)++ // Folder color of a workflow, if it lives in a colored folder+ const workflowColor = (wf: Workflow): string | undefined =>+ wf.folder ? folderColors[wf.folder] : undefined++ // Tab of the workflow currently executing (dot indicator), if any+ const runningWorkflowId = useWorkflowRunStore((s) =>+ s.runState.status === 'running' || s.runState.status === 'paused' ? s.activeWorkflowId : null,+ )++ // Close the tab context menu on any outside click (it has no backdrop of its own)+ useEffect(() => {+ if (!tabMenu) return+ const close = (): void => setTabMenu(null)+ window.addEventListener('mousedown', close)+ return () => window.removeEventListener('mousedown', close)+ }, [tabMenu])++ // Escape closes whichever popup is topmost, regardless of what's focused —+ // relying on a focused element's own onKeyDown would miss presses right after+ // a popup opens (before anything inside it has focus).+ useEffect(() => {+ const onKey = (e: KeyboardEvent): void => {+ if (e.key !== 'Escape') return+ if (deleteTarget) { setDeleteTarget(null); return }+ if (renameTarget) { setRenameTarget(null); return }+ if (newFolderName !== null) { setNewFolderName(null); return }+ if (tabMenu) { setTabMenu(null); return }+ if (openListVisible) { setOpenListVisible(false); return }+ }+ window.addEventListener('keydown', onKey)+ return () => window.removeEventListener('keydown', onKey)+ }, [deleteTarget, renameTarget, newFolderName, tabMenu, openListVisible])++ // Browser-style tab shortcuts: Ctrl+T new, Ctrl+W close, Ctrl(+Shift)+Tab cycle+ useEffect(() => {+ const onKey = (e: KeyboardEvent): void => {+ if (!(e.ctrlKey || e.metaKey)) return+ if (e.key === 't' && !e.shiftKey) {+ e.preventDefault()+ handleCreateBlank()+ } else if (e.key === 'w' && !e.shiftKey) {+ e.preventDefault()+ if (activeId) handleCloseTab(activeId)+ } else if (e.key === 'Tab') {+ e.preventDefault()+ if (openIds.length < 2 || !activeId) return+ const idx = openIds.indexOf(activeId)+ const next = e.shiftKey ? (idx - 1 + openIds.length) % openIds.length : (idx + 1) % openIds.length+ setActive(openIds[next])+ }+ }+ window.addEventListener('keydown', onKey)+ return () => window.removeEventListener('keydown', onKey)+ // eslint-disable-next-line react-hooks/exhaustive-deps -- store setters are stable; handleCreateBlank only uses them+ }, [activeId, openIds])++ // Fresh search / closed color picker each time the Open popup opens+ useEffect(() => {+ if (!openListVisible) { setOpenSearch(''); setColorPickerFolder(null) }+ }, [openListVisible])++ const allExtensions = useMemo(+ () => buildAllWorkflowExtensions(modelExtensions, processExtensions),+ [modelExtensions, processExtensions],+ )++ // eslint-disable-next-line react-hooks/exhaustive-deps -- load once on mount+ useEffect(() => { load(); loadExtensions() }, [])++ // Auto-select the first open tab when none is active or the active id is gone+ useEffect(() => {+ if (loading) return+ if (openIds.length === 0) return+ if (activeId && openIds.includes(activeId) && workflows.find((w) => w.id === activeId)) return+ setActive(openIds[0])+ // eslint-disable-next-line react-hooks/exhaustive-deps -- setActive is a stable store setter+ }, [workflows, loading, activeId, openIds])++ const openWorkflows = openIds.map((id) => workflows.find((w) => w.id === id)).filter((w): w is Workflow => !!w)+ const activeWorkflow = workflows.find((w) => w.id === activeId) ?? null++ async function handleCreateBlank() {+ const wf = newWorkflow()+ await save(wf)+ openWorkflow(wf.id)+ }++ async function handleImport() {+ const result = await importFile()+ if (result.success && result.workflow) openWorkflow((result.workflow as Workflow).id)+ }++ async function handleRename() {+ if (!renameTarget) return+ const wf = workflows.find((w) => w.id === renameTarget.id)+ const trimmed = renameTarget.value.trim()+ if (wf && trimmed && trimmed !== wf.name) {+ await save({ ...wf, name: trimmed, updatedAt: new Date().toISOString() })+ }+ setRenameTarget(null)+ }++ function renderWorkflowCard(wf: Workflow): JSX.Element {+ const isOpen = openIds.includes(wf.id)+ const cardActionCls = 'flex items-center justify-center w-5 h-5 rounded-md bg-zinc-900/70 backdrop-blur-sm text-zinc-500 opacity-0 group-hover:opacity-100 transition-all hover:scale-110'+ return (+ <div+ key={wf.id}+ draggable+ onDragStart={(e) => {+ e.dataTransfer.setData('modly/workflow-id', wf.id)+ e.dataTransfer.effectAllowed = 'move'+ }}+ onClick={() => { openWorkflow(wf.id); setOpenListVisible(false) }}+ className={`group relative flex flex-col rounded-lg overflow-hidden border cursor-pointer transition-colors+ ${isOpen ? 'border-violet-500/50 bg-violet-500/10' : 'border-zinc-800 bg-zinc-950/40 hover:border-zinc-700 hover:bg-zinc-800/40'}`}+ >+ <div className="relative h-[72px] border-b border-zinc-800/60 bg-zinc-950/50">+ {workflowColor(wf) && (+ <div+ className="absolute inset-0 pointer-events-none"+ style={{ background: `radial-gradient(ellipse 90% 110% at 50% 45%, ${workflowColor(wf)}30, ${workflowColor(wf)}08 60%, transparent 80%)` }}+ />+ )}+ <WorkflowMiniPreview wf={wf} />+ <div className="absolute top-1 right-1 flex items-center gap-0.5">+ <button+ onClick={(e) => { e.stopPropagation(); handleToggleBookmark(wf.id) }}+ title={wf.bookmarked ? 'Remove bookmark' : 'Bookmark'}+ className={`flex items-center justify-center w-5 h-5 rounded-md bg-zinc-900/70 backdrop-blur-sm opacity-0 group-hover:opacity-100 transition-all hover:scale-110+ ${wf.bookmarked ? 'text-amber-400 drop-shadow-[0_0_5px_rgba(251,191,36,0.55)]' : 'text-zinc-500 hover:text-amber-300'}`}+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill={wf.bookmarked ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="1.75" strokeLinejoin="round">+ <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>+ </svg>+ </button>+ <button+ onClick={(e) => { e.stopPropagation(); handleDuplicate(wf.id) }}+ title="Duplicate"+ className={`${cardActionCls} hover:text-zinc-200 hover:bg-zinc-700/80`}+ >+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>+ </svg>+ </button>+ <button+ onClick={(e) => { e.stopPropagation(); setRenameTarget({ id: wf.id, value: wf.name }) }}+ title="Rename"+ className={`${cardActionCls} hover:text-zinc-200 hover:bg-zinc-700/80`}+ >+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"/>+ </svg>+ </button>+ <button+ onClick={(e) => { e.stopPropagation(); setDeleteTarget(wf.id) }}+ title="Delete"+ className={`${cardActionCls} hover:text-red-400 hover:bg-red-950/60`}+ >+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <polyline points="3 6 5 6 21 6"/>+ <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>+ </svg>+ </button>+ </div>+ </div>+ <div className="px-2.5 py-1.5">+ <p className="text-xs font-medium text-zinc-200 truncate">{wf.name || 'Untitled'}</p>+ <p className="text-[10px] text-zinc-600 truncate">{new Date(wf.updatedAt).toLocaleString()}</p>+ </div>+ </div>+ )+ }++ function renderFolder(folder: string): JSX.Element {+ const inFolder = workflows.filter((w) => w.folder === folder).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))+ const collapsed = collapsedFolders.has(folder)+ return (+ <div key={folder}>+ <div+ onClick={() => setCollapsedFolders((s) => {+ const next = new Set(s)+ if (next.has(folder)) next.delete(folder); else next.add(folder)+ return next+ })}+ onDragOver={(e) => { e.preventDefault(); e.stopPropagation(); setDragOverFolder(folder) }}+ onDragLeave={() => setDragOverFolder(null)}+ onDrop={(e) => {+ e.preventDefault()+ e.stopPropagation()+ setDragOverFolder(null)+ const id = e.dataTransfer.getData('modly/workflow-id')+ if (id) handleMoveToFolder(id, folder)+ }}+ className={`group flex items-center gap-2 px-4 py-2 cursor-pointer text-zinc-400 hover:text-zinc-200 transition-colors+ ${dragOverFolder === folder ? 'bg-accent/10 text-accent-light' : ''}`}+ >+ <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"+ className={`shrink-0 transition-transform ${collapsed ? '' : 'rotate-90'}`}>+ <polyline points="9 18 15 12 9 6"/>+ </svg>+ <svg width="12" height="12" viewBox="0 0 24 24" fill={folderColors[folder] ? `${folderColors[folder]}33` : 'none'} stroke={folderColors[folder] ?? 'currentColor'} strokeWidth="2" className="shrink-0">+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>+ </svg>+ <span className="text-xs font-medium truncate">{folder}</span>+ <span className="text-[10px] text-zinc-600">{inFolder.length}</span>+ <div className="flex-1" />+ <button+ onClick={(e) => { e.stopPropagation(); toggleFolderBookmark(folder) }}+ title={bookmarkedFolders.includes(folder) ? 'Remove bookmark' : 'Bookmark folder'}+ className={`shrink-0 flex items-center justify-center w-5 h-5 rounded-md opacity-0 group-hover:opacity-100 transition-all hover:scale-110 hover:bg-zinc-800+ ${bookmarkedFolders.includes(folder) ? 'text-amber-400 drop-shadow-[0_0_5px_rgba(251,191,36,0.55)]' : 'text-zinc-600 hover:text-amber-300'}`}+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill={bookmarkedFolders.includes(folder) ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="1.75" strokeLinejoin="round">+ <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>+ </svg>+ </button>+ <button+ onClick={(e) => { e.stopPropagation(); setColorPickerFolder((cur) => (cur === folder ? null : folder)) }}+ title="Folder color"+ className="shrink-0 flex items-center justify-center w-5 h-5 rounded opacity-0 group-hover:opacity-100 hover:bg-zinc-800 transition-all"+ >+ <span className="w-2.5 h-2.5 rounded-full border border-zinc-600" style={{ background: folderColors[folder] ?? 'transparent' }} />+ </button>+ <button+ onClick={(e) => { e.stopPropagation(); handleDeleteFolder(folder) }}+ title="Delete folder (workflows move to root)"+ className="shrink-0 flex items-center justify-center w-5 h-5 rounded text-zinc-700 opacity-0 group-hover:opacity-100 hover:text-red-400 hover:bg-red-950/30 transition-all"+ >+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <polyline points="3 6 5 6 21 6"/>+ <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>+ </svg>+ </button>+ </div>+ {colorPickerFolder === folder && (+ <div className="flex items-center gap-1.5 pl-11 pr-4 py-1.5">+ {FOLDER_COLORS.map((c) => (+ <button+ key={c}+ onClick={() => { setFolderColor(folder, c); setColorPickerFolder(null) }}+ className={`w-4 h-4 rounded-full transition-transform hover:scale-125 ${folderColors[folder] === c ? 'ring-2 ring-zinc-400 ring-offset-1 ring-offset-zinc-900' : ''}`}+ style={{ background: c }}+ />+ ))}+ </div>+ )}+ {!collapsed && inFolder.length > 0 && (+ <div className="grid grid-cols-3 gap-2 pl-8 pr-4 py-1.5">+ {inFolder.map((wf) => renderWorkflowCard(wf))}+ </div>+ )}+ {!collapsed && inFolder.length === 0 && (+ <p className="pl-11 pr-5 py-1.5 text-[10px] text-zinc-700 italic">Empty — drag workflows here</p>+ )}+ </div>+ )+ }++ // Closing the tab of an empty workflow (no nodes) deletes it too — a blank+ // "New Workflow" the user closes is throwaway, don't let them pile up on disk.+ // Reads the store directly so a keyboard shortcut never acts on a stale list.+ function handleCloseTab(id: string) {+ const wf = useWorkflowsStore.getState().workflows.find((w) => w.id === id)+ if (wf && wf.nodes.length === 0) { remove(id); return }+ closeWorkflow(id)+ }++ async function handleToggleBookmark(id: string) {+ const wf = workflows.find((w) => w.id === id)+ if (!wf) return+ // Not an edit — keep updatedAt so the recency sort doesn't reshuffle+ await save({ ...wf, bookmarked: !wf.bookmarked })+ }++ async function handleMoveToFolder(id: string, folder?: string) {+ const wf = workflows.find((w) => w.id === id)+ if (!wf || (wf.folder ?? undefined) === folder) return+ await save({ ...wf, folder })+ }++ async function handleDeleteFolder(name: string) {+ for (const wf of workflows.filter((w) => w.folder === name)) {+ await save({ ...wf, folder: undefined })+ }+ removeFolder(name)+ }++ function handleCreateFolder() {+ const trimmed = (newFolderName ?? '').trim()+ if (trimmed) addFolder(trimmed)+ setNewFolderName(null)+ }++ async function handleDuplicate(id: string) {+ const src = workflows.find((w) => w.id === id)+ if (!src) return+ const now = new Date().toISOString()+ const copy: Workflow = {+ ...structuredClone(src),+ id: newId(),+ name: `${src.name || 'Untitled'} copy`,+ bookmarked: undefined, // a copy isn't the favorite+ createdAt: now,+ updatedAt: now,+ }+ await save(copy)+ openWorkflow(copy.id)+ }++ return (+ <div className="flex flex-col flex-1 overflow-hidden">++ {/* Tab bar */}+ {!loading && (+ <div className="flex items-stretch border-b border-zinc-800 bg-zinc-950/30 overflow-x-auto shrink-0 h-9">+ {openWorkflows.map((wf) => (+ <div+ key={wf.id}+ draggable+ onDragStart={(e) => { e.dataTransfer.setData('modly/tab-id', wf.id); e.dataTransfer.effectAllowed = 'move' }}+ onDragOver={(e) => {+ if (!e.dataTransfer.types.includes('modly/tab-id')) return+ e.preventDefault()+ setDragOverTab(wf.id)+ }}+ onDragLeave={() => setDragOverTab((cur) => (cur === wf.id ? null : cur))}+ onDrop={(e) => {+ e.preventDefault()+ setDragOverTab(null)+ const dragId = e.dataTransfer.getData('modly/tab-id')+ if (dragId) moveOpenTab(dragId, wf.id)+ }}+ onClick={() => setActive(wf.id)}+ onMouseDown={(e) => { if (e.button === 1) { e.preventDefault(); handleCloseTab(wf.id) } }}+ onContextMenu={(e) => { e.preventDefault(); setTabMenu({ id: wf.id, x: e.clientX, y: e.clientY }) }}+ className={`relative flex items-center gap-1.5 pl-3 pr-1.5 h-full text-[11px] font-medium shrink-0 transition-colors border-b-2 cursor-pointer group+ ${wf.id === activeId+ ? 'text-zinc-100 border-accent bg-zinc-900/50'+ : 'text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800/20 border-transparent'+ }`}+ >+ {dragOverTab === wf.id && <span className="absolute left-0 top-1 bottom-1 w-0.5 bg-accent rounded" />}+ {/* Folder color dot; doubles as the running indicator (pulses) */}+ {(workflowColor(wf) || runningWorkflowId === wf.id) && (+ <span+ className={`w-1.5 h-1.5 rounded-full shrink-0 ${runningWorkflowId === wf.id ? 'animate-pulse' : ''} ${workflowColor(wf) ? '' : 'bg-accent'}`}+ title={runningWorkflowId === wf.id ? 'Running' : undefined}+ style={workflowColor(wf) ? { background: workflowColor(wf), boxShadow: `0 0 4px ${workflowColor(wf)}80` } : undefined}+ />+ )}+ <span className="truncate max-w-[120px]">{wf.name || 'Untitled'}</span>+ <button+ onClick={(e) => { e.stopPropagation(); handleCloseTab(wf.id) }}+ title="Close tab"+ className="shrink-0 flex items-center justify-center w-5 h-5 rounded text-zinc-600 hover:text-zinc-300 hover:bg-zinc-700/60 transition-colors"+ >+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>+ </svg>+ </button>+ </div>+ ))}+ <button+ onClick={handleCreateBlank}+ title="New workflow"+ className="shrink-0 flex items-center justify-center w-9 h-full text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800/40 transition-colors"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>+ </svg>+ </button>+ </div>+ )}++ {/* Tab context menu */}+ {tabMenu && (+ <div+ style={{ left: tabMenu.x, top: tabMenu.y }}+ className="fixed z-50 min-w-[140px] py-1 rounded-lg bg-zinc-900 border border-zinc-700 shadow-xl"+ onMouseDown={(e) => e.stopPropagation()}+ >+ <button+ onClick={() => {+ const wf = workflows.find((w) => w.id === tabMenu.id)+ if (wf) setRenameTarget({ id: wf.id, value: wf.name })+ setTabMenu(null)+ }}+ className="w-full flex items-center gap-2 px-3 py-1.5 text-[11px] text-zinc-300 hover:bg-zinc-800 hover:text-zinc-100 transition-colors"+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="shrink-0">+ <path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"/>+ </svg>+ Rename+ </button>+ <button+ onClick={() => { handleDuplicate(tabMenu.id); setTabMenu(null) }}+ className="w-full flex items-center gap-2 px-3 py-1.5 text-[11px] text-zinc-300 hover:bg-zinc-800 hover:text-zinc-100 transition-colors"+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="shrink-0">+ <rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>+ </svg>+ Duplicate+ </button>+ <button+ onClick={() => {+ const wf = workflows.find((w) => w.id === tabMenu.id)+ if (wf) exportFile(wf)+ setTabMenu(null)+ }}+ className="w-full flex items-center gap-2 px-3 py-1.5 text-[11px] text-zinc-300 hover:bg-zinc-800 hover:text-zinc-100 transition-colors"+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="shrink-0">+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>+ <polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/>+ </svg>+ Export JSON+ </button>+ <div className="my-1 h-px bg-zinc-800" />+ <button+ onClick={() => { setDeleteTarget(tabMenu.id); setTabMenu(null) }}+ className="w-full flex items-center gap-2 px-3 py-1.5 text-[11px] text-zinc-400 hover:bg-red-950/40 hover:text-red-400 transition-colors"+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="shrink-0">+ <polyline points="3 6 5 6 21 6"/>+ <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>+ </svg>+ Delete+ </button>+ </div>+ )}++ {/* Rename popup (above the Open popup, which can trigger it) */}+ {renameTarget && createPortal(+ <div+ className="fixed inset-0 z-[10000] flex items-center justify-center bg-zinc-950/70 backdrop-blur-sm"+ onMouseDown={() => setRenameTarget(null)}+ >+ <div+ className="w-[320px] rounded-2xl bg-zinc-900 border border-zinc-700/60 shadow-2xl p-5"+ onMouseDown={(e) => e.stopPropagation()}+ >+ <p className="text-sm font-semibold text-zinc-200 mb-3">Rename workflow</p>+ <input+ autoFocus+ value={renameTarget.value}+ onChange={(e) => setRenameTarget({ ...renameTarget, value: e.target.value })}+ onFocus={(e) => e.currentTarget.select()}+ onKeyDown={(e) => { if (e.key === 'Enter') handleRename() }}+ placeholder="Workflow name…"+ className="w-full bg-zinc-800 border border-zinc-700/80 rounded-md px-3 py-2 text-sm text-zinc-200 placeholder-zinc-600 focus:outline-none focus:border-accent/60"+ />+ <div className="flex justify-end gap-2 mt-4">+ <button+ onClick={() => setRenameTarget(null)}+ className="px-3 py-1.5 rounded-md border border-zinc-700 text-zinc-400 text-xs font-medium hover:bg-zinc-800 hover:text-zinc-200 transition-colors"+ >+ Cancel+ </button>+ <button+ onClick={handleRename}+ disabled={!renameTarget.value.trim()}+ className="px-3 py-1.5 rounded-md bg-accent text-white text-xs font-semibold hover:bg-accent/90 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"+ >+ Rename+ </button>+ </div>+ </div>+ </div>,+ document.body,+ )}++ {/* Delete confirmation popup (topmost — reachable from the Open popup) */}+ {deleteTarget && createPortal(+ <div+ className="fixed inset-0 z-[10001] flex items-center justify-center bg-zinc-950/70 backdrop-blur-sm"+ onMouseDown={() => setDeleteTarget(null)}+ >+ <div+ className="w-[320px] rounded-2xl bg-zinc-900 border border-zinc-700/60 shadow-2xl p-5"+ onMouseDown={(e) => e.stopPropagation()}+ >+ <p className="text-sm font-semibold text-zinc-200">Delete workflow?</p>+ <p className="text-xs text-zinc-500 mt-2">+ “{workflows.find((w) => w.id === deleteTarget)?.name || 'Untitled'}” will be permanently deleted. This cannot be undone.+ </p>+ <div className="flex justify-end gap-2 mt-5">+ <button+ onClick={() => setDeleteTarget(null)}+ className="px-3 py-1.5 rounded-md border border-zinc-700 text-zinc-400 text-xs font-medium hover:bg-zinc-800 hover:text-zinc-200 transition-colors"+ >+ Cancel+ </button>+ <button+ onClick={() => { remove(deleteTarget); setDeleteTarget(null) }}+ className="px-3 py-1.5 rounded-md bg-red-600 text-white text-xs font-semibold hover:bg-red-500 transition-colors"+ >+ Delete+ </button>+ </div>+ </div>+ </div>,+ document.body,+ )}++ {/* Open workflow popup */}+ {openListVisible && createPortal(+ <div+ className="fixed inset-0 z-[9999] flex items-center justify-center bg-zinc-950/70 backdrop-blur-sm"+ onMouseDown={() => setOpenListVisible(false)}+ >+ <div+ className="w-[640px] max-w-[92vw] max-h-[70vh] rounded-2xl bg-zinc-900 border border-zinc-700/60 shadow-2xl flex flex-col overflow-hidden"+ onMouseDown={(e) => e.stopPropagation()}+ >+ <div className="flex items-center justify-between px-5 py-4 border-b border-zinc-800">+ <p className="text-sm font-semibold text-zinc-200">Open workflow</p>+ <div className="flex items-center gap-1">+ <button+ onClick={() => setNewFolderName('')}+ title="New folder"+ className="flex items-center justify-center w-6 h-6 rounded text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800 transition-colors"+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>+ <line x1="12" y1="11" x2="12" y2="17"/><line x1="9" y1="14" x2="15" y2="14"/>+ </svg>+ </button>+ <button+ onClick={() => setOpenListVisible(false)}+ className="flex items-center justify-center w-6 h-6 rounded text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800 transition-colors"+ >+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>+ </svg>+ </button>+ </div>+ </div>++ {/* Search */}+ <div className="px-4 py-2 border-b border-zinc-800">+ <div className="flex items-center gap-2 bg-zinc-800 border border-zinc-700/80 rounded-md px-2.5 py-1.5 focus-within:border-accent/60">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="shrink-0 text-zinc-500">+ <circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>+ </svg>+ <input+ autoFocus+ value={openSearch}+ onChange={(e) => setOpenSearch(e.target.value)}+ placeholder="Search workflows…"+ className="flex-1 min-w-0 bg-transparent text-xs text-zinc-200 placeholder-zinc-600 focus:outline-none"+ />+ {openSearch && (+ <button onClick={() => setOpenSearch('')} className="shrink-0 text-zinc-600 hover:text-zinc-300 transition-colors">+ <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>+ </svg>+ </button>+ )}+ </div>+ </div>++ {/* New folder inline input */}+ {newFolderName !== null && (+ <div className="flex items-center gap-2 px-4 py-2 border-b border-zinc-800 bg-zinc-950/40">+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="shrink-0 text-zinc-500">+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>+ </svg>+ <input+ autoFocus+ value={newFolderName}+ onChange={(e) => setNewFolderName(e.target.value)}+ onKeyDown={(e) => { if (e.key === 'Enter') handleCreateFolder() }}+ onBlur={() => setNewFolderName(null)}+ placeholder="Folder name… (Enter to create)"+ className="flex-1 min-w-0 bg-zinc-800 border border-zinc-700/80 rounded-md px-2.5 py-1.5 text-xs text-zinc-200 placeholder-zinc-600 focus:outline-none focus:border-accent/60"+ />+ </div>+ )}++ <div+ className="flex-1 overflow-y-auto py-1"+ onDragOver={(e) => e.preventDefault()}+ onDrop={(e) => {+ // Drop on the list background (not a folder) → move back to root+ e.preventDefault()+ setDragOverFolder(null)+ const id = e.dataTransfer.getData('modly/workflow-id')+ if (id) handleMoveToFolder(id, undefined)+ }}+ >+ {workflows.length === 0 && folders.length === 0 && (+ <p className="px-5 py-6 text-center text-xs text-zinc-600 italic">No saved workflows.</p>+ )}++ {/* Search results — flat list across all folders */}+ {openSearch.trim() !== '' && (() => {+ const q = openSearch.trim().toLowerCase()+ const matches = workflows+ .filter((w) => (w.name || 'Untitled').toLowerCase().includes(q))+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))+ if (matches.length === 0) {+ return <p className="px-5 py-6 text-center text-xs text-zinc-600 italic">No workflow matches “{openSearch.trim()}”.</p>+ }+ return (+ <div className="grid grid-cols-3 gap-2 px-4 py-2">+ {matches.map((wf) => renderWorkflowCard(wf))}+ </div>+ )+ })()}++ {/* Bookmarks — pinned section: starred folders, then starred workflows */}+ {openSearch.trim() === '' && (() => {+ const markedFolders = [...bookmarkedFolders].filter((f) => folders.includes(f)).sort((a, b) => a.localeCompare(b))+ // Starred workflows already shown inside a starred folder aren't repeated+ const marked = workflows+ .filter((w) => w.bookmarked && !(w.folder && bookmarkedFolders.includes(w.folder)))+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))+ if (marked.length === 0 && markedFolders.length === 0) return null+ return (+ <div className="border-b border-zinc-800/60 pb-1 mb-1">+ <div className="flex items-center gap-2 px-4 py-2 text-amber-400/80">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor" className="shrink-0">+ <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>+ </svg>+ <span className="text-xs font-medium">Bookmarks</span>+ </div>+ {markedFolders.map((folder) => renderFolder(folder))}+ {marked.length > 0 && (+ <div className="grid grid-cols-3 gap-2 px-4 py-1.5">+ {marked.map((wf) => renderWorkflowCard(wf))}+ </div>+ )}+ </div>+ )+ })()}++ {/* Folders (bookmarked ones live in the section above) */}+ {openSearch.trim() === '' && [...folders]+ .filter((f) => !bookmarkedFolders.includes(f))+ .sort((a, b) => a.localeCompare(b))+ .map((folder) => renderFolder(folder))}++ {/* Root workflows */}+ {openSearch.trim() === '' && (() => {+ const root = workflows+ .filter((w) => !w.folder || !folders.includes(w.folder))+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))+ if (root.length === 0) return null+ return (+ <div className="grid grid-cols-3 gap-2 px-4 py-2">+ {root.map((wf) => renderWorkflowCard(wf))}+ </div>+ )+ })()}+ </div>+ </div>+ </div>,+ document.body,+ )}++ {/* Canvas + extensions panel */}+ <div className="flex flex-1 overflow-hidden">++ {activeWorkflow ? (+ <ReactFlowProvider>+ <WorkflowCanvasInner+ key={activeWorkflow.id}+ workflow={activeWorkflow}+ allExtensions={allExtensions}+ onSave={save}+ panelOpen={panelOpen}+ onTogglePanel={() => setPanelOpen((o) => !o)}+ onOpen={() => setOpenListVisible(true)}+ onImport={handleImport}+ />+ </ReactFlowProvider>+ ) : (+ <div className="flex flex-1 flex-col items-center justify-center text-zinc-600 gap-3">+ <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1">+ <rect x="3" y="3" width="6" height="5" rx="1"/><rect x="3" y="11" width="6" height="5" rx="1"/>+ <path d="M9 5.5h3.5a1 1 0 0 1 1 1v5"/><rect x="13" y="9" width="8" height="7" rx="1"/>+ </svg>+ <div className="text-center">+ <p className="text-sm font-medium">{workflows.length === 0 ? 'No workflows yet' : 'No workflow open'}</p>+ <p className="text-xs mt-1">{workflows.length === 0 ? 'Create one to get started' : 'Open a saved workflow or create a new one'}</p>+ </div>+ <div className="flex items-center gap-2 mt-2">+ {workflows.length > 0 && (+ <button onClick={() => setOpenListVisible(true)} className="px-4 py-2 rounded-lg bg-accent text-white text-xs font-semibold hover:bg-accent/90 transition-colors">+ Open+ </button>+ )}+ <button onClick={handleCreateBlank} className={`px-4 py-2 rounded-lg text-xs font-semibold transition-colors ${workflows.length === 0 ? 'bg-accent text-white hover:bg-accent/90' : 'border border-zinc-700 text-zinc-300 hover:bg-zinc-800'}`}>+ New Workflow+ </button>+ <button onClick={handleImport} className="px-4 py-2 rounded-lg border border-zinc-700 text-zinc-300 text-xs font-semibold hover:bg-zinc-800 transition-colors">+ Import+ </button>+ </div>+ </div>+ )}++ {/* Extensions panel */}+ <ExtensionsPanel allExtensions={allExtensions} open={panelOpen} />+ </div>+ </div>+ )+}diff --git a/apps/forge-desktop/src/areas/workflows/mockExtensions.test.mjs b/apps/forge-desktop/src/areas/workflows/mockExtensions.test.mjsnew file mode 100644index 000000000..a3edbe842--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/mockExtensions.test.mjs@@ -0,0 +1,62 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-workflow-ext-test-')), 'mockExtensions.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('src/areas/workflows/mockExtensions.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++function extension(type, overrides = {}) {+ return {+ type,+ id: `${type}-extension`,+ name: `${type} extension`,+ trusted: false,+ builtin: false,+ entry: type === 'process' ? 'processor.js' : undefined,+ nodes: [{+ id: 'generate',+ name: 'Generate',+ input: 'image',+ output: 'mesh',+ paramsSchema: [],+ }],+ ...overrides,+ }+}++test('workflow discovery excludes corrupted extensions with preserved nodes', () => {+ const { buildAllWorkflowExtensions } = loadModule()+ const healthyModel = extension('model', { id: 'healthy-model' })+ const pendingModel = extension('model', {+ id: 'pixal3d',+ corrupted: true,+ manifestError: 'incomplete',+ })+ const pendingProcess = extension('process', {+ id: 'pending-process',+ corrupted: true,+ manifestError: 'incomplete',+ })++ const result = buildAllWorkflowExtensions(+ [healthyModel, pendingModel],+ [pendingProcess],+ )++ assert.deepEqual(result.map((entry) => entry.id), ['healthy-model/generate'])+})diff --git a/apps/forge-desktop/src/areas/workflows/mockExtensions.ts b/apps/forge-desktop/src/areas/workflows/mockExtensions.tsnew file mode 100644index 000000000..9bdb9a0a6--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/mockExtensions.ts@@ -0,0 +1,91 @@+import type { ModelExtension, ProcessExtension } from '@shared/stores/extensionsStore'+export type { ParamSchema } from '@shared/types/electron.d'+import type { ParamSchema, WeightVariantsInfo } from '@shared/types/electron.d'++export interface WorkflowExtension {+ id: string // "ext_id/node_id"+ extensionId: string // "ext_id" (for IPC calls)+ extensionName: string // display name of the parent extension+ extensionAuthor: string // author of the parent extension+ nodeId: string // "node_id"+ name: string+ description: string+ input: 'image' | 'text' | 'mesh' | 'audio' | 'scene'+ inputs?: ('image' | 'text' | 'mesh' | 'audio' | 'scene')[] // multi-input; overrides input when set+ inputLabels?: string[] // display labels per input slot+ output: 'image' | 'text' | 'mesh' | 'audio' | 'scene'+ params: ParamSchema[]+ builtin: boolean+ type: 'model' | 'process'+ weightVariants?: WeightVariantsInfo+}++function applyParamDefaults(+ schema: ParamSchema[],+ defaults: Record<string, number | string> | undefined,+): ParamSchema[] {+ if (!defaults || Object.keys(defaults).length === 0) return schema+ return schema.map((p) =>+ Object.prototype.hasOwnProperty.call(defaults, p.id)+ ? { ...p, default: defaults[p.id]! }+ : p,+ )+}++export function buildAllWorkflowExtensions(+ modelExtensions: ModelExtension[],+ processExtensions: ProcessExtension[],+): WorkflowExtension[] {+ const result: WorkflowExtension[] = []++ for (const ext of processExtensions) {+ if (ext.corrupted) continue+ for (const node of ext.nodes) {+ result.push({+ id: `${ext.id}/${node.id}`,+ extensionId: ext.id,+ extensionName: ext.name,+ extensionAuthor: ext.author ?? '',+ nodeId: node.id,+ name: node.name,+ description: ext.description ?? '',+ input: node.input,+ inputs: node.inputs,+ inputLabels: node.inputLabels,+ output: node.output,+ params: applyParamDefaults(node.paramsSchema as ParamSchema[], node.paramDefaults),+ builtin: ext.builtin,+ type: 'process',+ })+ }+ }++ for (const ext of modelExtensions) {+ if (ext.corrupted) continue+ for (const node of ext.nodes) {+ result.push({+ id: `${ext.id}/${node.id}`,+ extensionId: ext.id,+ extensionName: ext.name,+ extensionAuthor: ext.author ?? '',+ nodeId: node.id,+ name: node.name,+ description: ext.description ?? '',+ input: node.input,+ inputs: node.inputs,+ inputLabels: node.inputLabels,+ output: node.output,+ params: applyParamDefaults(node.paramsSchema as ParamSchema[], node.paramDefaults),+ builtin: ext.builtin,+ type: 'model',+ weightVariants: node.weightVariants,+ })+ }+ }++ return result+}++export function getWorkflowExtension(id: string, all: WorkflowExtension[]): WorkflowExtension | undefined {+ return all.find((e) => e.id === id)+}diff --git a/apps/forge-desktop/src/areas/workflows/nodeBehaviors.test.mjs b/apps/forge-desktop/src/areas/workflows/nodeBehaviors.test.mjsnew file mode 100644index 000000000..2685ba43b--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodeBehaviors.test.mjs@@ -0,0 +1,109 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++// nodeBehaviors.ts only type-imports from electron.d, so esbuild erases it.+function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-nodebehaviors-test-')), 'nodeBehaviors.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('src/areas/workflows/nodeBehaviors.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++const {+ isPassthrough, isBranchStarter, isSceneOutput, isBranchConsumer,+ resolveDataSource, nearestUpstreamWaits, reachesSceneOutput,+} = loadModule()++// ─── Fixtures ────────────────────────────────────────────────────────────────++const node = (id, type) => ({ id, type, position: { x: 0, y: 0 }, data: {} })+const edge = (source, target) => ({ id: `${source}->${target}`, source, target })+const mapOf = (...nodes) => new Map(nodes.map((n) => [n.id, n]))++// ─── Behavior predicates ───────────────────────────────────────────────────────++test('predicates read the behavior table and tolerate unknown/undefined types', () => {+ assert.equal(isPassthrough('waitNode'), true)+ assert.equal(isBranchStarter('waitNode'), true)+ assert.equal(isSceneOutput('outputNode'), true)+ assert.equal(isBranchConsumer('outputNode'), true)+ assert.equal(isBranchConsumer('extensionNode'), true)++ assert.equal(isPassthrough('extensionNode'), false)+ assert.equal(isSceneOutput('waitNode'), false)+ assert.equal(isPassthrough(undefined), false)+ assert.equal(isBranchStarter('ghostNode'), false)+})++// ─── resolveDataSource ─────────────────────────────────────────────────────────++test('resolveDataSource walks back through passthrough nodes to the real source', () => {+ const nodes = mapOf(node('img', 'imageNode'), node('wait', 'waitNode'), node('proc', 'extensionNode'))+ const edges = [edge('img', 'wait'), edge('wait', 'proc')]++ assert.equal(resolveDataSource('wait', edges, nodes), 'img') // hop over the Wait+ assert.equal(resolveDataSource('img', edges, nodes), 'img') // non-passthrough returns itself+})++test('resolveDataSource returns undefined when a passthrough has no incoming edge', () => {+ const nodes = mapOf(node('wait', 'waitNode'))+ assert.equal(resolveDataSource('wait', [], nodes), undefined)+})++test('resolveDataSource terminates on a passthrough cycle (no infinite loop)', () => {+ const nodes = mapOf(node('w1', 'waitNode'), node('w2', 'waitNode'))+ const edges = [edge('w2', 'w1'), edge('w1', 'w2')]+ assert.equal(resolveDataSource('w1', edges, nodes), 'w1')+})++// ─── nearestUpstreamWaits ──────────────────────────────────────────────────────++test('nearestUpstreamWaits finds the first Wait on each incoming path', () => {+ const nodes = mapOf(node('img', 'imageNode'), node('wait', 'waitNode'), node('proc', 'extensionNode'), node('out', 'outputNode'))+ const edges = [edge('img', 'wait'), edge('wait', 'proc'), edge('proc', 'out')]+ assert.deepEqual([...nearestUpstreamWaits('out', edges, nodes)], ['wait'])+})++test('nearestUpstreamWaits reports >1 when a node merges two branches', () => {+ const nodes = mapOf(node('wa', 'waitNode'), node('wb', 'waitNode'), node('merge', 'outputNode'))+ const edges = [edge('wa', 'merge'), edge('wb', 'merge')]+ assert.equal(nearestUpstreamWaits('merge', edges, nodes).size, 2)+})++test('nearestUpstreamWaits is empty with no upstream Wait', () => {+ const nodes = mapOf(node('img', 'imageNode'), node('proc', 'extensionNode'))+ const edges = [edge('img', 'proc')]+ assert.equal(nearestUpstreamWaits('proc', edges, nodes).size, 0)+})++// ─── reachesSceneOutput ────────────────────────────────────────────────────────++test('reachesSceneOutput follows forward paths to a scene output', () => {+ const nodes = mapOf(node('proc', 'extensionNode'), node('out', 'outputNode'))+ const edges = [edge('proc', 'out')]+ assert.equal(reachesSceneOutput('proc', edges, nodes), true)+})++test('reachesSceneOutput stops at a Wait boundary (output gated behind a branch)', () => {+ const nodes = mapOf(node('proc', 'extensionNode'), node('wait', 'waitNode'), node('out', 'outputNode'))+ const edges = [edge('proc', 'wait'), edge('wait', 'out')]+ assert.equal(reachesSceneOutput('proc', edges, nodes), false)+})++test('reachesSceneOutput is false when no path reaches an output', () => {+ const nodes = mapOf(node('proc', 'extensionNode'), node('img', 'imageNode'))+ const edges = [edge('proc', 'img')]+ assert.equal(reachesSceneOutput('proc', edges, nodes), false)+})diff --git a/apps/forge-desktop/src/areas/workflows/nodeBehaviors.ts b/apps/forge-desktop/src/areas/workflows/nodeBehaviors.tsnew file mode 100644index 000000000..4846eeef6--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodeBehaviors.ts@@ -0,0 +1,110 @@+import type { WFNode, WFEdge } from '@shared/types/electron.d'++// ─── Node behaviors registry ──────────────────────────────────────────────────+//+// Add a new entry here when you introduce a node type that needs to participate+// in the runner's control-flow logic. The predicates and helpers below derive+// everything they need from this table — no hardcoded type checks anywhere else.+//+// • passthrough — data flows through this node unchanged. Resolvers (inputs,+// preflight typing) walk past it to find the real source.+// • branchStarter — splits the run into a user-driven sub-DAG. The runner+// pauses on these nodes and exposes a Continue/Retry button.+// • sceneOutput — terminal sink that gets pushed to the 3D viewer. Used by+// the immediate mesh-push logic during execution.+// • branchConsumer — executes inside a Wait branch and consumes its single mesh+// output, so it can't be fed by more than one Wait branch.++export interface NodeBehavior {+ passthrough?: boolean+ branchStarter?: boolean+ sceneOutput?: boolean+ branchConsumer?: boolean+}++const BEHAVIORS: Record<string, NodeBehavior> = {+ waitNode: { passthrough: true, branchStarter: true },+ outputNode: { sceneOutput: true, branchConsumer: true },+ extensionNode: { branchConsumer: true },+ imagePreviewNode: { passthrough: true },+}++export const isPassthrough = (type: string | undefined): boolean => !!type && !!BEHAVIORS[type]?.passthrough+export const isBranchStarter = (type: string | undefined): boolean => !!type && !!BEHAVIORS[type]?.branchStarter+export const isSceneOutput = (type: string | undefined): boolean => !!type && !!BEHAVIORS[type]?.sceneOutput+export const isBranchConsumer = (type: string | undefined): boolean => !!type && !!BEHAVIORS[type]?.branchConsumer++// ─── Helpers ──────────────────────────────────────────────────────────────────++/**+ * Walks `sourceId` backwards through passthrough nodes (following each one's+ * incoming edge) until it hits a non-passthrough node. Returns its id, or+ * undefined if a passthrough has no incoming edge.+ */+export function resolveDataSource(+ sourceId: string,+ edges: WFEdge[],+ nodeMap: Map<string, WFNode>,+): string | undefined {+ let cur = sourceId+ const seen = new Set<string>()+ while (isPassthrough(nodeMap.get(cur)?.type) && !seen.has(cur)) {+ seen.add(cur)+ const parent = edges.find((e) => e.target === cur)+ if (!parent) return undefined+ cur = parent.source+ }+ return cur+}++/**+ * Walks backwards from `nodeId` and returns the set of nearest upstream+ * branch-starter (Wait) nodes — the first Wait found on each incoming path,+ * without traversing past it. Empty = no upstream Wait. Size > 1 = the node+ * merges two distinct branches.+ */+export function nearestUpstreamWaits(+ nodeId: string,+ edges: WFEdge[],+ nodeMap: Map<string, WFNode>,+): Set<string> {+ const result = new Set<string>()+ const seen = new Set<string>()+ const stack = edges.filter((e) => e.target === nodeId).map((e) => e.source)+ while (stack.length > 0) {+ const id = stack.pop()!+ if (seen.has(id)) continue+ seen.add(id)+ if (isBranchStarter(nodeMap.get(id)?.type)) { result.add(id); continue }+ for (const e of edges) if (e.target === id) stack.push(e.source)+ }+ return result+}++/**+ * True if any forward path from `sourceId` reaches a sceneOutput node, walking+ * through passthrough nodes — but stopping at branch-starter (Wait) boundaries.+ * A scene output gated behind a Wait belongs to a branch that runs later, so it+ * must not be treated as immediately reachable (otherwise pre-phase nodes would+ * push their mesh to the viewer before the user clicks Continue).+ */+export function reachesSceneOutput(+ sourceId: string,+ edges: WFEdge[],+ nodeMap: Map<string, WFNode>,+): boolean {+ const stack = [sourceId]+ const seen = new Set<string>()+ while (stack.length > 0) {+ const id = stack.pop()!+ if (seen.has(id)) continue+ seen.add(id)+ for (const e of edges) {+ if (e.source !== id) continue+ const tType = nodeMap.get(e.target)?.type+ if (isSceneOutput(tType)) return true+ if (isPassthrough(tType) && !isBranchStarter(tType)) stack.push(e.target)+ }+ }+ return false+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/AddToSceneNode.tsx b/apps/forge-desktop/src/areas/workflows/nodes/AddToSceneNode.tsxnew file mode 100644index 000000000..f28cff250--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/AddToSceneNode.tsx@@ -0,0 +1,64 @@+import { useCallback } from 'react'+import { Handle, Position } from '@xyflow/react'+import { useAppStore } from '@shared/stores/appStore'+import { useNavStore } from '@shared/stores/navStore'+import type { WFNodeData } from '@shared/types/electron.d'+import BaseNode from './BaseNode'++const INPUT_COLOR = '#a78bfa'++export default function AddToSceneNode({ id, data, selected }: { id: string; data: WFNodeData; selected?: boolean }) {+ const { navigate } = useNavStore()+ const setCurrentJob = useAppStore((s) => s.setCurrentJob)+ const outputUrl = data.params.outputUrl as string | undefined++ const viewIn3D = useCallback(() => {+ if (!outputUrl) return+ setCurrentJob({ id: 'workflow-output', imageFile: '', status: 'done', progress: 100, outputUrl, createdAt: Date.now() })+ navigate('generate')+ }, [outputUrl, setCurrentJob, navigate])++ return (+ <BaseNode+ id={id}+ selected={selected}+ title="Add to Scene"+ minWidth={160}+ icon={+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#a78bfa" strokeWidth="2">+ <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>+ </svg>+ }+ subheader={+ <div className="flex items-center gap-1.5 px-3 py-2">+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-violet-500/30 bg-violet-500/10 text-violet-400">mesh</span>+ <span className="text-[9px] text-zinc-600">→ scene</span>+ </div>+ }+ handles={+ <Handle type="target" position={Position.Left}+ style={{ background: INPUT_COLOR, width: 14, height: 14, border: '2.5px solid #18181b' }} />+ }+ >+ <div className="px-3 pb-3 pt-2.5">+ {outputUrl ? (+ <div className="flex flex-col gap-2">+ <div className="flex items-center gap-1.5">+ <div className="w-1.5 h-1.5 rounded-full bg-emerald-500 shrink-0" />+ <span className="text-[10px] text-emerald-400">Mesh ready</span>+ </div>+ <button onClick={viewIn3D}+ className="nodrag w-full flex items-center justify-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-violet-500/15 border border-violet-500/30 text-violet-400 hover:bg-violet-500/25 hover:border-violet-500/50 transition-colors text-[10px] font-medium">+ Add to 3D scene+ <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <path d="M5 12h14M13 6l6 6-6 6"/>+ </svg>+ </button>+ </div>+ ) : (+ <p className="text-[10px] text-zinc-600 italic">Connect a mesh to add it to the 3D scene.</p>+ )}+ </div>+ </BaseNode>+ )+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/BaseNode.tsx b/apps/forge-desktop/src/areas/workflows/nodes/BaseNode.tsxnew file mode 100644index 000000000..856e528c0--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/BaseNode.tsx@@ -0,0 +1,176 @@+import { useState, useRef } from 'react'+import { NodeResizer, useReactFlow } from '@xyflow/react'+import type { ReactNode } from 'react'++const RESIZER_HANDLE_STYLE = { background: 'transparent', border: 'none', width: 12, height: 12 }++// ─── Props ────────────────────────────────────────────────────────────────────++export interface BaseNodeProps {+ id: string+ selected?: boolean+ running?: boolean++ // Header+ title: string+ icon?: ReactNode // small icon left of title+ badge?: string // e.g. "built-in"++ // Optional controls — only rendered when prop is provided+ enabled?: boolean // shows enable toggle+ showInGenerate?: boolean // shows eye toggle+ deletable?: boolean // default true+ collapsible?: boolean // default false — shows chevron, hides body when collapsed+ defaultExpanded?: boolean // default true++ // Extra slots+ subheader?: ReactNode // always visible, sits between header and body (e.g. IO row)+ handles?: ReactNode // React Flow handles — rendered at root level++ // Resize+ minWidth?: number // default 180+ minHeight?: number // default 60+ autoHeight?: boolean // when true: node sizes to content, no vertical resize++ // Body content (hidden when collapsed)+ children?: ReactNode+}++// ─── BaseNode ─────────────────────────────────────────────────────────────────++export default function BaseNode({+ id, selected, running,+ title, icon, badge,+ enabled, showInGenerate,+ deletable = true,+ collapsible = false,+ defaultExpanded = true,+ subheader, handles,+ minWidth = 180,+ minHeight = 60,+ autoHeight = false,+ children,+}: BaseNodeProps) {+ const { updateNodeData, deleteElements } = useReactFlow()+ const [expanded, setExpanded] = useState(defaultExpanded)+ const rootRef = useRef<HTMLDivElement>(null)++ const isDisabled = enabled === false++ return (+ <div+ ref={rootRef}+ style={autoHeight ? { width: '100%' } : { width: '100%', height: '100%' }}+ className={`relative rounded-xl border bg-zinc-900/95 backdrop-blur-sm shadow-xl transition-all flex flex-col+ ${running ? 'border-accent shadow-[0_0_16px_rgba(99,102,241,0.35)] animate-pulse'+ : selected ? 'border-accent/70'+ : isDisabled ? 'border-zinc-800 opacity-50'+ : 'border-zinc-700'}`}+ >+ <NodeResizer+ minWidth={minWidth} minHeight={autoHeight ? 0 : minHeight}+ lineStyle={{ borderColor: 'transparent' }}+ handleStyle={autoHeight ? { display: 'none' } : RESIZER_HANDLE_STYLE}+ />++ {/* React Flow handles — must live at root level */}+ {handles}++ {/* ── Header ─────────────────────────────────────────────────────────── */}+ <div className="flex items-start px-3 pt-3 pb-2.5 gap-2 shrink-0">++ {running && (+ <div className="shrink-0 mt-0.5">+ <svg className="animate-spin text-accent" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <path d="M21 12a9 9 0 1 1-6.219-8.56"/>+ </svg>+ </div>+ )}+ {!running && icon && <div className="shrink-0 mt-0.5">{icon}</div>}++ <div className="flex-1 min-w-0">+ <p className="text-[11px] font-semibold text-zinc-200 leading-tight truncate">{title}</p>+ {badge && (+ <span className="inline-block mt-0.5 text-[8px] uppercase tracking-wide px-1.5 py-0.5 rounded bg-zinc-700/70 text-zinc-400 border border-zinc-600/50">+ {badge}+ </span>+ )}+ </div>++ {/* Eye — visible in Generate page */}+ {showInGenerate !== undefined && (+ <button+ onClick={() => updateNodeData(id, { showInGenerate: !showInGenerate })}+ title={showInGenerate ? 'Visible in Generate' : 'Hidden from Generate'}+ className="nodrag p-0.5 rounded transition-colors shrink-0 mt-0.5"+ >+ {showInGenerate ? (+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-accent">+ <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>+ <circle cx="12" cy="12" r="3"/>+ </svg>+ ) : (+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-600 hover:text-zinc-400">+ <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/>+ <line x1="1" y1="1" x2="23" y2="23"/>+ </svg>+ )}+ </button>+ )}++ {/* Enable / disable toggle */}+ {enabled !== undefined && (+ <button+ onClick={() => updateNodeData(id, { enabled: !enabled })}+ title={enabled ? 'Disable' : 'Enable'}+ className="nodrag relative shrink-0 mt-0.5"+ style={{ width: 26, height: 15 }}+ >+ <span className={`absolute inset-0 rounded-full transition-colors ${enabled ? 'bg-accent/70' : 'bg-zinc-700'}`} />+ <span className={`absolute top-[1.5px] w-3 h-3 rounded-full bg-white shadow transition-all ${enabled ? 'left-[11px]' : 'left-[1.5px]'}`} />+ </button>+ )}++ {/* Collapse chevron */}+ {collapsible && (+ <button+ onClick={() => setExpanded((v) => !v)}+ className="nodrag p-0.5 rounded text-zinc-600 hover:text-zinc-400 transition-colors shrink-0 mt-0.5"+ >+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"+ className={`transition-transform ${expanded ? 'rotate-180' : ''}`}>+ <polyline points="6 9 12 15 18 9"/>+ </svg>+ </button>+ )}++ {/* Delete */}+ {deletable && (+ <button+ onClick={() => deleteElements({ nodes: [{ id }] })}+ className="nodrag p-0.5 rounded text-zinc-700 hover:text-red-400 transition-colors shrink-0 mt-0.5"+ >+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <line x1="18" y1="6" x2="6" y2="18"/>+ <line x1="6" y1="6" x2="18" y2="18"/>+ </svg>+ </button>+ )}+ </div>++ {/* ── Sub-header (always visible) ────────────────────────────────────── */}+ {subheader && (+ <div className="shrink-0 border-t border-zinc-800/60">+ {subheader}+ </div>+ )}++ {/* ── Body (collapsible) ─────────────────────────────────────────────── */}+ {children && (!collapsible || expanded) && (+ <div className="border-t border-zinc-800 flex-1 min-h-0 flex flex-col">+ {children}+ </div>+ )}+ </div>+ )+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/ExtensionNode.tsx b/apps/forge-desktop/src/areas/workflows/nodes/ExtensionNode.tsxnew file mode 100644index 000000000..17e5f3fa6--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/ExtensionNode.tsx@@ -0,0 +1,298 @@+import { useCallback, useEffect, useRef, useLayoutEffect, useState } from 'react'+import { Handle, Position, useReactFlow } from '@xyflow/react'+import { useExtensionsStore } from '@shared/stores/extensionsStore'+import { useNavStore } from '@shared/stores/navStore'+import { buildAllWorkflowExtensions } from '../mockExtensions'+import type { ParamSchema } from '../mockExtensions'+import type { WFNodeData } from '@shared/types/electron.d'+import { PICKER_LABELS, openParamPicker, resolvePickerIntent } from '@shared/utils/paramPicker'+import { FloatInput, IntInput, PickerIcon } from '@shared/components/ui'+import { isMissingWeightVariant, withWeightVariantAvailability } from '@shared/utils/weightVariants'+import { useWorkflowRunStore } from '../workflowRunStore'+import BaseNode from './BaseNode'++// ─── Handle colors ────────────────────────────────────────────────────────────++const HANDLE_COLOR: Record<string, string> = {+ audio: '#34d399',+ image: '#38bdf8',+ mesh: '#a78bfa',+ text: '#fbbf24',+ scene: '#f472b6',+}++const TAG_CLS: Record<string, string> = {+ audio: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-400',+ image: 'border-sky-500/30 bg-sky-500/10 text-sky-400',+ mesh: 'border-violet-500/30 bg-violet-500/10 text-violet-400',+ text: 'border-amber-500/30 bg-amber-500/10 text-amber-400',+ scene: 'border-pink-500/30 bg-pink-500/10 text-pink-400',+}++// ─── Param control ────────────────────────────────────────────────────────────++// nodrag — without it, React Flow starts dragging the node on mousedown inside+// these fields, so click-drag text selection (or opening a <select>) moves the+// node instead.+const inputCls = 'nodrag w-full bg-zinc-800 border border-zinc-700 rounded-lg px-2 py-1 text-[11px] text-zinc-200 focus:outline-none focus:border-accent/60'++/** Dropdown of the files inside the folder held by another param (dir_from). */+function FileSelectControl({ param, value, dirValue, onChange }: {+ param: ParamSchema+ value: string+ dirValue: string+ onChange: (v: string) => void+}) {+ const [files, setFiles] = useState<string[]>([])+ const extsKey = (param.extensions ?? []).join(',')+ useEffect(() => {+ let alive = true+ if (!dirValue) { setFiles([]); return }+ window.electron.fs.listFiles(dirValue, param.extensions ?? undefined).then((list) => {+ if (alive) setFiles(list)+ }).catch(() => { if (alive) setFiles([]) })+ return () => { alive = false }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [dirValue, extsKey])++ return (+ <select value={value} disabled={!dirValue} onChange={(e) => onChange(e.target.value)}+ className={`${inputCls} ${!dirValue ? 'opacity-50 cursor-not-allowed' : ''}`}>+ <option value="">{!dirValue ? 'Pick a folder first…' : files.length === 0 ? 'No files found' : 'Select…'}</option>+ {/* Keep a saved value visible even if it's no longer in the folder listing. */}+ {value && !files.includes(value) && <option value={value}>{value} (missing)</option>}+ {files.map((f) => <option key={f} value={f}>{f}</option>)}+ </select>+ )+}++function ParamControl({ param, value, onChange, resolvedParams }: {+ param: ParamSchema+ value: number | string+ onChange: (v: number | string) => void+ resolvedParams: Record<string, unknown>+}) {+ if (param.type === 'file-select') {+ const dirValue = String(resolvedParams[param.dir_from ?? ''] ?? '')+ return <FileSelectControl param={param} value={String(value ?? '')} dirValue={dirValue} onChange={onChange} />+ }+ if (param.type === 'select') {+ return (+ <select value={value} onChange={(e) => onChange(e.target.value)} className={inputCls}>+ {param.options?.map((o) => (+ <option key={String(o.value)} value={o.value}>{o.label ?? String(o.value)}</option>+ ))}+ </select>+ )+ }+ if (param.type === 'string') {+ const intent = resolvePickerIntent(param)+ return (+ <div className="flex items-center gap-1">+ <input type="text" value={value as string} placeholder={param.tooltip ?? ''}+ onChange={(e) => onChange(e.target.value)} className={`${inputCls} flex-1`} />+ <button+ onClick={async () => {+ const p = await openParamPicker(param, window.electron.fs)+ if (p) onChange(p)+ }}+ title={PICKER_LABELS[intent]}+ aria-label={PICKER_LABELS[intent]}+ className="nodrag shrink-0 flex items-center justify-center w-6 h-6 rounded bg-zinc-700 hover:bg-zinc-600 text-zinc-400 hover:text-zinc-200 transition-colors"+ >+ <PickerIcon intent={intent} />+ </button>+ </div>+ )+ }+ if (param.type === 'float') {+ return <FloatInput value={value as number} onChange={(v) => onChange(v)} className={inputCls}+ min={param.min} max={param.max} step={param.step} label={param.label} />+ }+ // int+ return <IntInput value={value as number} onChange={(v) => onChange(v)} className={inputCls} />+}++// ─── ExtensionNode ────────────────────────────────────────────────────────────++export default function ExtensionNode({ id, data, selected }: { id: string; data: WFNodeData; selected?: boolean }) {+ const { updateNodeData } = useReactFlow()+ const running = useWorkflowRunStore((s) => s.activeNodeId === id)++ const handleRefs = useRef<HTMLDivElement[]>([])+ const [handleTops, setHandleTops] = useState<string[]>([])++ const { modelExtensions, processExtensions } = useExtensionsStore()+ const installedVariants = useExtensionsStore((s) => (data.extensionId ? s.installedWeightVariants[data.extensionId] : undefined))+ const allExtensions = buildAllWorkflowExtensions(modelExtensions, processExtensions)+ const ext = allExtensions.find((e) => e.id === data.extensionId)+ const openExtension = useNavStore((s) => s.openExtension)++ const inputs = ext?.inputs // defined → multi-input mode+ const isMulti = inputs && inputs.length > 1+ const isTerminal = ext?.id === 'mesh-exporter'+ const outputColor = HANDLE_COLOR[ext?.output ?? 'mesh']+ const hasParams = (ext?.params.length ?? 0) > 0++ // Align handles with their respective IO rows after mount+ useLayoutEffect(() => {+ setHandleTops(handleRefs.current.map((ref) => {+ if (ref) {+ const center = ref.offsetTop + ref.offsetHeight / 2+ return `${center}px`+ }+ return '50%'+ }))+ }, [isMulti, inputs?.length])++ const patchParam = useCallback((key: string, val: number | string) => {+ const params = { ...data.params, [key]: val }+ updateNodeData(id, { params })+ // Push live so a paused/looping run picks up the change on the next node start.+ useWorkflowRunStore.getState().setLiveNodeParams(id, params)+ }, [id, data.params, updateNodeData])++ const paramById = new Map(ext?.params.map((p) => [p.id, p]))++ const isVisible = (param: ParamSchema): boolean => {+ if (!param.show_if) return true+ return Object.entries(param.show_if).every(([key, expected]) => {+ const current = data.params[key] ?? paramById.get(key)?.default+ return Array.isArray(expected) ? expected.includes(current as string | number) : current === expected+ })+ }++ // ── IO subheader ─────────────────────────────────────────────────────────+ const ioSubheader = isMulti ? (+ // Multi-input layout: one row per input (N, not just 2), output on the first row.+ // Row refs feed the same handleRefs array handlesEl aligns its Handles against.+ <div className="flex flex-col divide-y divide-zinc-800/40">+ {inputs.map((inputType, i) => (+ <div key={i} ref={(el) => { if (el) handleRefs.current[i] = el }} className="flex items-center justify-between px-3 py-2">+ <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border ${TAG_CLS[inputType] ?? 'border-zinc-700 bg-zinc-800 text-zinc-400'}`}>+ {ext?.inputLabels?.[i] ?? inputType}+ </span>+ {i === 0 && !isTerminal && (+ <>+ <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-600 shrink-0">+ <line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/>+ </svg>+ <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border ${TAG_CLS[ext?.output ?? ''] ?? 'border-zinc-700 bg-zinc-800 text-zinc-400'}`}>+ {ext?.output ?? '—'}+ </span>+ </>+ )}+ </div>+ ))}+ </div>+ ) : (+ // Single-input layout (existing behavior)+ <div ref={(el) => { if (el) handleRefs.current[0] = el }} className="flex items-center justify-between px-3 py-2">+ <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border ${TAG_CLS[ext?.input ?? ''] ?? 'border-zinc-700 bg-zinc-800 text-zinc-400'}`}>+ {ext?.input ?? '—'}+ </span>+ {!isTerminal && (+ <>+ <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-600 shrink-0">+ <line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/>+ </svg>+ <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border ${TAG_CLS[ext?.output ?? ''] ?? 'border-zinc-700 bg-zinc-800 text-zinc-400'}`}>+ {ext?.output ?? '—'}+ </span>+ </>+ )}+ </div>+ )++ // ── Handles ──────────────────────────────────────────────────────────────+ const handlesEl = isMulti ? (+ <>+ {inputs.map((inputType, i) => (+ <Handle+ key={i}+ id={`input-${i}`}+ type="target"+ position={Position.Left}+ style={{ background: HANDLE_COLOR[inputType], width: 14, height: 14, border: '2.5px solid #18181b', top: handleTops[i] ?? '50%' }}+ />+ ))}+ {!isTerminal && (+ <Handle+ id="output"+ type="source"+ position={Position.Right}+ style={{ background: outputColor, width: 14, height: 14, border: '2.5px solid #18181b', top: handleTops[0] ?? '50%' }}+ />+ )}+ </>+ ) : (+ <>+ <Handle+ id="input-0"+ type="target"+ position={Position.Left}+ style={{ background: HANDLE_COLOR[ext?.input ?? 'image'], width: 14, height: 14, border: '2.5px solid #18181b', top: handleTops[0] ?? '50%' }}+ />+ {!isTerminal && (+ <Handle+ id="output"+ type="source"+ position={Position.Right}+ style={{ background: outputColor, width: 14, height: 14, border: '2.5px solid #18181b', top: handleTops[0] ?? '50%' }}+ />+ )}+ </>+ )++ return (+ <BaseNode+ id={id}+ selected={selected}+ running={running}+ title={ext?.name ?? data.extensionId ?? 'Unknown extension'}+ enabled={data.enabled}+ showInGenerate={data.showInGenerate ?? false}+ collapsible={hasParams}+ minWidth={200}+ subheader={ioSubheader}+ handles={handlesEl}+ >+ {hasParams && (+ <div className="px-3 pb-3 pt-2.5 flex flex-col gap-2">+ {(() => {+ // Effective values of every param (user value or schema default) —+ // lets file-select params resolve their source folder (dir_from).+ const resolvedParams = Object.fromEntries(+ (ext?.params ?? []).map((p) => [p.id, data.params[p.id] ?? p.default]),+ )+ return ext!.params.filter(isVisible).map((param) => {+ const val = (data.params[param.id] ?? param.default) as number | string+ return (+ <div key={param.id} className="flex items-center gap-2">+ <label className="text-[10px] text-zinc-500 w-24 shrink-0 leading-tight">{param.label}</label>+ <div className="flex-1">+ <ParamControl+ param={withWeightVariantAvailability(param, ext?.weightVariants, installedVariants)}+ value={val}+ onChange={(v) => patchParam(param.id, v)}+ resolvedParams={resolvedParams}+ />+ {/* Offer the install instead of leaving the graph on selection. */}+ {ext && isMissingWeightVariant(param.id, val, ext.weightVariants, installedVariants) && (+ <button+ onClick={() => openExtension(ext.extensionId)}+ className="nodrag mt-1 text-[10px] text-amber-400 hover:text-amber-300 hover:underline"+ >+ Not installed — install it+ </button>+ )}+ </div>+ </div>+ )+ })+ })()}+ </div>+ )}+ </BaseNode>+ )+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/ForEachNode.tsx b/apps/forge-desktop/src/areas/workflows/nodes/ForEachNode.tsxnew file mode 100644index 000000000..3b14d3fa4--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/ForEachNode.tsx@@ -0,0 +1,139 @@+import { useLayoutEffect, useRef, useState } from 'react'+import { Handle, Position, useReactFlow } from '@xyflow/react'+import type { WFNodeData } from '@shared/types/electron.d'+import BaseNode from './BaseNode'+import { useWorkflowRunStore } from '../workflowRunStore'++// For Each — an iterator source. It walks a folder alphabetically and emits one+// file per loop pass; every node wired downstream re-runs for each file. Runs to+// completion unless the user hits Stop, with an optional Pause (then Continue →+// next file / Retry → same file). A dropdown picks what it emits: image / text / mesh.+type Mode = 'image' | 'text' | 'mesh'++const MODES: Record<Mode, { title: string; color: string; hint: string }> = {+ image: { title: 'For Each Image', color: '#38bdf8', hint: 'images' },+ text: { title: 'For Each Text', color: '#fbbf24', hint: 'text files' },+ mesh: { title: 'For Each Mesh', color: '#a78bfa', hint: 'meshes' },+}++export default function ForEachNode({ id, data, selected }: { id: string; data: WFNodeData; selected?: boolean }) {+ const { updateNodeData } = useReactFlow()+ const mode = ((data.params.mode as Mode | undefined) ?? 'image')+ const variant = MODES[mode] ?? MODES.image++ const status = useWorkflowRunStore((s) => s.runState.status)+ const activeNodeId = useWorkflowRunStore((s) => s.activeNodeId)+ const continueWhile = useWorkflowRunStore((s) => s.continueWhile)+ const retryWhile = useWorkflowRunStore((s) => s.retryWhile)+ const pauseWhile = useWorkflowRunStore((s) => s.pauseWhile)+ const progress = useWorkflowRunStore((s) => s.whileProgress[id])+ const pausedGroup = useWorkflowRunStore((s) => s.pausedGroup)+ const isPaused = status === 'paused' && (activeNodeId === id || pausedGroup.includes(id))+ const isLooping = status === 'running' && progress != null && !isPaused+ const locked = status === 'running' || status === 'paused'++ const ioRowRef = useRef<HTMLDivElement>(null)+ const [handleTop, setHandleTop] = useState('50%')+ useLayoutEffect(() => {+ if (ioRowRef.current) setHandleTop(`${ioRowRef.current.offsetTop + ioRowRef.current.offsetHeight / 2}px`)+ }, [])++ const dir = (data.params.dir as string | undefined) ?? ''+ const dirLabel = dir ? dir.split(/[\\/]/).filter(Boolean).pop() : 'Pick folder…'++ const pickDir = async (): Promise<void> => {+ const picked = await window.electron.fs.selectDirectory(dir || undefined)+ if (picked) updateNodeData(id, { params: { ...data.params, dir: picked } })+ }++ return (+ <BaseNode+ id={id}+ selected={selected}+ running={isLooping || isPaused}+ title={variant.title}+ showInGenerate={data.showInGenerate ?? false}+ minWidth={200}+ autoHeight+ icon={+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={variant.color} strokeWidth="2">+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>+ </svg>+ }+ subheader={+ <div ref={ioRowRef} className="flex items-center justify-end px-3 py-2">+ {progress && (+ <span className="mr-auto px-1.5 py-0.5 rounded bg-zinc-700/60 text-zinc-300 tabular-nums text-[9px]">+ {progress.total != null ? `${progress.current}/${progress.total}` : progress.current}+ </span>+ )}+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border"+ style={{ borderColor: `${variant.color}55`, background: `${variant.color}18`, color: variant.color }}>+ {mode}+ </span>+ </div>+ }+ handles={+ <Handle type="source" position={Position.Right}+ style={{ background: variant.color, width: 14, height: 14, border: '2.5px solid #18181b', top: handleTop }} />+ }+ >+ <div className="px-3 pb-3 pt-2.5 flex flex-col gap-2">+ {/* Iterated type */}+ <select+ value={mode}+ disabled={locked}+ onChange={(e) => updateNodeData(id, { params: { ...data.params, mode: e.target.value as Mode, dir: undefined } })}+ className={`nodrag w-full bg-zinc-800 border border-zinc-700 rounded-lg px-2.5 py-2 text-[11px] text-zinc-200 focus:outline-none focus:border-zinc-600 ${locked ? 'opacity-50 cursor-not-allowed' : ''}`}+ >+ <option value="image">Image</option>+ <option value="text">Text</option>+ <option value="mesh">Mesh</option>+ </select>++ <button+ onClick={pickDir}+ disabled={locked}+ className={`nodrag w-full flex items-center gap-1.5 bg-zinc-800 border border-zinc-700 rounded-lg px-2.5 py-2 text-[11px] text-zinc-200 ${locked ? 'opacity-50 cursor-not-allowed' : 'hover:border-zinc-600'}`}+ title={dir || `Folder of ${variant.hint}`}+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="shrink-0 text-zinc-500">+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>+ </svg>+ <span className="truncate">{dirLabel}</span>+ </button>++ {/* Run controls */}+ {isLooping && (+ <button+ onClick={pauseWhile}+ className="nodrag flex items-center justify-center gap-1 px-2 py-1 rounded bg-amber-500/20 border border-amber-500/40 text-amber-300 hover:bg-amber-500/30 transition-colors text-[10px] font-medium"+ >+ <svg width="9" height="9" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>+ Pause+ </button>+ )}+ {isPaused && (+ <div className="nodrag flex items-center gap-1.5">+ <button+ onClick={continueWhile}+ className="flex-1 flex items-center justify-center gap-1 px-2 py-1 rounded bg-emerald-500/20 border border-emerald-500/40 text-emerald-300 hover:bg-emerald-500/30 transition-colors text-[10px] font-medium"+ >+ <svg width="8" height="8" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>+ Continue+ </button>+ <button+ onClick={retryWhile}+ className="flex-1 flex items-center justify-center gap-1 px-2 py-1 rounded bg-sky-500/20 border border-sky-500/40 text-sky-300 hover:bg-sky-500/30 transition-colors text-[10px] font-medium"+ >+ <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>+ </svg>+ Retry+ </button>+ </div>+ )}+ </div>+ </BaseNode>+ )+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/ImageNode.tsx b/apps/forge-desktop/src/areas/workflows/nodes/ImageNode.tsxnew file mode 100644index 000000000..7ff44892a--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/ImageNode.tsx@@ -0,0 +1,78 @@+import { useCallback, useLayoutEffect, useRef, useState } from 'react'+import { Handle, Position, useReactFlow } from '@xyflow/react'+import type { WFNodeData } from '@shared/types/electron.d'+import BaseNode from './BaseNode'+import { mimeFromPath } from './imageUtils'++const OUTPUT_COLOR = '#38bdf8'++export default function ImageNode({ id, data, selected }: { id: string; data: WFNodeData; selected?: boolean }) {+ const { updateNodeData } = useReactFlow()+ const ioRowRef = useRef<HTMLDivElement>(null)+ const [handleTop, setHandleTop] = useState('50%')++ useLayoutEffect(() => {+ if (ioRowRef.current) {+ const center = ioRowRef.current.offsetTop + ioRowRef.current.offsetHeight / 2+ setHandleTop(`${center}px`)+ }+ }, [])++ const filePath = data.params.filePath as string | undefined+ const preview = data.params.preview as string | undefined++ const browse = useCallback(async () => {+ const p = await window.electron.fs.selectImage()+ if (!p) return+ const base64 = await window.electron.fs.readFileBase64(p)+ const src = `data:${mimeFromPath(p)};base64,${base64}`+ updateNodeData(id, { params: { ...data.params, filePath: p, preview: src } })+ }, [id, data.params, updateNodeData])++ return (+ <BaseNode+ id={id}+ selected={selected}+ title="Image"+ showInGenerate={data.showInGenerate ?? false}+ minWidth={160}+ icon={+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#38bdf8" strokeWidth="2">+ <rect x="3" y="3" width="18" height="18" rx="2"/>+ <circle cx="8.5" cy="8.5" r="1.5"/>+ <polyline points="21 15 16 10 5 21"/>+ </svg>+ }+ subheader={+ <div ref={ioRowRef} className="flex items-center justify-end px-3 py-2">+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-sky-500/30 bg-sky-500/10 text-sky-400">image</span>+ </div>+ }+ handles={+ <Handle type="source" position={Position.Right}+ style={{ background: OUTPUT_COLOR, width: 14, height: 14, border: '2.5px solid #18181b', top: handleTop }} />+ }+ >+ {preview ? (+ <button onClick={browse} className="nodrag relative flex-1 block group overflow-hidden rounded-b-xl">+ <img src={preview} alt={filePath?.split(/[\\/]/).pop() ?? ''} className="w-full h-full object-cover" />+ <div className="absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-colors flex items-center justify-center">+ <span className="text-[10px] text-white font-medium opacity-0 group-hover:opacity-100 transition-opacity">+ Change…+ </span>+ </div>+ </button>+ ) : (+ <div className="px-3 py-3">+ <button onClick={browse}+ className="nodrag w-full flex items-center gap-2 px-2.5 py-2 rounded-lg border border-dashed border-zinc-700 hover:border-sky-500/50 hover:bg-sky-500/5 transition-colors">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-500 shrink-0">+ <path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>+ </svg>+ <span className="text-[10px] text-zinc-500">Browse…</span>+ </button>+ </div>+ )}+ </BaseNode>+ )+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/ImagePreviewNode.tsx b/apps/forge-desktop/src/areas/workflows/nodes/ImagePreviewNode.tsxnew file mode 100644index 000000000..05cb79876--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/ImagePreviewNode.tsx@@ -0,0 +1,117 @@+import { useEffect, useLayoutEffect, useRef, useState } from 'react'+import { Handle, Position, useEdges, useNodes } from '@xyflow/react'+import { useWorkflowRunStore, fromWorkspaceUrl } from '../workflowRunStore'+import { resolveDataSource } from '../nodeBehaviors'+import BaseNode from './BaseNode'+import { mimeFromPath } from './imageUtils'+import type { WFNode } from '@shared/types/electron.d'++const IO_COLOR = '#38bdf8'++/**+ * Single-image passthrough preview: an image in, the same image forwarded out+ * unchanged. Distinct from PreviewImageNode ("Preview Views"), which is a+ * terminal node for multi-view strip outputs (e.g. MV-Adapter) and has no+ * output handle.+ *+ * Reads the source file straight off disk and renders it as a `data:` URL+ * (rather than an API-served URL) so the preview works without depending on+ * the backend being up or CSP allowances for a remote origin.+ */+export default function ImagePreviewNode({ id, selected }: { id: string; selected?: boolean }) {+ const nodeImageOutputs = useWorkflowRunStore((s) => s.nodeImageOutputs)+ const edges = useEdges()+ const nodes = useNodes()+ const ioRowRef = useRef<HTMLDivElement>(null)+ const [handleTop, setHandleTop] = useState('50%')+ const [dataUrl, setDataUrl] = useState<string | undefined>(undefined)++ useLayoutEffect(() => {+ if (ioRowRef.current) {+ const center = ioRowRef.current.offsetTop + ioRowRef.current.offsetHeight / 2+ setHandleTop(`${center}px`)+ }+ }, [])++ const incomingEdge = edges.find((e) => e.target === id)+ const nodeMap = new Map(nodes.map((n) => [n.id, n as unknown as WFNode]))+ const realSourceId = incomingEdge+ ? resolveDataSource(incomingEdge.source, edges, nodeMap)+ : undefined+ const sourceNode = realSourceId ? nodes.find((n) => n.id === realSourceId) : undefined+ const workspaceUrl = realSourceId ? nodeImageOutputs[realSourceId] : undefined+ const imageFilePath = sourceNode?.type === 'imageNode'+ ? (sourceNode.data as { params?: { filePath?: string } })?.params?.filePath+ : undefined++ useEffect(() => {+ let cancelled = false+ if (!workspaceUrl && !imageFilePath) {+ setDataUrl(undefined)+ return+ }+ ;(async () => {+ try {+ let absPath: string+ if (workspaceUrl) {+ const settings = await window.electron.settings.get()+ absPath = fromWorkspaceUrl(workspaceUrl, settings.workspaceDir)+ } else {+ absPath = imageFilePath!+ }+ const base64 = await window.electron.fs.readFileBase64(absPath)+ if (!cancelled) setDataUrl(`data:${mimeFromPath(absPath)};base64,${base64}`)+ } catch {+ if (!cancelled) setDataUrl(undefined)+ }+ })()+ return () => { cancelled = true }+ }, [workspaceUrl, imageFilePath])++ return (+ <BaseNode+ id={id}+ selected={selected}+ title="Preview Image"+ minWidth={180}+ icon={+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={IO_COLOR} strokeWidth="2">+ <rect x="3" y="3" width="18" height="18" rx="2"/>+ <circle cx="8.5" cy="8.5" r="1.5"/>+ <polyline points="21 15 16 10 5 21"/>+ </svg>+ }+ subheader={+ <div ref={ioRowRef} className="flex items-center justify-between px-3 py-2">+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-sky-500/30 bg-sky-500/10 text-sky-400">image</span>+ <span className="text-[9px] text-zinc-600">→</span>+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-sky-500/30 bg-sky-500/10 text-sky-400">image</span>+ </div>+ }+ handles={+ <>+ <Handle+ type="target"+ position={Position.Left}+ style={{ background: IO_COLOR, width: 14, height: 14, border: '2.5px solid #18181b', top: handleTop }}+ />+ <Handle+ type="source"+ position={Position.Right}+ style={{ background: IO_COLOR, width: 14, height: 14, border: '2.5px solid #18181b', top: handleTop }}+ />+ </>+ }+ >+ <div className="px-2 pb-2 pt-1 flex-1 min-h-0">+ {dataUrl ? (+ <img src={dataUrl} alt="preview" className="nodrag w-full h-full object-contain rounded" />+ ) : (+ <p className="py-3 text-center text-[10px] text-zinc-600 italic">+ Connect an image and run to preview.+ </p>+ )}+ </div>+ </BaseNode>+ )+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/InputNode.tsx b/apps/forge-desktop/src/areas/workflows/nodes/InputNode.tsxnew file mode 100644index 000000000..e9bcf7817--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/InputNode.tsx@@ -0,0 +1,66 @@+import { useCallback, useRef, useLayoutEffect, useState } from 'react'+import { Handle, Position, useReactFlow } from '@xyflow/react'+import type { WFNodeData } from '@shared/types/electron.d'+import BaseNode from './BaseNode'++const HANDLE_COLOR: Record<string, string> = {+ image: '#38bdf8',+ text: '#fbbf24',+}++export default function InputNode({ id, data, selected }: { id: string; data: WFNodeData; selected?: boolean }) {+ const { updateNodeData } = useReactFlow()+ const inputType = data.inputType ?? 'image'+ const handleColor = HANDLE_COLOR[inputType] ?? '#38bdf8'++ // Align handle with the type-toggle row+ const toggleRowRef = useRef<HTMLDivElement>(null)+ const [handleTop, setHandleTop] = useState('50%')++ useLayoutEffect(() => {+ if (toggleRowRef.current) {+ const center = toggleRowRef.current.offsetTop + toggleRowRef.current.offsetHeight / 2+ setHandleTop(`${center}px`)+ }+ }, [])++ const setType = useCallback((t: 'image' | 'text') => {+ updateNodeData(id, { inputType: t })+ }, [id, updateNodeData])++ return (+ <BaseNode+ id={id}+ selected={selected}+ title="Input"+ deletable={false}+ minWidth={160}+ icon={<div className="w-2 h-2 rounded-full bg-zinc-500" />}+ handles={+ <Handle type="source" position={Position.Right}+ style={{ background: handleColor, width: 14, height: 14, border: '2.5px solid #18181b', top: handleTop }} />+ }+ >+ <div ref={toggleRowRef} className="px-3 pb-3 pt-2.5 flex gap-1.5">+ <button+ onClick={() => setType('image')}+ className={`nodrag flex-1 py-1 rounded-lg text-[10px] font-medium transition-colors+ ${inputType === 'image'+ ? 'bg-sky-500/20 text-sky-400 border border-sky-500/40'+ : 'bg-zinc-800 text-zinc-500 border border-zinc-700 hover:border-zinc-600'}`}+ >+ Image+ </button>+ <button+ onClick={() => setType('text')}+ className={`nodrag flex-1 py-1 rounded-lg text-[10px] font-medium transition-colors+ ${inputType === 'text'+ ? 'bg-amber-500/20 text-amber-400 border border-amber-500/40'+ : 'bg-zinc-800 text-zinc-500 border border-zinc-700 hover:border-zinc-600'}`}+ >+ Text+ </button>+ </div>+ </BaseNode>+ )+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/Load3DMeshNode.tsx b/apps/forge-desktop/src/areas/workflows/nodes/Load3DMeshNode.tsxnew file mode 100644index 000000000..1392e9b03--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/Load3DMeshNode.tsx@@ -0,0 +1,101 @@+import { useCallback, useLayoutEffect, useRef, useState } from 'react'+import { Handle, Position, useReactFlow } from '@xyflow/react'+import type { WFNodeData } from '@shared/types/electron.d'+import BaseNode from './BaseNode'++const OUTPUT_COLOR = '#a78bfa'++export default function Load3DMeshNode({ id, data, selected }: { id: string; data: WFNodeData; selected?: boolean }) {+ const { updateNodeData } = useReactFlow()+ const ioRowRef = useRef<HTMLDivElement>(null)+ const [handleTop, setHandleTop] = useState('50%')++ useLayoutEffect(() => {+ if (ioRowRef.current) {+ const center = ioRowRef.current.offsetTop + ioRowRef.current.offsetHeight / 2+ setHandleTop(`${center}px`)+ }+ }, [])++ const source = (data.params.source as 'file' | 'current') ?? 'file'+ const fileName = data.params.fileName as string | undefined++ const browse = useCallback(async () => {+ const p = await window.electron.fs.selectMeshFile()+ if (!p) return+ const name = p.split(/[\\/]/).pop() ?? p+ updateNodeData(id, { params: { ...data.params, filePath: p, fileName: name } })+ }, [id, data.params, updateNodeData])++ const toggleSource = useCallback(() => {+ const next = source === 'file' ? 'current' : 'file'+ updateNodeData(id, { params: { ...data.params, source: next } })+ }, [id, data.params, source, updateNodeData])++ return (+ <BaseNode+ id={id}+ selected={selected}+ title="Load 3D Mesh"+ showInGenerate={data.showInGenerate ?? false}+ minWidth={180}+ icon={+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={OUTPUT_COLOR} strokeWidth="2">+ <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" />+ </svg>+ }+ subheader={+ <div ref={ioRowRef} className="flex items-center justify-end px-3 py-2">+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-violet-500/30 bg-violet-500/10 text-violet-400">mesh</span>+ </div>+ }+ handles={+ <Handle type="source" position={Position.Right}+ style={{ background: OUTPUT_COLOR, width: 14, height: 14, border: '2.5px solid #18181b', top: handleTop }} />+ }+ >+ <div className="px-3 py-2.5 flex flex-col gap-2">+ {/* Toggle: use current model */}+ <button+ onClick={toggleSource}+ className="nodrag flex items-center gap-2 w-full text-left"+ >+ <div className={`w-7 h-4 rounded-full relative transition-colors ${source === 'current' ? 'bg-violet-500' : 'bg-zinc-700'}`}>+ <div className={`absolute top-0.5 w-3 h-3 rounded-full bg-white shadow transition-transform ${source === 'current' ? 'translate-x-3.5' : 'translate-x-0.5'}`} />+ </div>+ <span className="text-[10px] text-zinc-400">Use current model</span>+ </button>++ {/* File picker — disabled when using current */}+ {source === 'file' ? (+ fileName ? (+ <button+ onClick={browse}+ className="nodrag w-full flex items-center gap-2 px-2.5 py-2 rounded-lg bg-zinc-800 hover:bg-zinc-700 transition-colors group"+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke={OUTPUT_COLOR} strokeWidth="2" className="shrink-0">+ <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" />+ </svg>+ <span className="text-[10px] text-zinc-300 truncate flex-1 text-left">{fileName}</span>+ <span className="text-[9px] text-zinc-500 group-hover:text-zinc-400 shrink-0">Change…</span>+ </button>+ ) : (+ <button+ onClick={browse}+ className="nodrag w-full flex items-center gap-2 px-2.5 py-2 rounded-lg border border-dashed border-zinc-700 hover:border-violet-500/50 hover:bg-violet-500/5 transition-colors"+ >+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-500 shrink-0">+ <path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>+ </svg>+ <span className="text-[10px] text-zinc-500">Browse…</span>+ </button>+ )+ ) : (+ <div className="px-2.5 py-2 rounded-lg bg-zinc-800/50 border border-zinc-700/40">+ <span className="text-[10px] text-zinc-500">Will use the model currently loaded in the 3D viewer</span>+ </div>+ )}+ </div>+ </BaseNode>+ )+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/LoadSceneNode.tsx b/apps/forge-desktop/src/areas/workflows/nodes/LoadSceneNode.tsxnew file mode 100644index 000000000..40f3af1c1--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/LoadSceneNode.tsx@@ -0,0 +1,123 @@+import { useCallback, useLayoutEffect, useRef, useState } from 'react'+import { Handle, Position, useReactFlow } from '@xyflow/react'+import type { ReactFlowInstance } from '@xyflow/react'+import type { WFNode, WFNodeData } from '@shared/types/electron.d'++import BaseNode from './BaseNode'+import {+ applySceneValidationResult,+ invalidateValidatedScenePath,+ resolveSceneSourceManifest,+} from '../workflowSceneSource'++const OUTPUT_COLOR = '#f472b6'++async function validateAndPersistScenePath(args: {+ id: string+ nextPath: string+ updateNodeData: ReactFlowInstance<WFNode>['updateNodeData']+}): Promise<void> {+ args.updateNodeData(args.id, (node) => ({+ params: invalidateValidatedScenePath(node.data.params, args.nextPath),+ }))++ const settings = await window.electron.settings.get()+ const resolution = await resolveSceneSourceManifest({+ scenePath: args.nextPath,+ workspaceDir: settings.workspaceDir,+ readFileBase64: window.electron.fs.readFileBase64,+ })++ args.updateNodeData(args.id, (node) => {+ const params = applySceneValidationResult(node.data.params, args.nextPath, resolution)+ return params ? { params } : {}+ })+}++export default function LoadSceneNode({ id, data, selected }: { id: string; data: WFNodeData; selected?: boolean }) {+ const { updateNodeData } = useReactFlow<WFNode>()+ const ioRowRef = useRef<HTMLDivElement>(null)+ const [handleTop, setHandleTop] = useState('50%')++ useLayoutEffect(() => {+ if (ioRowRef.current) {+ const center = ioRowRef.current.offsetTop + ioRowRef.current.offsetHeight / 2+ setHandleTop(`${center}px`)+ }+ }, [])++ const scenePath = typeof data.params.path === 'string' ? data.params.path : ''+ const manifestPath = typeof data.params.manifestPath === 'string' ? data.params.manifestPath : undefined+ const sceneRoot = typeof data.params.sceneRoot === 'string' ? data.params.sceneRoot : undefined+ const error = typeof data.params.error === 'string' ? data.params.error : undefined++ const browseDirectory = useCallback(async () => {+ const path = await window.electron.fs.selectDirectory()+ if (!path) return+ await validateAndPersistScenePath({ id, nextPath: path, updateNodeData })+ }, [id, updateNodeData])++ const validatePath = useCallback(async () => {+ if (!scenePath.trim()) return+ await validateAndPersistScenePath({ id, nextPath: scenePath, updateNodeData })+ }, [id, scenePath, updateNodeData])++ return (+ <BaseNode+ id={id}+ selected={selected}+ title="Load Scene"+ showInGenerate={data.showInGenerate ?? false}+ minWidth={220}+ icon={+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={OUTPUT_COLOR} strokeWidth="2">+ <path d="M4 7h16" />+ <path d="M7 4h10v16H7z" />+ <path d="M10 11h4" />+ <path d="M10 15h4" />+ </svg>+ }+ subheader={+ <div ref={ioRowRef} className="flex items-center justify-end px-3 py-2">+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-pink-500/30 bg-pink-500/10 text-pink-400">scene</span>+ </div>+ }+ handles={+ <Handle+ type="source"+ position={Position.Right}+ style={{ background: OUTPUT_COLOR, width: 14, height: 14, border: '2.5px solid #18181b', top: handleTop }}+ />+ }+ >+ <div className="px-3 py-2.5 flex flex-col gap-2">+ <input+ type="text"+ value={scenePath}+ placeholder="Scenes/castle or Scenes/castle/scene-manifest.json"+ onChange={(event) => updateNodeData(id, { params: invalidateValidatedScenePath(data.params, event.target.value) })}+ className="nodrag w-full rounded-lg border border-zinc-700 bg-zinc-800 px-2.5 py-2 text-[10px] text-zinc-200 placeholder-zinc-600 focus:outline-none focus:border-pink-500/40"+ />+ <div className="flex gap-2">+ <button onClick={browseDirectory} className="nodrag flex-1 rounded-lg border border-zinc-700 px-2 py-1.5 text-[10px] text-zinc-300 hover:border-pink-500/40 hover:bg-pink-500/5 transition-colors">+ Directory...+ </button>+ <button onClick={validatePath} className="nodrag rounded-lg border border-pink-500/30 bg-pink-500/10 px-2 py-1.5 text-[10px] text-pink-300 hover:bg-pink-500/15 transition-colors">+ Validate+ </button>+ </div>+ {manifestPath ? (+ <div className="rounded-lg border border-pink-500/20 bg-pink-500/5 px-2.5 py-2 text-[10px] text-zinc-300">+ <div className="text-pink-400">Manifest: {manifestPath}</div>+ {sceneRoot && <div className="text-zinc-500">sceneRoot: {sceneRoot}</div>}+ </div>+ ) : (+ <div className="rounded-lg border border-zinc-700/70 bg-zinc-900/40 px-2.5 py-2 text-[10px] text-zinc-500">+ Loads an existing workspace scene manifest for downstream scene nodes.+ </div>+ )}+ {error && <div className="text-[10px] text-rose-400">{error}</div>}+ </div>+ </BaseNode>+ )+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/PreviewImageNode.tsx b/apps/forge-desktop/src/areas/workflows/nodes/PreviewImageNode.tsxnew file mode 100644index 000000000..7d7cd4642--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/PreviewImageNode.tsx@@ -0,0 +1,76 @@+import { Handle, Position, useReactFlow } from '@xyflow/react'+import { useWorkflowRunStore } from '../workflowRunStore'+import BaseNode from './BaseNode'++const INPUT_COLOR = '#38bdf8'++/**+ * Preview node for multi-view image outputs (e.g. MV-Adapter Generate Views).+ *+ * Expects a vertical strip PNG where N views are stacked top→bottom.+ * Displays them in a 2×3 grid using CSS background-position cropping.+ */+export default function PreviewImageNode({ id, selected }: { id: string; selected?: boolean }) {+ const nodeImageOutputs = useWorkflowRunStore((s) => s.nodeImageOutputs)+ const { getEdges } = useReactFlow()++ // Find the image URL fed into this node (first matching incoming edge)+ const incomingEdge = getEdges().find((e) => e.target === id)+ const imageUrl = incomingEdge ? nodeImageOutputs[incomingEdge.source] : undefined++ return (+ <BaseNode+ id={id}+ selected={selected}+ title="Preview Views"+ minWidth={200}+ icon={+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={INPUT_COLOR} strokeWidth="2">+ <rect x="3" y="3" width="18" height="18" rx="2"/>+ <circle cx="8.5" cy="8.5" r="1.5"/>+ <polyline points="21 15 16 10 5 21"/>+ </svg>+ }+ subheader={+ <div className="flex items-center gap-1.5 px-3 py-2">+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-sky-500/30 bg-sky-500/10 text-sky-400">image</span>+ <span className="text-[9px] text-zinc-600">→ preview</span>+ </div>+ }+ handles={+ <Handle+ type="target"+ position={Position.Left}+ style={{ background: INPUT_COLOR, width: 14, height: 14, border: '2.5px solid #18181b' }}+ />+ }+ >+ <div className="px-2 pb-2 pt-1">+ {imageUrl ? (+ <div+ className="nodrag grid gap-0.5 rounded overflow-hidden"+ style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}+ >+ {[0, 1, 2, 3, 4, 5].map((i) => (+ <div+ key={i}+ style={{+ aspectRatio: '1',+ backgroundImage: `url(${imageUrl})`,+ backgroundSize: '100% 600%',+ backgroundPosition: `0 ${i * 20}%`,+ backgroundRepeat: 'no-repeat',+ borderRadius: '2px',+ }}+ />+ ))}+ </div>+ ) : (+ <p className="py-2 text-center text-[10px] text-zinc-600 italic">+ Connect a multi-view image to preview.+ </p>+ )}+ </div>+ </BaseNode>+ )+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/TextNode.tsx b/apps/forge-desktop/src/areas/workflows/nodes/TextNode.tsxnew file mode 100644index 000000000..6e329896d--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/TextNode.tsx@@ -0,0 +1,70 @@+import { useEffect, useLayoutEffect, useRef, useState } from 'react'+import { Handle, Position, useReactFlow } from '@xyflow/react'+import type { WFNodeData } from '@shared/types/electron.d'+import BaseNode from './BaseNode'++const OUTPUT_COLOR = '#fbbf24'++export default function TextNode({ id, data, selected }: { id: string; data: WFNodeData; selected?: boolean }) {+ const { updateNodeData, setNodes } = useReactFlow()+ const ioRowRef = useRef<HTMLDivElement>(null)+ const textareaRef = useRef<HTMLTextAreaElement>(null)+ const [handleTop, setHandleTop] = useState('50%')++ useLayoutEffect(() => {+ if (ioRowRef.current) {+ const center = ioRowRef.current.offsetTop + ioRowRef.current.offsetHeight / 2+ setHandleTop(`${center}px`)+ }+ }, [])++ // Clear stored height so React Flow measures content naturally+ useEffect(() => {+ setNodes(nodes => nodes.map(n => n.id === id ? { ...n, height: undefined } : n))+ }, [id, setNodes])++ const text = (data.params.text as string | undefined) ?? ''++ useEffect(() => {+ const ta = textareaRef.current+ if (!ta) return+ ta.style.height = 'auto'+ ta.style.height = `${ta.scrollHeight}px`+ }, [text])++ return (+ <BaseNode+ id={id}+ selected={selected}+ title="Text"+ showInGenerate={data.showInGenerate ?? false}+ minWidth={180}+ autoHeight+ icon={+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#fbbf24" strokeWidth="2">+ <path d="M17 6.1H3M21 12.1H3M15.1 18H3"/>+ </svg>+ }+ subheader={+ <div ref={ioRowRef} className="flex items-center justify-end px-3 py-2">+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-medium border border-amber-500/30 bg-amber-500/10 text-amber-400">text</span>+ </div>+ }+ handles={+ <Handle type="source" position={Position.Right}+ style={{ background: OUTPUT_COLOR, width: 14, height: 14, border: '2.5px solid #18181b', top: handleTop }} />+ }+ >+ <div className="px-3 pb-3 pt-2.5">+ <textarea+ ref={textareaRef}+ value={text}+ onChange={(e) => updateNodeData(id, { params: { ...data.params, text: e.target.value } })}+ placeholder="Enter text…"+ rows={1}+ className="nodrag w-full bg-zinc-800 border border-zinc-700 rounded-lg px-2.5 py-2 text-[11px] text-zinc-200 placeholder-zinc-600 focus:outline-none focus:border-amber-500/40 resize-none leading-relaxed overflow-hidden"+ />+ </div>+ </BaseNode>+ )+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/WaitNode.tsx b/apps/forge-desktop/src/areas/workflows/nodes/WaitNode.tsxnew file mode 100644index 000000000..3f3dff725--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/WaitNode.tsx@@ -0,0 +1,63 @@+import { Handle, Position } from '@xyflow/react'+import type { WFNodeData } from '@shared/types/electron.d'+import { useWaitButton } from '../useWaitButton'+import BaseNode from './BaseNode'++const HANDLE_STYLE = { background: '#71717a', width: 14, height: 14, border: '2.5px solid #18181b' }++export default function WaitNode({ id, data, selected }: { id: string; data: WFNodeData; selected?: boolean }) {+ const { waitState, canContinue, isRunning, label, buttonClass, statusText, onContinue } = useWaitButton(id)++ const subheader = waitState ? (+ <button+ onClick={onContinue}+ disabled={!canContinue}+ className={`nodrag w-full flex items-center justify-center gap-1.5 px-2.5 py-2 border-y transition-colors text-[10px] font-medium ${buttonClass} ${+ canContinue ? (waitState === 'pending' ? 'animate-pulse' : '') : 'opacity-40 cursor-not-allowed'+ }`}+ >+ {isRunning ? (+ <>+ <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" className="animate-spin">+ <path d="M21 12a9 9 0 1 1-6.219-8.56" />+ </svg>+ Running…+ </>+ ) : (+ <>+ <svg width="9" height="9" viewBox="0 0 24 24" fill="currentColor">+ <polygon points="5 3 19 12 5 21 5 3"/>+ </svg>+ {label}+ </>+ )}+ </button>+ ) : undefined++ return (+ <BaseNode+ id={id}+ selected={selected}+ title="Wait"+ minWidth={170}+ showInGenerate={data.showInGenerate ?? false}+ icon={+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#71717a" strokeWidth="2">+ <circle cx="12" cy="12" r="10"/>+ <polyline points="12 6 12 12 16 14"/>+ </svg>+ }+ subheader={subheader}+ handles={+ <>+ <Handle type="target" position={Position.Left} style={HANDLE_STYLE} />+ <Handle type="source" position={Position.Right} style={HANDLE_STYLE} />+ </>+ }+ >+ <div className="px-3 pb-3 pt-2.5">+ <p className="text-[10px] text-zinc-500 italic">{statusText}</p>+ </div>+ </BaseNode>+ )+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/WhileNode.tsx b/apps/forge-desktop/src/areas/workflows/nodes/WhileNode.tsxnew file mode 100644index 000000000..f3a646acc--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/WhileNode.tsx@@ -0,0 +1,108 @@+import { NodeResizer, useReactFlow } from '@xyflow/react'+import type { WFNodeData } from '@shared/types/electron.d'+import { useWorkflowRunStore } from '../workflowRunStore'++// While container — a resizable frame that wraps the loop-body nodes.+// Drop nodes inside it (they become children) to define the body; the runner+// re-runs that body either N times (iterations) or via the manual buttons.+export default function WhileNode({ id, data, selected }: { id: string; data: WFNodeData; selected?: boolean }) {+ const { updateNodeData, deleteElements } = useReactFlow()+ const status = useWorkflowRunStore((s) => s.runState.status)+ const activeNodeId = useWorkflowRunStore((s) => s.activeNodeId)+ const continueWhile = useWorkflowRunStore((s) => s.continueWhile)+ const retryWhile = useWorkflowRunStore((s) => s.retryWhile)+ const progress = useWorkflowRunStore((s) => s.whileProgress[id])+ const isPaused = status === 'paused' && activeNodeId === id+ const isRunning = status === 'running' && activeNodeId === id+ // Lock the iteration count while a run is active so it can't change mid-loop.+ const locked = status === 'running' || status === 'paused'++ return (+ <div+ style={{ width: '100%', height: '100%' }}+ className={`relative rounded-xl border-2 border-dashed flex flex-col+ ${isPaused || isRunning ? 'border-amber-500 bg-amber-500/[0.07]'+ : selected ? 'border-amber-500/70 bg-amber-500/[0.04]'+ : 'border-amber-500/40 bg-amber-500/[0.03]'}`}+ >+ <NodeResizer+ minWidth={260} minHeight={140}+ lineStyle={{ borderColor: 'transparent' }}+ handleStyle={{ background: '#f59e0b', border: 'none', width: 10, height: 10, borderRadius: 3 }}+ isVisible={selected}+ />++ {/* ── Header bar (drag handle) ─────────────────────────────────────── */}+ <div className="flex items-center gap-2 px-3 py-2 shrink-0 bg-amber-500/10 rounded-t-[10px] border-b border-amber-500/20">+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#f59e0b" strokeWidth="2">+ <polyline points="17 1 21 5 17 9"/>+ <path d="M3 11V9a4 4 0 0 1 4-4h14"/>+ <polyline points="7 23 3 19 7 15"/>+ <path d="M21 13v2a4 4 0 0 1-4 4H3"/>+ </svg>+ <span className="text-[11px] font-semibold text-amber-300 leading-none">While</span>++ {/* Iterations counter — 0 / empty = manual only */}+ <label className="nodrag flex items-center gap-1 ml-1 text-[9px] text-amber-400/70">+ <span>loop</span>+ <input+ type="number" min={0}+ value={data.iterations ?? 0}+ disabled={locked}+ onChange={(e) => updateNodeData(id, { iterations: Math.max(0, Number(e.target.value) || 0) })}+ onPointerDown={(e) => e.stopPropagation()}+ className={`nodrag w-11 px-1 py-0.5 bg-zinc-900/80 border border-amber-500/30 rounded text-amber-200 text-center outline-none focus:border-amber-500 ${locked ? 'opacity-50 cursor-not-allowed' : ''}`}+ />+ <span>×</span>+ {progress && (+ <span className="ml-1 px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-200 tabular-nums">+ {progress.total != null ? `${progress.current}/${progress.total}` : progress.current}+ </span>+ )}+ </label>++ <div className="flex-1" />++ {/* Continue / Retry — only while paused on this node */}+ {isPaused && (+ <div className="nodrag flex items-center gap-1">+ <button+ onClick={continueWhile}+ className="flex items-center gap-1 px-2 py-1 rounded bg-emerald-500/20 border border-emerald-500/40 text-emerald-300 hover:bg-emerald-500/30 transition-colors text-[9px] font-medium"+ >+ <svg width="8" height="8" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>+ Continue+ </button>+ <button+ onClick={retryWhile}+ className="flex items-center gap-1 px-2 py-1 rounded bg-amber-500/20 border border-amber-500/40 text-amber-300 hover:bg-amber-500/30 transition-colors text-[9px] font-medium"+ >+ <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <polyline points="23 4 23 10 17 10"/>+ <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>+ </svg>+ Retry+ </button>+ </div>+ )}++ {/* Delete */}+ <button+ onClick={() => deleteElements({ nodes: [{ id }] })}+ className="nodrag p-0.5 rounded text-amber-500/50 hover:text-red-400 transition-colors shrink-0"+ >+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>+ </svg>+ </button>+ </div>++ {/* ── Body drop zone (children render here, on top) ────────────────── */}+ <div className="flex-1 min-h-0 flex items-center justify-center pointer-events-none">+ <span className="text-[10px] text-amber-500/30 italic select-none">+ Drop nodes here to loop them+ </span>+ </div>+ </div>+ )+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/WorkflowEdge.tsx b/apps/forge-desktop/src/areas/workflows/nodes/WorkflowEdge.tsxnew file mode 100644index 000000000..90d32931b--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/WorkflowEdge.tsx@@ -0,0 +1,73 @@+import { getBezierPath, useReactFlow, useEdges } from '@xyflow/react'+import type { EdgeProps } from '@xyflow/react'+import { useExtensionsStore } from '@shared/stores/extensionsStore'+import { buildAllWorkflowExtensions } from '../mockExtensions'++const HANDLE_COLOR: Record<string, string> = {+ audio: '#34d399',+ image: '#38bdf8',+ mesh: '#a78bfa',+ text: '#fbbf24',+}++export default function WorkflowEdge({+ id, source, target,+ sourceX, sourceY, targetX, targetY,+ sourcePosition, targetPosition,+}: EdgeProps) {+ const { getNode } = useReactFlow()+ const edges = useEdges()+ const { modelExtensions, processExtensions } = useExtensionsStore()+ const allExtensions = buildAllWorkflowExtensions(modelExtensions, processExtensions)++ const sourceNode = getNode(source)+ const targetNode = getNode(target)++ // Read targetHandle directly from edge store — reliable regardless of EdgeProps version+ const thisEdge = edges.find((e) => e.id === id)+ const targetHandle = thisEdge?.targetHandle++ const sourceColor = sourceNode?.type === 'imageNode'+ ? HANDLE_COLOR.image+ : sourceNode?.type === 'textNode'+ ? HANDLE_COLOR.text+ : sourceNode?.type === 'meshNode'+ ? HANDLE_COLOR.mesh+ : (HANDLE_COLOR[allExtensions.find((e) => e.id === sourceNode?.data?.extensionId)?.output ?? ''] ?? '#52525b')++ // For multi-input nodes pick the color of the specific connected handle+ const targetExt = allExtensions.find((e) => e.id === targetNode?.data?.extensionId)+ const targetInputType = (() => {+ if (targetExt?.inputs && targetExt.inputs.length > 1 && targetHandle) {+ const idx = parseInt(targetHandle.replace('input-', ''), 10)+ return targetExt.inputs[isNaN(idx) ? 0 : idx] ?? targetExt.input+ }+ return targetExt?.input+ })()++ const targetColor = targetNode?.type === 'outputNode'+ ? HANDLE_COLOR.mesh+ : targetNode?.type === 'previewNode'+ ? HANDLE_COLOR.image+ : (HANDLE_COLOR[targetInputType ?? ''] ?? '#52525b')++ const [edgePath] = getBezierPath({ sourceX, sourceY, sourcePosition, targetX, targetY, targetPosition })+ const gradientId = `wf-edge-${id}`++ return (+ <>+ <defs>+ <linearGradient id={gradientId} gradientUnits="userSpaceOnUse" x1={sourceX} y1={sourceY} x2={targetX} y2={targetY}>+ <stop offset="0%" stopColor={sourceColor} />+ <stop offset="100%" stopColor={targetColor} />+ </linearGradient>+ </defs>+ <path+ d={edgePath}+ fill="none"+ style={{ stroke: `url(#${gradientId})`, strokeWidth: 2.5 }}+ className="react-flow__edge-path"+ />+ </>+ )+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/imageUtils.ts b/apps/forge-desktop/src/areas/workflows/nodes/imageUtils.tsnew file mode 100644index 000000000..44dd5327a--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/imageUtils.ts@@ -0,0 +1,8 @@+// Shared helpers for node components that read image files from disk.++export function mimeFromPath(p: string): string {+ const ext = p.split('.').pop()?.toLowerCase() ?? ''+ if (ext === 'jpg' || ext === 'jpeg') return 'image/jpeg'+ if (ext === 'webp') return 'image/webp'+ return 'image/png'+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/mesh-exporter/manifest.json b/apps/forge-desktop/src/areas/workflows/nodes/mesh-exporter/manifest.jsonnew file mode 100644index 000000000..20eb7a860--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/mesh-exporter/manifest.json@@ -0,0 +1,39 @@+{+ "id": "mesh-exporter",+ "name": "Mesh Exporter",+ "type": "process",+ "entry": "processor.js",+ "version": "1.0.0",+ "author": "Modly",+ "description": "Exports the mesh to a chosen format (GLB, STL, OBJ, PLY) at a specified output path.",+ "nodes": [+ {+ "id": "export",+ "name": "Export Mesh",+ "input": "mesh",+ "output": "mesh",+ "params_schema": [+ {+ "id": "export_format",+ "label": "Export Format",+ "type": "select",+ "default": "glb",+ "options": [+ { "value": "glb", "label": "GLB (Binary glTF)" },+ { "value": "stl", "label": "STL (3D printing)" },+ { "value": "obj", "label": "OBJ (Wavefront)" },+ { "value": "ply", "label": "PLY (Polygon)" }+ ],+ "tooltip": "Output file format."+ },+ {+ "id": "output_path",+ "label": "Output Path",+ "type": "string",+ "default": "",+ "tooltip": "Destination folder. Leave empty to save in the workspace Exports folder."+ }+ ]+ }+ ]+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/mesh-exporter/package.json b/apps/forge-desktop/src/areas/workflows/nodes/mesh-exporter/package.jsonnew file mode 100644index 000000000..3d709cac0--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/mesh-exporter/package.json@@ -0,0 +1,9 @@+{+ "name": "mesh-exporter",+ "version": "1.0.0",+ "private": true,+ "dependencies": {+ "@gltf-transform/core": "^3.9.0",+ "@gltf-transform/extensions": "^3.9.0"+ }+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/mesh-exporter/processor.ts b/apps/forge-desktop/src/areas/workflows/nodes/mesh-exporter/processor.tsnew file mode 100644index 000000000..4c1885611--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/mesh-exporter/processor.ts@@ -0,0 +1,231 @@+import path = require('path')+import fs = require('fs')++interface ProcessInput { filePath?: string; text?: string }+interface ProcessResult { filePath?: string; text?: string }+interface ProcessContext {+ workspaceDir: string+ tempDir: string+ log: (msg: string) => void+ progress: (pct: number, label: string) => void+}++// ─── Geometry extraction ──────────────────────────────────────────────────────++interface PrimGeometry {+ positions: Float32Array+ normals: Float32Array | null+ uvs: Float32Array | null+ indices: number[]+}++function extractPrimitives(doc: any): PrimGeometry[] {+ const result: PrimGeometry[] = []+ for (const mesh of doc.getRoot().listMeshes()) {+ for (const prim of mesh.listPrimitives()) {+ const posArr = prim.getAttribute('POSITION')?.getArray() as Float32Array | null+ if (!posArr) continue+ const normArr = (prim.getAttribute('NORMAL')?.getArray() as Float32Array | null) ?? null+ const uvArr = (prim.getAttribute('TEXCOORD_0')?.getArray() as Float32Array | null) ?? null+ const idxRaw = prim.getIndices()?.getArray() ?? null+ const vertCount = posArr.length / 3+ const indices = idxRaw+ ? Array.from(idxRaw as Uint16Array | Uint32Array)+ : Array.from({ length: vertCount }, (_, i) => i)+ result.push({ positions: posArr, normals: normArr, uvs: uvArr, indices })+ }+ }+ return result+}++// ─── STL (binary) ─────────────────────────────────────────────────────────────++function faceNormal(p: Float32Array, i0: number, i1: number, i2: number): [number, number, number] {+ const ax = p[i1*3]-p[i0*3], ay = p[i1*3+1]-p[i0*3+1], az = p[i1*3+2]-p[i0*3+2]+ const bx = p[i2*3]-p[i0*3], by = p[i2*3+1]-p[i0*3+1], bz = p[i2*3+2]-p[i0*3+2]+ const nx = ay*bz - az*by, ny = az*bx - ax*bz, nz = ax*by - ay*bx+ const len = Math.sqrt(nx*nx + ny*ny + nz*nz) || 1+ return [nx/len, ny/len, nz/len]+}++function writeSTL(prims: PrimGeometry[], outPath: string): void {+ let totalTri = 0+ for (const p of prims) totalTri += Math.floor(p.indices.length / 3)++ const buf = Buffer.allocUnsafe(84 + totalTri * 50)+ buf.fill(0, 0, 80)+ buf.writeUInt32LE(totalTri, 80)++ let off = 84+ for (const { positions: p, normals: n, indices } of prims) {+ for (let i = 0; i + 2 < indices.length; i += 3) {+ const i0 = indices[i], i1 = indices[i+1], i2 = indices[i+2]++ let nx: number, ny: number, nz: number+ if (n) {+ nx = (n[i0*3] + n[i1*3] + n[i2*3]) / 3+ ny = (n[i0*3+1] + n[i1*3+1] + n[i2*3+1]) / 3+ nz = (n[i0*3+2] + n[i1*3+2] + n[i2*3+2]) / 3+ } else {+ ;[nx, ny, nz] = faceNormal(p, i0, i1, i2)+ }++ buf.writeFloatLE(nx, off); off += 4+ buf.writeFloatLE(ny, off); off += 4+ buf.writeFloatLE(nz, off); off += 4++ for (const vi of [i0, i1, i2]) {+ buf.writeFloatLE(p[vi*3], off); off += 4+ buf.writeFloatLE(p[vi*3+1], off); off += 4+ buf.writeFloatLE(p[vi*3+2], off); off += 4+ }+ buf.writeUInt16LE(0, off); off += 2+ }+ }++ fs.writeFileSync(outPath, buf)+}++// ─── OBJ ──────────────────────────────────────────────────────────────────────++function writeOBJ(prims: PrimGeometry[], outPath: string): void {+ const lines: string[] = ['# Exported by Modly mesh-exporter', '']+ let vOff = 1, vnOff = 1, vtOff = 1++ for (let pi = 0; pi < prims.length; pi++) {+ const { positions: p, normals: n, uvs: uv, indices } = prims[pi]+ const vc = p.length / 3++ lines.push(`g mesh_${pi}`)++ for (let i = 0; i < p.length; i += 3)+ lines.push(`v ${p[i].toFixed(6)} ${p[i+1].toFixed(6)} ${p[i+2].toFixed(6)}`)++ if (n) for (let i = 0; i < n.length; i += 3)+ lines.push(`vn ${n[i].toFixed(6)} ${n[i+1].toFixed(6)} ${n[i+2].toFixed(6)}`)++ if (uv) for (let i = 0; i < uv.length; i += 2)+ lines.push(`vt ${uv[i].toFixed(6)} ${uv[i+1].toFixed(6)}`)++ for (let i = 0; i + 2 < indices.length; i += 3) {+ const [a, b, c] = [indices[i]+vOff, indices[i+1]+vOff, indices[i+2]+vOff]+ if (n && uv) {+ const [ua, ub, uc] = [indices[i]+vtOff, indices[i+1]+vtOff, indices[i+2]+vtOff]+ const [na, nb, nc] = [indices[i]+vnOff, indices[i+1]+vnOff, indices[i+2]+vnOff]+ lines.push(`f ${a}/${ua}/${na} ${b}/${ub}/${nb} ${c}/${uc}/${nc}`)+ } else if (n) {+ const [na, nb, nc] = [indices[i]+vnOff, indices[i+1]+vnOff, indices[i+2]+vnOff]+ lines.push(`f ${a}//${na} ${b}//${nb} ${c}//${nc}`)+ } else {+ lines.push(`f ${a} ${b} ${c}`)+ }+ }++ vOff += vc+ if (n) vnOff += n.length / 3+ if (uv) vtOff += uv.length / 2+ }++ fs.writeFileSync(outPath, lines.join('\n'), 'utf-8')+}++// ─── PLY (ASCII) ──────────────────────────────────────────────────────────────++function writePLY(prims: PrimGeometry[], outPath: string): void {+ let totalVerts = 0, totalFaces = 0+ let hasNormals = true+ for (const p of prims) {+ totalVerts += p.positions.length / 3+ totalFaces += Math.floor(p.indices.length / 3)+ if (!p.normals) hasNormals = false+ }++ const header = [+ 'ply',+ 'format ascii 1.0',+ 'comment Exported by Modly mesh-exporter',+ `element vertex ${totalVerts}`,+ 'property float x', 'property float y', 'property float z',+ ...(hasNormals ? ['property float nx', 'property float ny', 'property float nz'] : []),+ `element face ${totalFaces}`,+ 'property list uchar int vertex_indices',+ 'end_header',+ ]++ const vertLines: string[] = []+ const faceLines: string[] = []+ let vertOffset = 0++ for (const { positions: p, normals: n, indices } of prims) {+ const vc = p.length / 3+ for (let i = 0; i < vc; i++) {+ const row = [p[i*3].toFixed(6), p[i*3+1].toFixed(6), p[i*3+2].toFixed(6)]+ if (hasNormals) {+ if (n) row.push(n[i*3].toFixed(6), n[i*3+1].toFixed(6), n[i*3+2].toFixed(6))+ else row.push('0.000000', '0.000000', '0.000000')+ }+ vertLines.push(row.join(' '))+ }+ for (let i = 0; i + 2 < indices.length; i += 3)+ faceLines.push(`3 ${indices[i]+vertOffset} ${indices[i+1]+vertOffset} ${indices[i+2]+vertOffset}`)+ vertOffset += vc+ }++ fs.writeFileSync(outPath, [...header, ...vertLines, ...faceLines].join('\n'), 'utf-8')+}++// ─── Main ─────────────────────────────────────────────────────────────────────++const EXT_MAP: Record<string, string> = { glb: '.glb', stl: '.stl', obj: '.obj', ply: '.ply' }++const processor = async (+ input: ProcessInput,+ params: Record<string, unknown>,+ context: ProcessContext,+): Promise<ProcessResult> => {+ if (!input.filePath) throw new Error('mesh-exporter: input.filePath is required')++ const format = String(params['export_format'] ?? 'glb').toLowerCase()+ const outputPath = String(params['output_path'] ?? '').trim()++ const ext = EXT_MAP[format]+ if (!ext) throw new Error(`mesh-exporter: unsupported format "${format}"`)++ context.log(`Format: ${format} — input: ${input.filePath}`)++ const { NodeIO } = require('@gltf-transform/core')+ const { ALL_EXTENSIONS } = require('@gltf-transform/extensions')+ const io = new NodeIO().registerExtensions(ALL_EXTENSIONS)++ context.progress(20, 'Loading mesh…')+ const doc = await io.read(input.filePath)++ let outPath: string+ if (outputPath) {+ fs.mkdirSync(outputPath, { recursive: true })+ outPath = path.join(outputPath, `export-${Date.now()}${ext}`)+ } else {+ const exportsDir = path.join(context.workspaceDir, 'Exports')+ fs.mkdirSync(exportsDir, { recursive: true })+ outPath = path.join(exportsDir, `export-${Date.now()}${ext}`)+ }+ fs.mkdirSync(path.dirname(outPath), { recursive: true })++ context.progress(50, `Exporting as ${format.toUpperCase()}…`)++ if (format === 'glb') {+ await io.write(outPath, doc)+ } else {+ const prims = extractPrimitives(doc)+ if (prims.length === 0) throw new Error('mesh-exporter: no mesh data found in input')+ if (format === 'stl') writeSTL(prims, outPath)+ else if (format === 'obj') writeOBJ(prims, outPath)+ else if (format === 'ply') writePLY(prims, outPath)+ }++ context.progress(100, 'Done')+ context.log(`Output: ${outPath}`)+ return { filePath: outPath }+}++export = processordiff --git a/apps/forge-desktop/src/areas/workflows/nodes/mesh-optimizer/manifest.json b/apps/forge-desktop/src/areas/workflows/nodes/mesh-optimizer/manifest.jsonnew file mode 100644index 000000000..e2480dda0--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/mesh-optimizer/manifest.json@@ -0,0 +1,28 @@+{+ "id": "mesh-optimizer",+ "name": "Mesh Optimizer",+ "type": "process",+ "entry": "processor.py",+ "version": "1.0.0",+ "author": "Modly",+ "description": "Reduces mesh triangle count using quadric simplification (meshoptimizer).",+ "nodes": [+ {+ "id": "optimize",+ "name": "Optimize Mesh",+ "input": "mesh",+ "output": "mesh",+ "params_schema": [+ {+ "id": "target_faces",+ "label": "Target Triangles",+ "type": "int",+ "default": 10000,+ "min": 100,+ "max": 1000000,+ "tooltip": "Target number of triangles after simplification."+ }+ ]+ }+ ]+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/mesh-optimizer/package.json b/apps/forge-desktop/src/areas/workflows/nodes/mesh-optimizer/package.jsonnew file mode 100644index 000000000..b341f66b5--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/mesh-optimizer/package.json@@ -0,0 +1,11 @@+{+ "name": "mesh-optimizer",+ "version": "1.0.0",+ "private": true,+ "dependencies": {+ "@gltf-transform/core": "^3.9.0",+ "@gltf-transform/extensions": "^3.9.0",+ "@gltf-transform/functions": "^3.9.0",+ "meshoptimizer": "^0.22.0"+ }+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/mesh-optimizer/processor.py b/apps/forge-desktop/src/areas/workflows/nodes/mesh-optimizer/processor.pynew file mode 100644index 000000000..c28428738--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/mesh-optimizer/processor.py@@ -0,0 +1,22 @@+"""Thin workflow adapter for the shared meshoptimizer operation."""++import os+import sys+from pathlib import Path+++api_dir = os.environ.get("MODLY_API_DIR")+if not api_dir:+ for parent in Path(__file__).resolve().parents:+ candidate = parent / "api"+ if candidate.is_dir():+ api_dir = str(candidate)+ break+if api_dir and api_dir not in sys.path:+ sys.path.insert(0, api_dir)++from services.mesh_ops.processor import run_processor+++if __name__ == "__main__":+ run_processor("decimate", "mesh-optimizer")diff --git a/apps/forge-desktop/src/areas/workflows/nodes/mesh-remesher/manifest.json b/apps/forge-desktop/src/areas/workflows/nodes/mesh-remesher/manifest.jsonnew file mode 100644index 000000000..2f4c72b6c--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/mesh-remesher/manifest.json@@ -0,0 +1,41 @@+{+ "id": "mesh-remesher",+ "name": "Mesh Remesher",+ "type": "process",+ "entry": "processor.py",+ "version": "1.0.0",+ "author": "Modly",+ "description": "Regularizes mesh topology with isotropic remeshing. Quad mode is quad-dominant cleanup, not character retopology.",+ "nodes": [+ {+ "id": "remesh",+ "name": "Remesh",+ "input": "mesh",+ "output": "mesh",+ "params_schema": [+ {+ "id": "mode",+ "label": "Mode",+ "type": "select",+ "default": "triangle",+ "options": [+ { "value": "triangle", "label": "Triangle" },+ { "value": "quad", "label": "Quad-Dominant" },+ { "value": "none", "label": "None" }+ ],+ "tooltip": "Triangle produces a clean uniform triangulation. Quad-Dominant attempts more regular polygon flow for cleanup, but it is not character-oriented retopology. None passes the mesh through unchanged."+ },+ {+ "id": "target_edge_length",+ "label": "Target Edge Length",+ "type": "float",+ "default": 0.0,+ "min": 0.0,+ "max": 1.0,+ "step": 0.001,+ "tooltip": "Target edge length in world units. Set to 0 for automatic (uses average edge length of the input mesh)."+ }+ ]+ }+ ]+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/mesh-remesher/processor.py b/apps/forge-desktop/src/areas/workflows/nodes/mesh-remesher/processor.pynew file mode 100644index 000000000..06efb63e8--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/mesh-remesher/processor.py@@ -0,0 +1,131 @@+"""+Mesh Remesher — built-in process extension.++Protocol: reads one JSON line from stdin, writes JSON lines to stdout.+ stdin : { input, params, workspaceDir, tempDir }+ stdout: { type: "progress"|"log"|"done"|"error", ... }+"""+import json+import os+import shutil+import sys+import tempfile+from pathlib import Path+++def emit(obj: dict) -> None:+ print(json.dumps(obj), flush=True)+++def progress(pct: int, label: str) -> None:+ emit({"type": "progress", "percent": pct, "label": label})+++def log(msg: str) -> None:+ emit({"type": "log", "message": msg})+++def done(file_path: str) -> None:+ emit({"type": "done", "result": {"filePath": file_path}})+++def error(msg: str) -> None:+ emit({"type": "error", "message": msg})+++def main() -> None:+ raw = sys.stdin.readline()+ data = json.loads(raw)++ input_data = data.get("input", {})+ params = data.get("params", {})+ workspace_dir = data.get("workspaceDir", "")++ input_path = input_data.get("filePath")+ if not input_path or not Path(input_path).is_file():+ error(f"mesh-remesher: input file not found: {input_path}")+ return++ mode = str(params.get("mode", "triangle"))+ target_edge_length = float(params.get("target_edge_length", 0.0))++ out_dir = Path(workspace_dir) / "Workflows"+ out_dir.mkdir(parents=True, exist_ok=True)+ from time import time+ out_path = str(out_dir / f"mesh-remesher-{int(time() * 1000)}.glb")++ log(f"Mode: {mode}, edge length: {target_edge_length or 'auto'}")++ if mode == "none":+ progress(50, "Passing through…")+ shutil.copy2(input_path, out_path)+ progress(100, "Done")+ done(out_path)+ return++ try:+ import pymeshlab+ except ImportError:+ error("mesh-remesher: pymeshlab is not available on this system")+ return++ import trimesh++ progress(10, "Loading mesh…")+ loaded = trimesh.load(input_path)+ if isinstance(loaded, trimesh.Scene):+ geoms = list(loaded.geometry.values())+ geom = trimesh.util.concatenate(geoms) if len(geoms) > 1 else geoms[0]+ else:+ geom = loaded++ tmp_dir = tempfile.mkdtemp()+ try:+ ply_in = os.path.join(tmp_dir, "input.ply")+ ply_out = os.path.join(tmp_dir, "output.ply")+ geom.export(ply_in)++ ms = pymeshlab.MeshSet()+ ms.load_new_mesh(ply_in)++ if target_edge_length <= 0:+ measures = ms.get_geometric_measures()+ target_edge_length = float(measures.get("avg_edge_length", 0.02))+ log(f"Auto edge length: {target_edge_length:.6f}")++ progress(30, f"Remeshing ({mode})…")++ if mode == "triangle":+ ms.meshing_isotropic_explicit_remeshing(+ targetlen=pymeshlab.PureValue(target_edge_length),+ iterations=3,+ )+ elif mode == "quad":+ ms.meshing_isotropic_explicit_remeshing(+ targetlen=pymeshlab.PureValue(target_edge_length),+ iterations=3,+ )+ try:+ ms.generate_polygonal_mesh()+ ms.meshing_poly_to_tri()+ except Exception:+ pass++ progress(80, "Exporting…")+ ms.save_current_mesh(ply_out)+ result = trimesh.load(ply_out, force="mesh")+ finally:+ shutil.rmtree(tmp_dir, ignore_errors=True)++ result.export(out_path)+ log(f"Output: {out_path} ({len(result.faces)} faces)")+ progress(100, "Done")+ done(out_path)+++if __name__ == "__main__":+ try:+ main()+ except Exception as exc:+ import traceback+ error(f"{exc}\n{traceback.format_exc()}")diff --git a/apps/forge-desktop/src/areas/workflows/nodes/mesh-repair/manifest.json b/apps/forge-desktop/src/areas/workflows/nodes/mesh-repair/manifest.jsonnew file mode 100644index 000000000..fb44ef57c--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/mesh-repair/manifest.json@@ -0,0 +1,56 @@+{+ "id": "mesh-repair",+ "name": "Mesh Repair",+ "type": "process",+ "entry": "processor.py",+ "version": "1.2.0",+ "author": "Modly",+ "description": "Repairs mesh topology: removes duplicates, degenerate faces, fixes non-manifold edges, fills simple boundary holes.",+ "nodes": [+ {+ "id": "repair",+ "name": "Repair",+ "input": "mesh",+ "output": "mesh",+ "params_schema": [+ {+ "id": "remove_duplicates",+ "label": "Remove Duplicates",+ "type": "boolean",+ "default": true,+ "tooltip": "Remove duplicate vertices and faces."+ },+ {+ "id": "remove_degenerate",+ "label": "Remove Degenerate Faces",+ "type": "boolean",+ "default": true,+ "tooltip": "Remove zero-area faces and collapsed edges."+ },+ {+ "id": "fix_non_manifold",+ "label": "Fix Non-Manifold",+ "type": "boolean",+ "default": true,+ "tooltip": "Detach faces causing non-manifold edges."+ },+ {+ "id": "fill_holes",+ "label": "Fill Holes",+ "type": "boolean",+ "default": true,+ "tooltip": "Fill simple boundary holes. Structural holes from AI generation may not be fillable in post-processing."+ },+ {+ "id": "max_hole_size",+ "label": "Max Hole Size",+ "type": "int",+ "default": 2000,+ "min": 10,+ "max": 10000,+ "tooltip": "Maximum number of boundary edges of a hole to be filled. Increase if large holes remain open."+ }+ ]+ }+ ]+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/mesh-repair/processor.py b/apps/forge-desktop/src/areas/workflows/nodes/mesh-repair/processor.pynew file mode 100644index 000000000..6ff43d026--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/mesh-repair/processor.py@@ -0,0 +1,22 @@+"""Thin workflow adapter for the shared repair mesh operation."""++import os+import sys+from pathlib import Path+++api_dir = os.environ.get("MODLY_API_DIR")+if not api_dir:+ for parent in Path(__file__).resolve().parents:+ candidate = parent / "api"+ if candidate.is_dir():+ api_dir = str(candidate)+ break+if api_dir and api_dir not in sys.path:+ sys.path.insert(0, api_dir)++from services.mesh_ops.processor import run_processor+++if __name__ == "__main__":+ run_processor("repair", "mesh-repair")diff --git a/apps/forge-desktop/src/areas/workflows/nodes/mesh-smoother/manifest.json b/apps/forge-desktop/src/areas/workflows/nodes/mesh-smoother/manifest.jsonnew file mode 100644index 000000000..4a84affc3--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/mesh-smoother/manifest.json@@ -0,0 +1,49 @@+{+ "id": "mesh-smoother",+ "name": "Mesh Smoother",+ "type": "process",+ "entry": "processor.py",+ "version": "1.0.0",+ "author": "Modly",+ "description": "Smooths mesh vertices to reduce sharp artifacts (e.g. zipper triangles from AI-generated meshes) using Taubin smoothing.",+ "nodes": [+ {+ "id": "smooth",+ "name": "Smooth",+ "input": "mesh",+ "output": "mesh",+ "params_schema": [+ {+ "id": "iterations",+ "label": "Iterations",+ "type": "int",+ "default": 5,+ "min": 1,+ "max": 50,+ "tooltip": "Number of smoothing passes. More iterations = smoother result but may lose fine details."+ },+ {+ "id": "lambda_",+ "label": "Smoothing Strength",+ "type": "float",+ "default": 0.5,+ "min": 0.1,+ "max": 1.0,+ "step": 0.05,+ "tooltip": "Controls how far each vertex moves toward its neighbours per iteration. Lower = more conservative."+ },+ {+ "id": "mode",+ "label": "Mode",+ "type": "select",+ "default": "taubin",+ "options": [+ { "value": "taubin", "label": "Taubin (volume-preserving)" },+ { "value": "laplacian", "label": "Laplacian (stronger, may shrink)" }+ ],+ "tooltip": "Taubin alternates positive/negative steps to prevent mesh shrinkage. Laplacian is simpler but tends to shrink the mesh over many iterations."+ }+ ]+ }+ ]+}diff --git a/apps/forge-desktop/src/areas/workflows/nodes/mesh-smoother/processor.py b/apps/forge-desktop/src/areas/workflows/nodes/mesh-smoother/processor.pynew file mode 100644index 000000000..b59dcb380--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/nodes/mesh-smoother/processor.py@@ -0,0 +1,22 @@+"""Thin workflow adapter for the shared smooth mesh operation."""++import os+import sys+from pathlib import Path+++api_dir = os.environ.get("MODLY_API_DIR")+if not api_dir:+ for parent in Path(__file__).resolve().parents:+ candidate = parent / "api"+ if candidate.is_dir():+ api_dir = str(candidate)+ break+if api_dir and api_dir not in sys.path:+ sys.path.insert(0, api_dir)++from services.mesh_ops.processor import run_processor+++if __name__ == "__main__":+ run_processor("smooth", "mesh-smoother")diff --git a/apps/forge-desktop/src/areas/workflows/preflight.test.mjs b/apps/forge-desktop/src/areas/workflows/preflight.test.mjsnew file mode 100644index 000000000..3b4df8aa8--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/preflight.test.mjs@@ -0,0 +1,168 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++// Bundle preflight.ts (and its real dependency mockExtensions.ts) into CJS.+// All @shared/* imports in those files are type-only, so esbuild erases them+// and no path-alias resolution is required.+function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-preflight-test-')), 'preflight.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('src/areas/workflows/preflight.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++// ─── Fixtures ────────────────────────────────────────────────────────────────++function ext(overrides = {}) {+ return {+ id: 'pack/process-node',+ extensionId: 'pack',+ extensionName: 'Pack',+ extensionAuthor: 'tester',+ nodeId: 'process-node',+ name: 'Process Node',+ description: '',+ input: 'image',+ output: 'mesh',+ params: [],+ builtin: false,+ type: 'process',+ ...overrides,+ }+}++function wf(nodes, edges = []) {+ return { id: 'wf', name: 'wf', description: '', nodes, edges, createdAt: '', updatedAt: '' }+}++const imageNode = (id = 'img') => ({ id, type: 'imageNode', position: { x: 0, y: 0 }, data: {} })+const textNode = (id = 'txt') => ({ id, type: 'textNode', position: { x: 0, y: 0 }, data: {} })++// ─── Tests ───────────────────────────────────────────────────────────────────++test('valid graph (image → extension expecting image) produces no issues', () => {+ const { validateWorkflowPreflight } = loadModule()+ const extensions = [ext()]+ const workflow = wf(+ [imageNode('img'), { id: 'proc', type: 'extensionNode', position: { x: 0, y: 0 }, data: { extensionId: 'pack/process-node' } }],+ [{ id: 'e1', source: 'img', target: 'proc' }],+ )++ assert.deepEqual(validateWorkflowPreflight(workflow, extensions), [])+})++test('extension node with no matching incoming connection is flagged', () => {+ const { validateWorkflowPreflight } = loadModule()+ const extensions = [ext()]+ const workflow = wf(+ [{ id: 'proc', type: 'extensionNode', position: { x: 0, y: 0 }, data: { extensionId: 'pack/process-node' } }],+ [],+ )++ const issues = validateWorkflowPreflight(workflow, extensions)+ assert.equal(issues.length, 1)+ assert.equal(issues[0].key, 'proc:missing:image')+ assert.match(issues[0].message, /needs an incoming image connection/)+})++test('type mismatch on an incoming edge is flagged', () => {+ const { validateWorkflowPreflight } = loadModule()+ const extensions = [ext()] // expects image+ const workflow = wf(+ [textNode('txt'), { id: 'proc', type: 'extensionNode', position: { x: 0, y: 0 }, data: { extensionId: 'pack/process-node' } }],+ [{ id: 'e1', source: 'txt', target: 'proc' }],+ )++ const issues = validateWorkflowPreflight(workflow, extensions)+ // missing required image input AND a text→image type mismatch+ assert.ok(issues.some((i) => i.key === 'proc:missing:image'))+ assert.ok(issues.some((i) => i.key === 'proc:type:e1' && /outputs text/.test(i.message)))+})++test('unknown extension id is reported as unavailable', () => {+ const { validateWorkflowPreflight } = loadModule()+ const workflow = wf(+ [{ id: 'proc', type: 'extensionNode', position: { x: 0, y: 0 }, data: { extensionId: 'ghost/node' } }],+ [],+ )++ const issues = validateWorkflowPreflight(workflow, [])+ assert.equal(issues.length, 1)+ assert.equal(issues[0].key, 'proc:missing-extension')+ assert.match(issues[0].message, /unavailable/)+})++test('meshNode set to current scene flags when no mesh is loaded', () => {+ const { validateWorkflowPreflight } = loadModule()+ const workflow = wf([+ { id: 'mesh', type: 'meshNode', position: { x: 0, y: 0 }, data: { params: { source: 'current' } } },+ ])++ const without = validateWorkflowPreflight(workflow, [], { currentMeshUrl: null })+ assert.equal(without.length, 1)+ assert.equal(without[0].key, 'mesh:current-mesh')++ const withMesh = validateWorkflowPreflight(workflow, [], { currentMeshUrl: '/tmp/mesh.glb' })+ assert.deepEqual(withMesh, [])+})++test('multi-input extension requires every declared input type', () => {+ const { validateWorkflowPreflight } = loadModule()+ const extensions = [ext({ inputs: ['image', 'text'] })]+ const workflow = wf(+ [imageNode('img'), { id: 'proc', type: 'extensionNode', position: { x: 0, y: 0 }, data: { extensionId: 'pack/process-node' } }],+ [{ id: 'e1', source: 'img', target: 'proc' }],+ )++ const issues = validateWorkflowPreflight(workflow, extensions)+ // image satisfied, text still missing+ assert.ok(!issues.some((i) => i.key === 'proc:missing:image'))+ assert.ok(issues.some((i) => i.key === 'proc:missing:text'))+})++test('scene input requires a validated Load Scene source and rejects image wiring', () => {+ const { validateWorkflowPreflight } = loadModule()+ const model = { id: 'model', type: 'extensionNode', position: { x: 0, y: 0 }, data: { extensionId: 'pack/process-node' } }+ const scene = { id: 'scene', type: 'sceneNode', position: { x: 0, y: 0 }, data: { params: { manifestPath: 'Workflows/room/scene-manifest.json' } } }+ for (const output of ['scene', 'mesh']) {+ const extension = ext({ input: 'scene', output, type: 'model' })+ assert.deepEqual(validateWorkflowPreflight(wf([scene, model], [{ id: 'scene-edge', source: 'scene', target: 'model' }]), [extension]), [])+ }++ const extension = ext({ input: 'scene', output: 'scene', type: 'model' })+ const issues = validateWorkflowPreflight(wf([imageNode(), model], [{ id: 'image-edge', source: 'img', target: 'model' }]), [extension])+ assert.ok(issues.some((issue) => issue.key === 'model:missing:scene'))+ assert.ok(issues.some((issue) => issue.key === 'model:type:image-edge'))+})++test('Load Scene must be validated before a workflow can run', () => {+ const { validateWorkflowPreflight } = loadModule()+ const scene = { id: 'scene', type: 'sceneNode', position: { x: 0, y: 0 }, data: { params: { path: 'Workflows/room' } } }+ const issues = validateWorkflowPreflight(wf([scene], []), [])+ assert.equal(issues[0].key, 'scene:scene-invalid')+})++test('renderer fails closed for unsupported process and mixed scene node shapes', () => {+ const { validateWorkflowPreflight } = loadModule()+ const scene = { id: 'scene', type: 'sceneNode', position: { x: 0, y: 0 }, data: { params: { manifestPath: 'Workflows/room/scene-manifest.json' } } }+ const target = { id: 'target', type: 'extensionNode', position: { x: 0, y: 0 }, data: { extensionId: 'pack/process-node' } }+ for (const extension of [+ ext({ input: 'scene', output: 'mesh', type: 'process' }),+ ext({ input: 'scene', inputs: ['scene', 'text'], output: 'mesh', type: 'model' }),+ ]) {+ const issues = validateWorkflowPreflight(wf([scene, target], [{ id: 'e', source: 'scene', target: 'target' }]), [extension])+ assert.ok(issues.some((issue) => issue.key === 'target:unsupported-scene-shape'))+ }+})diff --git a/apps/forge-desktop/src/areas/workflows/preflight.ts b/apps/forge-desktop/src/areas/workflows/preflight.tsnew file mode 100644index 000000000..068a9277b--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/preflight.ts@@ -0,0 +1,171 @@+import type { Workflow, WFNode } from '@shared/types/electron.d'+import { getWorkflowExtension, type WorkflowExtension } from './mockExtensions'+import { hasUnsupportedSceneShape } from './sceneShape'+import { isPassthrough, isBranchConsumer, resolveDataSource, nearestUpstreamWaits } from './nodeBehaviors'++type DataType = 'image' | 'text' | 'mesh' | 'audio' | 'scene'++export interface WorkflowPreflightIssue {+ key: string+ message: string+ nodeId?: string+}++function nodeLabel(node: WFNode, allExtensions: WorkflowExtension[]): string {+ if (node.type === 'imageNode') return 'Image'+ if (node.type === 'textNode') return 'Text'+ if (node.type === 'meshNode') return 'Load 3D Mesh'+ if (node.type === 'sceneNode') return 'Load Scene'+ if (node.type === 'outputNode') return 'Add to Scene'+ if (node.type === 'previewNode') return 'Preview Views'+ if (node.type === 'imagePreviewNode') return 'Preview Image'+ if (node.type === 'forEachNode') {+ const mode = (node.data.params?.mode as string) ?? 'image'+ return mode === 'text' ? 'For Each Text' : mode === 'mesh' ? 'For Each Mesh' : 'For Each Image'+ }+ if (node.type === 'extensionNode') {+ return getWorkflowExtension(node.data.extensionId ?? '', allExtensions)?.name ?? 'Extension'+ }+ return 'Node'+}++function formatType(type: DataType): string {+ if (type === 'scene') return 'scene'+ if (type === 'mesh') return 'mesh'+ if (type === 'image') return 'image'+ if (type === 'audio') return 'audio'+ return 'text'+}++function formatRequiredTypes(types: DataType[]): string {+ if (types.length === 1) return formatType(types[0])+ if (types.length === 2) return `${formatType(types[0])} and ${formatType(types[1])}`+ return `${types.slice(0, -1).map(formatType).join(', ')}, and ${formatType(types[types.length - 1])}`+}++function getNodeOutputType(node: WFNode, allExtensions: WorkflowExtension[]): DataType | undefined {+ if (node.type === 'imageNode') return 'image'+ if (node.type === 'textNode') return 'text'+ if (node.type === 'meshNode' || node.type === 'outputNode') return 'mesh'+ if (node.type === 'sceneNode') return 'scene'+ if (node.type === 'previewNode') return 'image'+ if (node.type === 'imagePreviewNode') return 'image'+ if (node.type === 'forEachNode') {+ const mode = (node.data.params?.mode as DataType | undefined) ?? 'image'+ return mode === 'text' || mode === 'mesh' ? mode : 'image'+ }+ if (node.type === 'extensionNode') {+ return getWorkflowExtension(node.data.extensionId ?? '', allExtensions)?.output+ }+ return undefined+}++function pushIssue(issues: WorkflowPreflightIssue[], issue: WorkflowPreflightIssue): void {+ if (!issues.some((existing) => existing.key === issue.key)) issues.push(issue)+}++export function validateWorkflowPreflight(+ workflow: Workflow,+ allExtensions: WorkflowExtension[],+ options?: { currentMeshUrl?: string | null },+): WorkflowPreflightIssue[] {+ const issues: WorkflowPreflightIssue[] = []+ const nodeMap = new Map(workflow.nodes.map((node) => [node.id, node]))++ const outputTypes = new Map<string, DataType | undefined>()+ for (const node of workflow.nodes) {+ outputTypes.set(node.id, getNodeOutputType(node, allExtensions))+ }+ // Passthrough nodes inherit their resolved upstream source's type.+ for (const node of workflow.nodes) {+ if (!isPassthrough(node.type)) continue+ const realSourceId = resolveDataSource(node.id, workflow.edges, nodeMap)+ if (realSourceId && realSourceId !== node.id) outputTypes.set(node.id, outputTypes.get(realSourceId))+ }++ for (const node of workflow.nodes) {+ if (node.type === 'meshNode' && node.data.params?.source === 'current' && !options?.currentMeshUrl) {+ pushIssue(issues, {+ key: `${node.id}:current-mesh`,+ nodeId: node.id,+ message: `${nodeLabel(node, allExtensions)} is set to Current Scene, but no mesh is loaded.`,+ })+ }++ if (node.type === 'forEachNode' && !((node.data.params?.dir as string | undefined)?.trim())) {+ pushIssue(issues, {+ key: `${node.id}:foreach-no-folder`,+ nodeId: node.id,+ message: `${nodeLabel(node, allExtensions)} needs a folder selected.`,+ })+ }++ if (node.type === 'sceneNode' && !((node.data.params?.manifestPath as string | undefined)?.trim())) {+ pushIssue(issues, {+ key: `${node.id}:scene-invalid`, nodeId: node.id,+ message: 'Load Scene needs a validated scene directory.',+ })+ }++ // A node fed by two different Wait branches can't be scheduled into a single+ // branch — it would run before either branch produces its mesh.+ if (+ isBranchConsumer(node.type) &&+ nearestUpstreamWaits(node.id, workflow.edges, nodeMap).size > 1+ ) {+ pushIssue(issues, {+ key: `${node.id}:wait-merge`,+ nodeId: node.id,+ message: `${nodeLabel(node, allExtensions)} merges two Wait branches, which isn't supported. Route it through a single Wait.`,+ })+ }++ if (node.type !== 'extensionNode') continue++ const ext = getWorkflowExtension(node.data.extensionId ?? '', allExtensions)+ if (!ext) {+ pushIssue(issues, {+ key: `${node.id}:missing-extension`,+ nodeId: node.id,+ message: `${nodeLabel(node, allExtensions)} is unavailable. Reload extensions or remove the node.`,+ })+ continue+ }++ if (hasUnsupportedSceneShape(ext)) {+ pushIssue(issues, {+ key: `${node.id}:unsupported-scene-shape`,+ nodeId: node.id,+ message: `${ext.name} uses an unsupported scene input or output declaration.`,+ })+ continue+ }++ const incomingEdges = workflow.edges.filter((edge) => edge.target === node.id)+ const requiredTypes = [...new Set((ext.inputs ?? [ext.input]) as DataType[])]++ for (const requiredType of requiredTypes) {+ const hasMatchingInput = incomingEdges.some((edge) => outputTypes.get(edge.source) === requiredType)+ if (!hasMatchingInput) {+ pushIssue(issues, {+ key: `${node.id}:missing:${requiredType}`,+ nodeId: node.id,+ message: `${ext.name} needs an incoming ${formatType(requiredType)} connection.`,+ })+ }+ }++ for (const edge of incomingEdges) {+ const sourceNode = nodeMap.get(edge.source)+ const sourceType = outputTypes.get(edge.source)+ if (!sourceNode || !sourceType || requiredTypes.includes(sourceType)) continue+ pushIssue(issues, {+ key: `${node.id}:type:${edge.id}`,+ nodeId: node.id,+ message: `${ext.name} expects ${formatRequiredTypes(requiredTypes)}, but ${nodeLabel(sourceNode, allExtensions)} outputs ${formatType(sourceType)}.`,+ })+ }+ }++ return issues+}diff --git a/apps/forge-desktop/src/areas/workflows/sceneShape.ts b/apps/forge-desktop/src/areas/workflows/sceneShape.tsnew file mode 100644index 000000000..5c6814bf0--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/sceneShape.ts@@ -0,0 +1,11 @@+import type { WorkflowExtension } from './mockExtensions'++/**+ * Scene is model-only and must be the node's single `input` (never inside+ * `inputs`). Mirrors assertSupportedSceneNodeShape on the install side.+ */+export function hasUnsupportedSceneShape(ext: Pick<WorkflowExtension, 'type' | 'input' | 'inputs' | 'output'>): boolean {+ const usesSceneInput = ext.input === 'scene' || ext.inputs?.includes('scene') === true+ if (ext.type === 'process') return usesSceneInput || ext.output === 'scene'+ return usesSceneInput && (ext.inputs !== undefined || ext.input !== 'scene')+}diff --git a/apps/forge-desktop/src/areas/workflows/slotInputs.test.mjs b/apps/forge-desktop/src/areas/workflows/slotInputs.test.mjsnew file mode 100644index 000000000..16adecd22--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/slotInputs.test.mjs@@ -0,0 +1,54 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++// slotInputs.ts has no runtime imports, so esbuild bundles it standalone.+function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-slotinputs-test-')), 'slotInputs.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('src/areas/workflows/slotInputs.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++const { assignSlotFilePaths } = loadModule()++test('a mesh slot becomes the mesh path', () => {+ const r = assignSlotFilePaths(['mesh', 'image'], ['a.glb', 'b.png'])+ assert.equal(r.nodeInputMeshPath, 'a.glb')+ assert.equal(r.nodeInputPath, 'b.png')+ assert.deepEqual(r.extraImagePaths, [])+})++test('the first image slot is the primary path and later images are extras', () => {+ const r = assignSlotFilePaths(['image', 'image', 'image'], ['1.png', '2.png', '3.png'])+ assert.equal(r.nodeInputPath, '1.png')+ assert.deepEqual(r.extraImagePaths, ['2.png', '3.png'])+ assert.equal(r.nodeInputMeshPath, undefined)+})++test('an audio slot becomes the primary path', () => {+ // Regression: audio slots were resolved and then dropped, so a multi-input+ // node such as [audio, text] failed with "needs an incoming audio connection".+ const r = assignSlotFilePaths(['audio', 'text'], ['song.wav', undefined])+ assert.equal(r.nodeInputPath, 'song.wav')+ assert.equal(r.nodeInputMeshPath, undefined)+ assert.deepEqual(r.extraImagePaths, [])+})++test('text slots never claim a file path, and empty slots are skipped', () => {+ const r = assignSlotFilePaths(['text', 'image'], ['leaked.png', undefined])+ assert.equal(r.nodeInputPath, undefined)+ assert.equal(r.nodeInputMeshPath, undefined)+ assert.deepEqual(r.extraImagePaths, [])+})diff --git a/apps/forge-desktop/src/areas/workflows/slotInputs.ts b/apps/forge-desktop/src/areas/workflows/slotInputs.tsnew file mode 100644index 000000000..c07705e9e--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/slotInputs.ts@@ -0,0 +1,36 @@+// Multi-input slot → file-path assignment for extension nodes.+//+// `inputTypes` is the node's declared `inputs` (one per handle); `inputPaths` is+// the file path resolved for each slot, indexed the same way (undefined where the+// slot carries text or nothing). Pure so it can be tested without the store.++export type SlotInputType = 'image' | 'text' | 'mesh' | 'audio'++export interface SlotFilePaths {+ /** Primary file: what the extension receives as `filePath` when no mesh is present. */+ nodeInputPath?: string+ /** Mesh slot, if any. Takes precedence as `filePath`; the primary file then rides in params. */+ nodeInputMeshPath?: string+ /** Every image beyond the first resolved image slot. */+ extraImagePaths: string[]+}++export function assignSlotFilePaths(+ inputTypes: readonly SlotInputType[],+ inputPaths: readonly (string | undefined)[],+): SlotFilePaths {+ const out: SlotFilePaths = { extraImagePaths: [] }+ for (let i = 0; i < inputTypes.length; i++) {+ const fp = inputPaths[i]+ if (!fp) continue+ if (inputTypes[i] === 'mesh') {+ out.nodeInputMeshPath = fp+ } else if (inputTypes[i] === 'image') {+ if (!out.nodeInputPath) out.nodeInputPath = fp+ else out.extraImagePaths.push(fp)+ } else if (inputTypes[i] === 'audio') {+ if (!out.nodeInputPath) out.nodeInputPath = fp+ }+ }+ return out+}diff --git a/apps/forge-desktop/src/areas/workflows/useWaitButton.ts b/apps/forge-desktop/src/areas/workflows/useWaitButton.tsnew file mode 100644index 000000000..873eba974--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/useWaitButton.ts@@ -0,0 +1,51 @@+import { useWorkflowRunStore } from './workflowRunStore'+import type { WaitState } from './workflowRunStore'++export interface WaitButtonModel {+ waitState: WaitState | undefined+ canContinue: boolean+ isRunning: boolean+ label: 'Retry' | 'Continue'+ buttonClass: string+ statusText: string+ onContinue: () => void+}++// Shared derivation for the Wait Continue/Retry control, used by both the+// canvas node (WaitNode) and the params panel (WaitParamRow). Keeps the two+// renderings in sync — they differ only in markup/sizing, not in logic.+export function useWaitButton(nodeId: string): WaitButtonModel {+ const waitState = useWorkflowRunStore((s) => s.waitStates[nodeId])+ const runningBranchId = useWorkflowRunStore((s) => s.runningBranchId)+ const status = useWorkflowRunStore((s) => s.runState.status)+ const continueRun = useWorkflowRunStore((s) => s.continueRun)++ const otherBranchRunning = runningBranchId !== null && runningBranchId !== nodeId+ // Pre-phase: shared nodes (e.g. Generate Mesh) still running before any branch hands off.+ const inPrePhase = status === 'running' && runningBranchId === null+ const isRunning = waitState === 'running'+ // A pre-phase failure aborts the run before any handoff (status → 'error' while+ // this Wait is still 'pending'): it never became runnable, so no Continue.+ const runAborted = status === 'error' && waitState === 'pending'+ const canContinue = (waitState === 'pending' || waitState === 'done' || waitState === 'error') && !otherBranchRunning && !inPrePhase && !runAborted+ const label: 'Retry' | 'Continue' = waitState === 'done' || waitState === 'error' ? 'Retry' : 'Continue'++ const buttonClass = waitState === 'error'+ ? 'bg-red-500/15 border-red-500/30 text-red-400 hover:bg-red-500/25'+ : waitState === 'done'+ ? 'bg-emerald-500/15 border-emerald-500/30 text-emerald-400 hover:bg-emerald-500/25'+ : 'bg-amber-500/15 border-amber-500/30 text-amber-400 hover:bg-amber-500/25'++ const statusText =+ waitState === 'blocked' ? 'Waiting for the previous Wait to finish…' :+ waitState === 'running' ? 'Branch in progress…' :+ waitState === 'done' ? 'Branch finished — Retry to re-run.' :+ waitState === 'error' ? 'Branch failed — Retry to re-run.' :+ waitState === 'pending' && runAborted ? 'Run failed upstream — fix the error and run again.' :+ waitState === 'pending' && inPrePhase ? 'Waiting for upstream nodes…' :+ waitState === 'pending' && otherBranchRunning ? 'Another branch is running…' :+ waitState === 'pending' ? 'Workflow paused — click Continue to run this branch.' :+ 'Pauses the workflow until you click Continue.'++ return { waitState, canContinue, isRunning, label, buttonClass, statusText, onContinue: () => continueRun(nodeId) }+}diff --git a/apps/forge-desktop/src/areas/workflows/workflowRunStore.ts b/apps/forge-desktop/src/areas/workflows/workflowRunStore.tsnew file mode 100644index 000000000..1c64c0c58--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/workflowRunStore.ts@@ -0,0 +1,1108 @@+import { create } from 'zustand'+import axios, { AxiosInstance } from 'axios'+import { useAppStore } from '@shared/stores/appStore'+import { getWorkflowExtension } from './mockExtensions'+import { hasUnsupportedSceneShape } from './sceneShape'+import { showCompletionNotification, showErrorNotification } from '@shared/utils/notification'+import type { WorkflowExtension } from './mockExtensions'+import type { Workflow, WFNode, WFEdge } from '@shared/types/electron.d'+import { isBranchStarter, isSceneOutput, resolveDataSource, reachesSceneOutput, nearestUpstreamWaits } from './nodeBehaviors'+import { assignSlotFilePaths } from './slotInputs'+import type { SlotInputType } from './slotInputs'++// ─── Types ────────────────────────────────────────────────────────────────────++export interface WorkflowRunState {+ status: 'idle' | 'running' | 'paused' | 'done' | 'error'+ blockIndex: number+ blockTotal: number+ blockProgress: number+ blockStep: string+ outputUrl?: string+ outputPath?: string+ error?: string+}++export type WaitState = 'blocked' | 'pending' | 'running' | 'done' | 'error'++const IDLE: WorkflowRunState = {+ status: 'idle', blockIndex: 0, blockTotal: 0, blockProgress: 0, blockStep: '',+}++// ─── Module-level run context (survives between run() and continueRun(id)) ───++const _cancel = { current: false }+const _activeJobId = { current: null as string | null }+// While container (manual mode) pause/resume — set by continueWhile()/retryWhile().+const _resume = { current: null as (() => void) | null }+const _retry = { current: false }+// For Each auto-loop: the user asked to pause at the next iteration boundary.+const _pauseRequested = { current: false }+// Live node params — the UI pushes edits here so a looping/paused run re-reads the+// latest values when a body node starts (instead of the snapshot from run start).+const _liveParams = { current: new Map<string, Record<string, unknown>>() }++function flushResume(): void {+ const fn = _resume.current+ _resume.current = null+ if (fn) fn()+}++interface NodeOutput { filePath?: string; text?: string; outputType?: string }++function isSceneMeshOutput(output: NodeOutput | undefined): output is NodeOutput & { filePath: string } {+ return output?.outputType === 'mesh' && typeof output.filePath === 'string'+}++// ─── For Each iterator (image / text / mesh) ───────────────────────────────────+// A "For Each" node walks a folder alphabetically and emits one file per loop+// iteration. Its loop body = the executable nodes reachable downstream, which+// re-run for every file. The `mode` param picks what it emits and which files it+// matches.++const FOR_EACH_MODES: Record<string, { exts: string[]; outputType: 'image' | 'text' | 'mesh' }> = {+ image: { exts: ['png', 'jpg', 'jpeg', 'webp'], outputType: 'image' },+ text: { exts: ['txt', 'md', 'prompt'], outputType: 'text' },+ mesh: { exts: ['glb', 'gltf', 'obj', 'stl', 'ply', 'fbx'], outputType: 'mesh' },+}++function iteratorConfig(node: WFNode): { exts: string[]; outputType: 'image' | 'text' | 'mesh' } {+ return FOR_EACH_MODES[(node.data.params?.mode as string) ?? 'image'] ?? FOR_EACH_MODES.image+}++function isIterator(type: string | undefined): boolean {+ return type === 'forEachNode'+}++/** True for nodes the runner executes (and can re-run inside a loop body). */+function isExecutable(node: WFNode): boolean {+ if (isIterator(node.type)) return true+ return node.type === 'extensionNode' && !!node.data.enabled+}++/** Absolute, alphabetically-sorted paths of an iterator's files (listFiles sorts). */+async function listIteratorFiles(dir: string, exts: string[]): Promise<string[]> {+ const names = await window.electron.fs.listFiles(dir, exts)+ const norm = dir.replace(/\\/g, '/').replace(/\/+$/, '')+ return names.map((n) => `${norm}/${n}`)+}++/** Read a UTF-8 text file through the base64 IPC bridge. */+async function readTextFile(filePath: string): Promise<string> {+ const b64 = await window.electron.fs.readFileBase64(filePath)+ return new TextDecoder('utf-8').decode(Uint8Array.from(atob(b64), (c) => c.charCodeAt(0)))+}++/**+ * Executable nodes reachable downstream from `startId` (its loop body). Traversal+ * stops at Wait boundaries — those nodes belong to branches, not the pre-phase loop.+ */+function reachableExecutable(startId: string, edges: WFEdge[], nodeMap: Map<string, WFNode>): Set<string> {+ const body = new Set<string>([startId])+ const stack = [startId]+ const seen = new Set<string>([startId])+ while (stack.length > 0) {+ const id = stack.pop()!+ for (const e of edges) {+ if (e.source !== id || seen.has(e.target)) continue+ seen.add(e.target)+ const t = nodeMap.get(e.target)+ if (!t || isBranchStarter(t.type)) continue+ if (isExecutable(t)) body.add(e.target)+ stack.push(e.target)+ }+ }+ return body+}++function toWorkspaceUrl(filePath: string, workspaceDir: string): string | undefined {+ const norm = filePath.replace(/\\/g, '/')+ if (!norm.startsWith(workspaceDir)) return undefined+ return `/workspace/${norm.slice(workspaceDir.length).replace(/^\//, '')}`+}++// Inverse of toWorkspaceUrl — used by node components that read a `/workspace/...`+// output URL back off disk (e.g. to build a data: URL for a preview).+export function fromWorkspaceUrl(url: string, workspaceDir: string): string {+ const wsDir = workspaceDir.replace(/\\/g, '/').replace(/\/+$/, '')+ const rel = url.replace(/^\/workspace\//, '')+ return `${wsDir}/${rel}`+}++interface RunContext {+ workflow: Workflow+ allExtensions: WorkflowExtension[]+ client: AxiosInstance+ workspaceDir: string+ selectedImagePath: string | undefined+ selectedImageData?: string+ overrideImageData?: string+ nodeOutputs: Map<string, NodeOutput>+ nodeMap: Map<string, WFNode>+ /** nodes in execution (topological) order */+ ordered: WFNode[]+ branches: Map<string, WFNode[]>+ waitIds: string[]+ /** waitId → nearest upstream waitId (null = top-level, runnable from the start) */+ parentWait: Map<string, string | null>+ /** iterator node id → its resolved file paths, one per loop iteration */+ iteratorFiles: Map<string, string[]>+ /** workspace URL of the most recently pushed scene mesh (last branch the user ran wins) */+ lastSceneMesh?: string+}+const _ctx = { current: null as RunContext | null }++// ─── Topological sort (DFS preorder, branch-first) ───────────────────────────++function topoSort(nodes: WFNode[], edges: WFEdge[]): WFNode[] {+ const nodeMap = new Map(nodes.map((n) => [n.id, n]))+ const adj = new Map(nodes.map((n) => [n.id, [] as string[]]))+ const inDeg = new Map(nodes.map((n) => [n.id, 0]))+ for (const e of edges) {+ if (!nodeMap.has(e.source) || !nodeMap.has(e.target)) continue+ adj.get(e.source)!.push(e.target)+ inDeg.set(e.target, (inDeg.get(e.target) ?? 0) + 1)+ }++ const visited = new Set<string>()+ const result: WFNode[] = []++ const visit = (id: string): void => {+ if (visited.has(id)) return+ for (const e of edges) {+ if (e.target === id && !visited.has(e.source) && nodeMap.has(e.source)) return+ }+ const node = nodeMap.get(id)+ if (!node) return+ visited.add(id)+ result.push(node)+ for (const childId of adj.get(id) ?? []) visit(childId)+ }++ for (const node of nodes) if ((inDeg.get(node.id) ?? 0) === 0) visit(node.id)+ for (const node of nodes) if (!visited.has(node.id)) visit(node.id)+ return result+}++// ─── While container geometry ──────────────────────────────────────────────────+// Body membership can't rely on parentId alone: React Flow only assigns it when a+// node is dragged into the container, so a While resized around existing nodes (or+// nodes added by palette click) leaves them unparented. We therefore also test+// on-canvas containment at run time.++interface WhileBounds { x: number; y: number; w: number; h: number }++function nodeSize(n: WFNode): { w: number; h: number } {+ const measured = (n as { measured?: { width?: number; height?: number } }).measured+ const styleW = n.style?.width+ const styleH = n.style?.height+ return {+ w: measured?.width ?? n.width ?? (typeof styleW === 'number' ? styleW : 200),+ h: measured?.height ?? n.height ?? (typeof styleH === 'number' ? styleH : 80),+ }+}++function whileBounds(w: WFNode): WhileBounds {+ const s = nodeSize(w)+ return { x: w.position.x, y: w.position.y, w: s.w, h: s.h }+}++function isInsideWhile(n: WFNode, whileId: string, b: WhileBounds): boolean {+ if (n.parentId === whileId) return true+ if (n.parentId) return false // explicit child of another container+ const s = nodeSize(n)+ const cx = n.position.x + s.w / 2+ const cy = n.position.y + s.h / 2+ return cx >= b.x && cx <= b.x + b.w && cy >= b.y && cy <= b.y + b.h+}++// ─── Branch identification ────────────────────────────────────────────────────+// A node belongs to Wait W's branch if its single nearest upstream Wait is W+// (dominance). Nodes with no upstream Wait — or with multiple (merges) — execute+// in the pre-phase before any user pause.++function identifyBranches(workflow: Workflow): {+ preExecExtNodes: WFNode[]+ branches: Map<string, WFNode[]>+ waitIds: string[]+ parentWait: Map<string, string | null>+ ordered: WFNode[]+} {+ const ordered = topoSort(workflow.nodes, workflow.edges)+ const nodeMap = new Map(workflow.nodes.map((n) => [n.id, n]))+ const waitIds = ordered.filter((n) => isBranchStarter(n.type)).map((n) => n.id)++ // A node is owned by its single nearest upstream Wait (dominance). This lets+ // Wait → … → Wait chains nest: nodes after the 2nd Wait belong to it, not the 1st.+ const branchOwner = new Map<string, string>()+ for (const node of workflow.nodes) {+ if (isBranchStarter(node.type) || !isExecutable(node)) continue+ const nearest = nearestUpstreamWaits(node.id, workflow.edges, nodeMap)+ if (nearest.size === 1) branchOwner.set(node.id, [...nearest][0])+ }++ // Each Wait's parent = its own nearest upstream Wait (null if top-level).+ const parentWait = new Map<string, string | null>()+ for (const w of waitIds) {+ const nearest = nearestUpstreamWaits(w, workflow.edges, nodeMap)+ parentWait.set(w, nearest.size === 1 ? [...nearest][0] : null)+ }++ const branches = new Map<string, WFNode[]>()+ for (const w of waitIds) branches.set(w, [])+ const preExecExtNodes: WFNode[] = []+ for (const node of ordered) {+ if (!isExecutable(node)) continue+ const owner = branchOwner.get(node.id)+ if (owner) branches.get(owner)!.push(node)+ else preExecExtNodes.push(node)+ }++ return { preExecExtNodes, branches, waitIds, parentWait, ordered }+}++// ─── For Each iterator execution ───────────────────────────────────────────────+// Emits the current iteration's file. Image iterators emit an image path; text+// iterators read the file and emit its text. The iteration index comes from the+// loop's progress (its own node id keys the loop).++async function executeIteratorNode(+ node: WFNode,+ ctx: RunContext,+ setRunState: (updater: (s: WorkflowRunState) => WorkflowRunState) => void,+): Promise<void> {+ const files = ctx.iteratorFiles.get(node.id) ?? []+ const current = useWorkflowRunStore.getState().whileProgress[node.id]?.current ?? 1+ const path = files[current - 1]+ if (!path) throw new Error('For Each: no file for this iteration')++ const kind = iteratorConfig(node)+ const name = path.split(/[\\/]/).pop()+ setRunState((s) => ({ ...s, blockProgress: 30, blockStep: `Reading ${name}` }))++ if (kind.outputType === 'text') {+ const text = await readTextFile(path)+ ctx.nodeOutputs.set(node.id, { text, outputType: 'text' })+ } else {+ ctx.nodeOutputs.set(node.id, { filePath: path, outputType: kind.outputType })+ }+ setRunState((s) => ({ ...s, blockProgress: 100, blockStep: `Loaded ${name}` }))+}++// ─── Per-node execution ──────────────────────────────────────────────────────+// Resolves inputs (walking through Wait passthroughs), runs the extension+// (model or process), updates nodeOutputs, and pushes the mesh to the scene+// if it feeds an Add-to-Scene through Waits.++async function executeExtensionNode(+ node: WFNode,+ ctx: RunContext,+ setRunState: (updater: (s: WorkflowRunState) => WorkflowRunState) => void,+): Promise<void> {+ if (isIterator(node.type)) {+ await executeIteratorNode(node, ctx, setRunState)+ return+ }++ const { workflow, allExtensions, client, workspaceDir, nodeOutputs, nodeMap,+ selectedImagePath, selectedImageData } = ctx++ const ext = getWorkflowExtension(node.data.extensionId ?? '', allExtensions)+ if (ext && hasUnsupportedSceneShape(ext)) {+ throw new Error(`${ext.name} uses an unsupported scene input or output declaration`)+ }+ // Freshest params at the moment the node starts (so loop iterations / Retry pick+ // up edits made while paused, not the values captured at run start).+ const liveParams = _liveParams.current.get(node.id) ?? node.data.params ?? {}++ const resolveSource = (sourceId: string): NodeOutput | undefined => {+ const realId = resolveDataSource(sourceId, workflow.edges, nodeMap)+ return realId ? nodeOutputs.get(realId) : undefined+ }++ let nodeInputPath: string | undefined+ let nodeInputText: string | undefined+ let nodeInputMeshPath: string | undefined+ let nodeInputScenePath: string | undefined+ // Per-slot texts for multi-text-input nodes (e.g. positive/negative prompts).+ // Indexed by target handle: input-0 → texts[0], input-1 → texts[1].+ const nodeInputTexts: (string | undefined)[] = []+ // Every image beyond the first resolved slot, for extensions that take several+ // (e.g. a texture node taking a mesh plus multiple reference images).+ const extraImagePaths: string[] = []++ const incomingEdges = workflow.edges.filter((e) => e.target === node.id)++ if (ext?.inputs && ext.inputs.length > 1) {+ // Scene is intentionally a single-input-only model contract. The guard+ // above rejects it before this multi-slot path, and filtering it here also+ // narrows the remaining declarations to assignSlotFilePaths' exact ABI.+ const inputTypes: SlotInputType[] = ext.inputs.filter((input) => input !== 'scene')+ // Resolved by target handle first, then typed by that slot's declared input --+ // not by the arrival order of `incomingEdges`, which does not match slot order.+ const inputPaths = new Array<string | undefined>(inputTypes.length).fill(undefined)++ for (const edge of incomingEdges) {+ const src = resolveSource(edge.source)+ if (!src) continue+ const slotMatch = /^input-(\d+)$/.exec(edge.targetHandle ?? '')+ const slot = slotMatch ? Number(slotMatch[1]) : 0+ if (src.filePath !== undefined && slot < inputTypes.length) inputPaths[slot] = src.filePath+ if (src.text !== undefined && src.text.trim().length > 0) {+ nodeInputText = src.text+ if (slotMatch) nodeInputTexts[slot] = src.text+ }+ }++ const slots = assignSlotFilePaths(inputTypes, inputPaths)+ nodeInputPath = slots.nodeInputPath+ nodeInputMeshPath = slots.nodeInputMeshPath+ extraImagePaths.push(...slots.extraImagePaths)+ } else {+ for (const edge of incomingEdges) {+ const src = resolveSource(edge.source)+ if (src?.filePath !== undefined) nodeInputPath = src.filePath+ if (src?.text !== undefined && src.text.trim().length > 0) nodeInputText = src.text+ if (src?.outputType === 'scene') nodeInputScenePath = src.filePath+ }+ }++ const isModelNode = ext?.type === 'model'++ if (isModelNode) {+ const isSceneInput = ext?.inputs ? ext.inputs.includes('scene') : ext?.input === 'scene'+ const isTextInput = ext?.inputs ? ext.inputs.every((i) => i === 'text') : ext?.input === 'text'+ if (isSceneInput && !nodeInputScenePath) throw new Error(`${ext?.name ?? 'Model'} needs an incoming scene connection`)+ const activeImagePath = (isTextInput || isSceneInput) ? undefined : (nodeInputPath ?? selectedImagePath)+ if (!isTextInput && !isSceneInput && !selectedImageData && (!activeImagePath || activeImagePath.trim().length === 0)) {+ throw new Error('No input image selected for model node')+ }++ let blob: Blob+ let fname: string+ if (isTextInput || isSceneInput || (selectedImageData && nodeInputPath === undefined)) {+ const base64 = selectedImageData && nodeInputPath === undefined+ ? selectedImageData+ : 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==' // 1x1 transparent PNG+ fname = 'placeholder.png'+ blob = new Blob([Uint8Array.from(atob(base64), (c) => c.charCodeAt(0))], { type: 'image/png' })+ } else {+ const base64 = await window.electron.fs.readFileBase64(activeImagePath as string)+ const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0))+ blob = new Blob([bytes], { type: 'image/png' })+ fname = activeImagePath?.split(/[\\/]/).pop() ?? 'image.png'+ }++ const extraParams: Record<string, unknown> = {}+ if (nodeInputMeshPath) {+ const norm = nodeInputMeshPath.replace(/\\/g, '/')+ extraParams.mesh_path = norm.startsWith(workspaceDir)+ ? norm.slice(workspaceDir.length).replace(/^\//, '')+ : norm+ }+ if (nodeInputText !== undefined && nodeInputText.trim().length > 0) {+ extraParams.prompt = nodeInputText+ extraParams.text = nodeInputText+ }+ if (extraImagePaths.length > 0) {+ extraParams.extra_image_paths = extraImagePaths+ }++ const schemaDefaults = Object.fromEntries(+ (ext.params ?? []).map((p) => [p.id, p.default]),+ )+ const effectiveParams = { ...schemaDefaults, ...liveParams }++ setRunState((s) => ({ ...s, blockProgress: 5, blockStep: 'Submitting to model…' }))+ let submission: { data: { job_id: string } }+ if (isSceneInput) {+ const normalized = nodeInputScenePath!.replace(/\\/g, '/')+ const inputPath = normalized.startsWith(`${workspaceDir}/`)+ ? normalized.slice(workspaceDir.length + 1)+ : normalized.replace(/^\/workspace\//, '')+ submission = await client.post('/generate/from-artifact', {+ input_kind: 'scene', input_path: inputPath,+ model_id: node.data.extensionId ?? '', collection: 'Workflows',+ params: { ...effectiveParams, ...extraParams },+ })+ } else {+ const fd = new FormData()+ fd.append('image', blob, fname)+ fd.append('model_id', node.data.extensionId ?? '')+ fd.append('collection', 'Workflows')+ fd.append('remesh', 'none')+ fd.append('enable_texture', 'false')+ fd.append('texture_resolution', '1024')+ fd.append('params', JSON.stringify({ ...effectiveParams, ...extraParams }))+ submission = await client.post('/generate/from-image', fd, { headers: { 'Content-Type': 'multipart/form-data' } })+ }+ const { data } = submission+ _activeJobId.current = data.job_id++ while (true) {+ if (_cancel.current) {+ await client.post(`/generate/cancel/${_activeJobId.current}`).catch(() => {})+ _activeJobId.current = null+ throw new Error('Cancelled')+ }+ await new Promise((r) => setTimeout(r, 1200))++ const { data: st } = await client.get<{+ status: string; progress?: number; step?: string; output_url?: string; error?: string+ }>(`/generate/status/${_activeJobId.current}`)++ if (st.status === 'done' && st.output_url) {+ const rel = st.output_url.replace(/^\/workspace\//, '')+ nodeInputPath = `${workspaceDir}/${rel}`+ _activeJobId.current = null+ setRunState((s) => ({ ...s, blockProgress: 100, blockStep: 'Generation complete' }))+ break+ }+ if (st.status === 'error') throw new Error(st.error ?? 'Generation failed')++ setRunState((s) => ({ ...s, blockProgress: st.progress ?? s.blockProgress, blockStep: st.step ?? 'Generating…' }))+ useAppStore.getState().updateCurrentJob({ status: 'generating', progress: st.progress, step: st.step })+ }+ } else {+ if (ext?.input === 'mesh' && !nodeInputPath) throw new Error(`${ext.name} needs an incoming mesh connection`)+ if (ext?.input === 'image' && !nodeInputPath) throw new Error(`${ext.name} needs an incoming image connection`)+ if (ext?.input === 'audio' && !nodeInputPath) throw new Error(`${ext.name} needs an incoming audio connection`)+ if (ext?.input === 'text' && !nodeInputText) throw new Error(`${ext.name} needs an incoming text connection`)++ const parts = (node.data.extensionId ?? '').split('/')+ const extId = parts[0]+ const nid = parts[1] ?? ''++ // Freshest params (liveParams), same as the model-node branch above, so a+ // multi-image process node re-run inside a loop also picks up edits made while+ // paused rather than the snapshot captured at run start.+ const processParams: Record<string, unknown> = { ...liveParams }+ if (nodeInputMeshPath && nodeInputPath) {+ // Texture node: mesh is filePath, all images in extra_image_paths+ processParams.extra_image_paths = [nodeInputPath, ...extraImagePaths]+ } else if (extraImagePaths.length > 0) {+ processParams.extra_image_paths = extraImagePaths+ }++ const result = await window.electron.extensions.runProcess(+ extId,+ {+ filePath: nodeInputMeshPath ?? nodeInputPath,+ text: nodeInputText,+ texts: nodeInputTexts.length > 0 ? nodeInputTexts : undefined,+ nodeId: nid,+ },+ processParams,+ )+ if (!result.success) throw new Error(result.error ?? 'Process extension failed')+ nodeInputPath = result.result?.filePath ?? nodeInputPath+ nodeInputText = result.result?.text ?? nodeInputText+ setRunState((s) => ({ ...s, blockProgress: 100, blockStep: 'Done' }))+ }++ const outputType = ext?.output ?? (nodeInputPath ? 'mesh' : undefined)+ nodeOutputs.set(node.id, { filePath: nodeInputPath, text: nodeInputText, outputType })++ const output = nodeOutputs.get(node.id)+ const url = isSceneMeshOutput(output) ? toWorkspaceUrl(output.filePath, workspaceDir) : undefined+ if (url && reachesSceneOutput(node.id, workflow.edges, nodeMap)) {+ ctx.lastSceneMesh = url // remember it so finalize() keeps the last-run branch in view+ useAppStore.getState().updateCurrentJob({ status: 'done', progress: 100, outputUrl: url })+ }+}++// ─── Wait dependency helpers ───────────────────────────────────────────────────++/** All Waits nested (transitively) under `rootId`, via the parentWait chain. */+function descendantWaits(rootId: string, ctx: RunContext): Set<string> {+ const out = new Set<string>()+ let frontier = new Set<string>([rootId])+ while (frontier.size > 0) {+ const next = new Set<string>()+ for (const w of ctx.waitIds) {+ const parent = ctx.parentWait.get(w)+ if (parent && frontier.has(parent) && !out.has(w)) { out.add(w); next.add(w) }+ }+ frontier = next+ }+ return out+}++/**+ * Push the mesh of every scene output owned by `waitId`'s branch to the viewer.+ * A branch whose only scene output has no in-branch processing (e.g. Wait → Add+ * to Scene) gets no immediate push during execution, so the display has to be+ * driven here, when the user continues that branch.+ */+function pushBranchSceneMesh(ctx: RunContext, waitId: string): void {+ for (const node of ctx.ordered) {+ if (!isSceneOutput(node.type)) continue+ const owners = nearestUpstreamWaits(node.id, ctx.workflow.edges, ctx.nodeMap)+ if (owners.size !== 1 || [...owners][0] !== waitId) continue+ const inEdge = ctx.workflow.edges.find((e) => e.target === node.id)+ if (!inEdge) continue+ const srcId = resolveDataSource(inEdge.source, ctx.workflow.edges, ctx.nodeMap)+ const sourceOutput = srcId ? ctx.nodeOutputs.get(srcId) : undefined+ const url = isSceneMeshOutput(sourceOutput) ? toWorkspaceUrl(sourceOutput.filePath, ctx.workspaceDir) : undefined+ if (url) {+ ctx.lastSceneMesh = url+ useAppStore.getState().updateCurrentJob({ status: 'done', progress: 100, outputUrl: url })+ }+ }+}++// ─── Store ────────────────────────────────────────────────────────────────────++interface WorkflowRunStore {+ runState: WorkflowRunState+ activeNodeId: string | null+ activeWorkflowId: string | null+ nodeImageOutputs: Record<string, string>+ waitStates: Record<string, WaitState>+ runningBranchId: string | null+ /** whileId → current iteration / total (total null = manual/unbounded) */+ whileProgress: Record<string, { current: number; total: number | null }>+ /** iterator ids paused together at a shared boundary (lockstep For Each group) */+ pausedGroup: string[]++ run: (workflow: Workflow, allExtensions: WorkflowExtension[], overrideImageData?: string) => Promise<void>+ cancel: () => void+ reset: () => void+ continueRun: (waitId: string) => Promise<void>+ /** While container: resume past the loop (Continue) */+ continueWhile: () => void+ /** While container: resume and re-run the loop body once more (Retry) */+ retryWhile: () => void+ /** For Each container: request a pause at the next file boundary */+ pauseWhile: () => void+ /** UI → runner: push the latest params for a node so a looping run uses them */+ setLiveNodeParams: (nodeId: string, params: Record<string, unknown>) => void+}++export const useWorkflowRunStore = create<WorkflowRunStore>((set, get) => {+ const setRunState = (updater: (s: WorkflowRunState) => WorkflowRunState): void => {+ set((s) => ({ runState: updater(s.runState) }))+ }++ const collectImageOutputs = (ctx: RunContext): Record<string, string> => {+ const out: Record<string, string> = {}+ for (const [nodeId, o] of ctx.nodeOutputs) {+ if (o.outputType === 'image' && o.filePath) {+ const norm = o.filePath.replace(/\\/g, '/')+ if (norm.startsWith(ctx.workspaceDir)) {+ out[nodeId] = `/workspace/${norm.slice(ctx.workspaceDir.length).replace(/^\//, '')}`+ }+ }+ }+ return out+ }++ const finalize = (ctx: RunContext, finalWaitStates?: Record<string, WaitState>): void => {+ // Prefer the mesh of the last branch the user actually ran — it's already in the+ // viewer, and topo order must not override the user's last action.+ let outputUrl: string | undefined = ctx.lastSceneMesh+ let outputPath: string | undefined++ const lastOutputNode = outputUrl ? undefined : [...ctx.ordered].reverse().find((n) => isSceneOutput(n.type))+ if (lastOutputNode) {+ for (const edge of ctx.workflow.edges.filter((e) => e.target === lastOutputNode.id)) {+ const src = ctx.nodeOutputs.get(edge.source)+ if (isSceneMeshOutput(src)) {+ outputUrl = toWorkspaceUrl(src.filePath, ctx.workspaceDir)+ }+ }+ }+ if (!outputUrl) {+ for (const [, o] of ctx.nodeOutputs) {+ if (o.filePath) {+ if (o.outputType === 'audio' || o.outputType === 'scene') {+ outputPath = o.filePath+ continue+ }+ const workspaceUrl = toWorkspaceUrl(o.filePath, ctx.workspaceDir)+ if (workspaceUrl) outputUrl = workspaceUrl+ else outputPath = o.filePath+ }+ }+ }++ set((s) => ({+ activeNodeId: null,+ runningBranchId: null,+ whileProgress: {},+ pausedGroup: [],+ waitStates: finalWaitStates ?? s.waitStates,+ nodeImageOutputs: collectImageOutputs(ctx),+ runState: {+ status: 'done',+ blockIndex: 0,+ blockTotal: 0,+ blockProgress: 100,+ blockStep: 'Done',+ outputUrl,+ outputPath,+ },+ }))+ useAppStore.getState().updateCurrentJob({ status: 'done', progress: 100, outputUrl })+ void showCompletionNotification('Workflow run complete')+ }++ return {+ runState: IDLE,+ activeNodeId: null,+ activeWorkflowId: null,+ nodeImageOutputs: {},+ waitStates: {},+ runningBranchId: null,+ whileProgress: {},+ pausedGroup: [],++ async run(workflow, allExtensions, overrideImageData?) {+ _cancel.current = false+ _pauseRequested.current = false+ // Seed live params from the snapshot; UI edits during the run override these.+ _liveParams.current = new Map(workflow.nodes.map((n) => [n.id, { ...(n.data.params ?? {}) }]))++ const appState = useAppStore.getState()+ const apiUrl = appState.apiUrl++ const { preExecExtNodes, branches, waitIds, parentWait, ordered } = identifyBranches(workflow)+ const branchSteps = waitIds.reduce((acc, w) => acc + (branches.get(w)?.length ?? 0), 0)++ const nodeMap = new Map(workflow.nodes.map((n) => [n.id, n]))++ // ── For Each iterators → resolve their folders up front ────────────────────+ // The loop count is driven by the folder contents, so the listing must resolve+ // before the loop table (and its progress totals) below.+ const iteratorFiles = new Map<string, string[]>()+ for (const w of workflow.nodes) {+ if (!isIterator(w.type)) continue+ const dir = (w.data.params?.dir as string | undefined)?.trim()+ const fail = (msg: string, step: string): void => {+ set((s) => ({ runState: { ...s.runState, status: 'error', error: msg, blockStep: step }, activeNodeId: null }))+ }+ if (!dir) { fail('For Each: pick a folder first', 'No folder selected'); return }+ try {+ const files = await listIteratorFiles(dir, iteratorConfig(w).exts)+ if (files.length === 0) { fail(`For Each: no matching files in ${dir}`, 'Empty folder'); return }+ iteratorFiles.set(w.id, files)+ } catch (err) {+ fail(String(err), 'Failed to read folder'); return+ }+ }++ // ── Loop table ─────────────────────────────────────────────────────────────+ // While containers loop their geometric body N× (or manually). For Each+ // iterators loop the executable nodes reachable downstream, once per file.+ // Replays filter by bodyIds membership (not a contiguous range), so unrelated+ // pre-phase nodes sorting between body members aren't replayed.+ interface LoopInfo { whileId: string; kind: 'while' | 'forEach'; firstIdx: number; lastIdx: number; bodyIds: Set<string>; iterations: number | null }+ const loops: LoopInfo[] = []+ const indexOf = new Map(preExecExtNodes.map((n, i) => [n.id, i]))++ for (const w of workflow.nodes) {+ if (w.type !== 'whileNode') continue+ const bounds = whileBounds(w)+ const idxs = preExecExtNodes.reduce<number[]>((acc, n, idx) => {+ if (isInsideWhile(n, w.id, bounds)) acc.push(idx)+ return acc+ }, [])+ if (idxs.length === 0) continue+ const iters = Number(w.data?.iterations)+ loops.push({+ whileId: w.id,+ kind: 'while',+ firstIdx: Math.min(...idxs),+ lastIdx: Math.max(...idxs),+ bodyIds: new Set(idxs.map((i) => preExecExtNodes[i].id)),+ iterations: Number.isFinite(iters) && iters > 0 ? Math.floor(iters) : null,+ })+ }++ for (const [iterId, files] of iteratorFiles) {+ const bodyIds = new Set([...reachableExecutable(iterId, workflow.edges, nodeMap)].filter((id) => indexOf.has(id)))+ const idxs = [...bodyIds].map((id) => indexOf.get(id)!)+ if (idxs.length === 0) continue+ loops.push({+ whileId: iterId,+ kind: 'forEach',+ firstIdx: Math.min(...idxs),+ lastIdx: Math.max(...idxs),+ bodyIds,+ iterations: files.length, // one pass per file+ })+ }+ const loopCounters = new Map(loops.map((l) => [l.whileId, l.iterations]))+ // Auto-mode loops replay their body N times; count the extra passes so the+ // progress total reflects the real work (manual loops stay unbounded). While+ // loops are independent. For Each loops sharing a boundary (same lastIdx) run+ // in lockstep over the union of their bodies, so that union is replayed once+ // per pass — count it once, for max(files) − 1 extra passes.+ const forEachGroups = new Map<number, LoopInfo[]>()+ let loopExtraSteps = 0+ for (const l of loops) {+ if (l.kind === 'while') {+ loopExtraSteps += l.iterations != null ? (l.iterations - 1) * l.bodyIds.size : 0+ } else {+ const g = forEachGroups.get(l.lastIdx) ?? []+ g.push(l)+ forEachGroups.set(l.lastIdx, g)+ }+ }+ for (const group of forEachGroups.values()) {+ const union = new Set<string>()+ let maxIter = 0+ for (const l of group) {+ l.bodyIds.forEach((id) => union.add(id))+ if (l.iterations != null) maxIter = Math.max(maxIter, l.iterations)+ }+ if (maxIter > 0) loopExtraSteps += (maxIter - 1) * union.size+ }+ const totalSteps = preExecExtNodes.length + branchSteps + loopExtraSteps++ const selectedImagePath = appState.selectedImagePath ?? undefined+ const selectedImageData = overrideImageData ?? appState.selectedImageData ?? undefined+ const currentMeshUrl = appState.currentJob?.outputUrl++ set({+ activeWorkflowId: workflow.id,+ nodeImageOutputs: {},+ // Top-level Waits are pending; nested Waits start blocked until their parent finishes.+ waitStates: Object.fromEntries(waitIds.map((id) => [id, parentWait.get(id) ? 'blocked' as WaitState : 'pending' as WaitState])),+ runningBranchId: null,+ whileProgress: Object.fromEntries(loops.map((l) => [l.whileId, { current: 1, total: l.iterations }])),+ pausedGroup: [],+ runState: {+ status: 'running', blockIndex: 0, blockTotal: totalSteps,+ blockProgress: 0, blockStep: 'Starting…',+ },+ })++ appState.setCurrentJob({+ id: crypto.randomUUID(),+ imageFile: selectedImagePath ?? '__workflow__',+ status: 'generating',+ progress: 0,+ createdAt: Date.now(),+ })++ try {+ const client = axios.create({ baseURL: apiUrl })+ const settings = await window.electron.settings.get()+ const workspaceDir = settings.workspaceDir.replace(/\\/g, '/')++ const tmpAbsPath = settings.workspaceDir.replace(/[\\/]+$/, '') + '/tmp'+ window.electron.fs.deleteDirectory(tmpAbsPath).catch(() => {})++ const nodeOutputs = new Map<string, NodeOutput>()++ // Pre-populate source nodes+ for (const node of ordered) {+ if (node.type === 'imageNode') {+ const fp = node.data.params?.filePath as string | undefined+ const resolvedPath = overrideImageData ? undefined : (fp ?? selectedImagePath ?? undefined)+ nodeOutputs.set(node.id, { filePath: resolvedPath, outputType: 'image' })+ }+ if (node.type === 'textNode') {+ nodeOutputs.set(node.id, { text: node.data.params?.text as string | undefined })+ }+ if (node.type === 'meshNode') {+ const source = node.data.params?.source as 'file' | 'current' | undefined+ if (source === 'current' && currentMeshUrl) {+ let meshFilePath: string+ if (currentMeshUrl.includes('serve-file?path=')) {+ const encoded = currentMeshUrl.split('serve-file?path=')[1]+ meshFilePath = decodeURIComponent(encoded).replace(/\\/g, '/')+ } else {+ const rel = currentMeshUrl.replace(/^\/workspace\//, '')+ meshFilePath = `${workspaceDir}/${rel}`+ }+ nodeOutputs.set(node.id, { filePath: meshFilePath, outputType: 'mesh' })+ } else {+ const fp = node.data.params?.filePath as string | undefined+ if (fp) nodeOutputs.set(node.id, { filePath: fp, outputType: 'mesh' })+ }+ }+ if (node.type === 'sceneNode') {+ const manifestPath = node.data.params?.manifestPath as string | undefined+ if (manifestPath) nodeOutputs.set(node.id, {+ filePath: `${workspaceDir}/${manifestPath.replace(/^\/+/, '')}`,+ outputType: 'scene',+ })+ }+ }++ const ctx: RunContext = {+ workflow, allExtensions, client, workspaceDir, selectedImagePath, selectedImageData,+ overrideImageData, nodeOutputs, nodeMap, ordered, branches, waitIds, parentWait, iteratorFiles,+ }+ _ctx.current = ctx++ // While the runner is replaying a loop body, this holds the body nodes of the+ // active loop (or the union of several For Each loops sharing a boundary);+ // re-iterations then execute only those members and skip everything else in+ // the range. null = first pass / no active loop (run all nodes once).+ let activeLoopBody: Set<string> | null = null++ // End-of-body handler for While containers. Called after each pre-phase node;+ // when the index is a loop's last body node, it either jumps back (auto N× or+ // Retry) or pauses for Continue/Retry. Returns the index to resume at,+ // 'cancel', or undefined to continue normally.+ const bumpWhileProgress = (whileId: string): void => set((s) => {+ const prev = s.whileProgress[whileId]+ return { whileProgress: { ...s.whileProgress, [whileId]: { current: (prev?.current ?? 1) + 1, total: prev?.total ?? null } } }+ }+ )++ const handleLoopEnd = async (idx: number): Promise<number | 'cancel' | undefined> => {+ const forEachLoops = loops.filter((l) => l.lastIdx === idx && l.kind === 'forEach')+ const whileLoop = loops.find((l) => l.lastIdx === idx && l.kind === 'while')++ // ── For Each: run through every file automatically. Several iterators can+ // share the same downstream body (e.g. an image folder + a mesh folder both+ // feeding one node); they advance together, in lockstep. It only stops if+ // the user hit Pause; then Continue advances to the next file(s) and Retry+ // re-runs the current one. No forced pause at the end — it just finishes.+ if (forEachLoops.length > 0) {+ const groupBody = new Set<string>()+ let jumpTo = Infinity+ for (const loop of forEachLoops) {+ loop.bodyIds.forEach((id) => groupBody.add(id))+ jumpTo = Math.min(jumpTo, loop.firstIdx)+ }++ if (_pauseRequested.current) {+ _pauseRequested.current = false+ _retry.current = false+ // Pause every iterator of the group together (they show the same state).+ const groupIds = forEachLoops.map((l) => l.whileId)+ set({ activeNodeId: groupIds[0], runningBranchId: groupIds[0], pausedGroup: groupIds })+ setRunState((s) => ({ ...s, status: 'paused', blockStep: 'Paused — Continue or Retry' }))+ await new Promise<void>((resolve) => { _resume.current = resolve })+ if (_cancel.current) return 'cancel'+ set({ runningBranchId: null, pausedGroup: [] })+ setRunState((s) => ({ ...s, status: 'running' }))+ if (_retry.current) { // re-run the current file(s), no advance+ _retry.current = false+ activeLoopBody = groupBody+ return jumpTo+ }+ // Continue → fall through to the normal advance below+ }++ // Advance every iterator that still has files left; they move together.+ let anyMore = false+ for (const loop of forEachLoops) {+ const remaining = loopCounters.get(loop.whileId)+ if (remaining != null && remaining > 1) {+ loopCounters.set(loop.whileId, remaining - 1)+ bumpWhileProgress(loop.whileId)+ anyMore = true+ }+ }+ if (anyMore) {+ setRunState((s) => ({ ...s, blockStep: 'Next file…' }))+ activeLoopBody = groupBody+ return jumpTo+ }+ activeLoopBody = null+ return undefined+ }++ if (!whileLoop) return undefined+ const remaining = loopCounters.get(whileLoop.whileId)++ // Auto mode with iterations left → loop back automatically.+ if (remaining != null && remaining > 1) {+ loopCounters.set(whileLoop.whileId, remaining - 1)+ bumpWhileProgress(whileLoop.whileId)+ setRunState((s) => ({ ...s, blockStep: `Looping… ${remaining - 1} left` }))+ activeLoopBody = whileLoop.bodyIds+ return whileLoop.firstIdx+ }+ // Otherwise the auto counter is exhausted (or it's manual mode): pause on+ // the While and wait for Continue (proceed) or Retry (run the body again).+ // runningBranchId blocks Wait branches while the pre-phase is parked here.+ _retry.current = false+ set({ activeNodeId: whileLoop.whileId, runningBranchId: whileLoop.whileId })+ setRunState((s) => ({ ...s, status: 'paused', blockStep: 'Loop finished — Continue or Retry' }))+ await new Promise<void>((resolve) => { _resume.current = resolve })+ if (_cancel.current) return 'cancel'+ set({ runningBranchId: null })+ setRunState((s) => ({ ...s, status: 'running' }))+ if (_retry.current) {+ _retry.current = false+ bumpWhileProgress(whileLoop.whileId)+ activeLoopBody = whileLoop.bodyIds+ return whileLoop.firstIdx+ }+ activeLoopBody = null // Continue → resume normal forward execution+ return undefined+ }++ // Pre-phase: nodes that don't belong to any single branch (sources + merges).+ let stepsDone = 0+ for (let i = 0; i < preExecExtNodes.length; i++) {+ if (_cancel.current) { _ctx.current = null; set({ runState: IDLE, activeNodeId: null }); return }+ const node = preExecExtNodes[i]+ // During a loop replay, only re-run the active loop's body members.+ if (activeLoopBody && !activeLoopBody.has(node.id)) continue+ set((s) => ({+ activeNodeId: node.id,+ runState: { ...s.runState, blockIndex: stepsDone, blockProgress: 0, blockStep: 'Starting…' },+ }))+ await executeExtensionNode(node, ctx, setRunState)+ stepsDone++++ const jump = await handleLoopEnd(i)+ if (jump === 'cancel') { _ctx.current = null; set({ runState: IDLE, activeNodeId: null }); return }+ if (jump !== undefined) { i = jump - 1 }+ }++ if (waitIds.length > 0) {+ // Hand off to the user — branches run on demand via continueRun(id).+ set((s) => ({+ activeNodeId: null,+ runState: { ...s.runState, status: 'paused', blockStep: 'Pick a branch and click Continue' },+ }))+ return+ }++ finalize(ctx)+ } catch (err) {+ if (!_cancel.current) {+ set((s) => ({ runState: { ...s.runState, status: 'error', error: String(err) }, activeNodeId: null }))+ useAppStore.getState().updateCurrentJob({ status: 'error', error: String(err) })+ void showErrorNotification(String(err), 'Workflow run failed')+ }+ }+ },++ async continueRun(waitId) {+ const state = get()+ if (state.runningBranchId !== null) return+ // Only runnable Waits: blocked (parent not done) and running are not.+ const ws = state.waitStates[waitId]+ if (ws !== 'pending' && ws !== 'done' && ws !== 'error') return+ // A pending Wait only runs after a clean handoff. If the run errored in the+ // pre-phase, it never handed off — don't start a branch with missing inputs.+ if (ws === 'pending' && state.runState.status === 'error') return+ const ctx = _ctx.current+ if (!ctx) {+ console.warn('continueRun: no active run context — was the module hot-reloaded mid-run?')+ return+ }++ const branch = ctx.branches.get(waitId) ?? []+ // Re-running a Wait invalidates everything downstream: descendant branches+ // were computed against the old output, so drop their outputs and reset+ // them to blocked until this branch produces a fresh result.+ const descendants = descendantWaits(waitId, ctx)++ _cancel.current = false++ // Reset outputs for this branch's nodes so Retry re-executes cleanly.+ for (const node of branch) ctx.nodeOutputs.delete(node.id)+ for (const d of descendants) for (const node of ctx.branches.get(d) ?? []) ctx.nodeOutputs.delete(node.id)++ set((s) => {+ const waitStates = { ...s.waitStates, [waitId]: 'running' as WaitState }+ for (const d of descendants) waitStates[d] = 'blocked'+ return {+ runningBranchId: waitId,+ waitStates,+ runState: { ...s.runState, status: 'running', blockIndex: 0, blockTotal: branch.length, blockProgress: 0, blockStep: branch.length === 0 ? 'Done' : 'Starting…' },+ }+ })++ const finishBranch = (next: WaitState, err?: string): void => {+ if (_cancel.current) return+ const newWaitStates = { ...get().waitStates, [waitId]: next }+ // Unblock nested Waits whose parent branch just finished, and push this+ // branch's scene output to the viewer.+ if (next === 'done') {+ for (const w of ctx.waitIds) {+ if (ctx.parentWait.get(w) === waitId && newWaitStates[w] === 'blocked') newWaitStates[w] = 'pending'+ }+ pushBranchSceneMesh(ctx, waitId)+ }+ // A failed branch can never feed its descendants — surface them as error+ // too, otherwise they stay 'blocked' and the run hangs on 'paused' forever.+ if (next === 'error') {+ for (const d of descendantWaits(waitId, ctx)) {+ if (newWaitStates[d] === 'blocked') newWaitStates[d] = 'error'+ }+ }+ const allFinished = ctx.waitIds.every((id) => newWaitStates[id] === 'done' || newWaitStates[id] === 'error')+ const anyError = ctx.waitIds.some((id) => newWaitStates[id] === 'error')++ if (allFinished && !anyError) {+ finalize(ctx, newWaitStates)+ } else {+ set((s) => ({+ activeNodeId: null,+ runningBranchId: null,+ waitStates: newWaitStates,+ runState: {+ ...s.runState,+ status: allFinished ? 'error' : 'paused',+ error: anyError ? (err ?? s.runState.error) : undefined,+ blockStep: err ? `Branch failed: ${err}` : 'Pick a branch and click Continue',+ },+ }))+ }+ }++ try {+ for (let i = 0; i < branch.length; i++) {+ if (_cancel.current) return+ const node = branch[i]+ set((s) => ({+ activeNodeId: node.id,+ runState: { ...s.runState, blockIndex: i, blockProgress: 0, blockStep: 'Starting…' },+ }))+ await executeExtensionNode(node, ctx, setRunState)+ }+ finishBranch('done')+ } catch (err) {+ finishBranch('error', String(err))+ }+ },++ cancel() {+ _cancel.current = true+ _pauseRequested.current = false+ flushResume() // unblock a manual While pause so the run can tear down+ if (_activeJobId.current) {+ const apiUrl = useAppStore.getState().apiUrl+ axios.create({ baseURL: apiUrl }).post(`/generate/cancel/${_activeJobId.current}`).catch(() => {})+ _activeJobId.current = null+ }+ _ctx.current = null+ set({ runState: IDLE, activeNodeId: null, activeWorkflowId: null, nodeImageOutputs: {}, waitStates: {}, runningBranchId: null, whileProgress: {}, pausedGroup: [] })+ useAppStore.getState().setCurrentJob(null)+ },++ reset() {+ _ctx.current = null+ set({ runState: IDLE, activeNodeId: null, activeWorkflowId: null, nodeImageOutputs: {}, waitStates: {}, runningBranchId: null, whileProgress: {}, pausedGroup: [] })+ },++ continueWhile() {+ flushResume()+ },++ retryWhile() {+ _retry.current = true+ flushResume()+ },++ pauseWhile() {+ _pauseRequested.current = true+ },++ setLiveNodeParams(nodeId, params) {+ _liveParams.current.set(nodeId, params)+ },+ }+})diff --git a/apps/forge-desktop/src/areas/workflows/workflowSceneRun.test.mjs b/apps/forge-desktop/src/areas/workflows/workflowSceneRun.test.mjsnew file mode 100644index 000000000..cb43b9d55--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/workflowSceneRun.test.mjs@@ -0,0 +1,60 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { build } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++const dir = mkdtempSync(join(tmpdir(), 'modly-scene-run-'))+const stub = (name, source) => { const path = join(dir, name); writeFileSync(path, source); return path }+const appStoreStub = stub('app.ts', `+export const appState: any = { apiUrl: 'http://modly.test', currentJob: null,+ setCurrentJob(value: any) { this.currentJob = value },+ updateCurrentJob(value: any) { this.currentJob = { ...(this.currentJob ?? {}), ...value } } }+export const useAppStore: any = (selector: any) => selector(appState)+useAppStore.getState = () => appState+`)+const axiosStub = stub('axios.ts', `const axios: any = { create: () => (globalThis as any).__sceneClient }; export default axios; export type AxiosInstance = any`)+const extStub = stub('ext.ts', `export const getWorkflowExtension = (id: string, all: any[]) => all.find((value) => value.id === id); export type WorkflowExtension = any`)+const notifyStub = stub('notify.ts', `export const showCompletionNotification = async () => {}; export const showErrorNotification = async () => {}`)+const aliases = new Map([+ ['axios', axiosStub], ['@shared/stores/appStore', appStoreStub],+ ['./mockExtensions', extStub], ['@shared/utils/notification', notifyStub],+])+const outfile = join(dir, 'store.cjs')+writeFileSync(outfile, (await build({+ entryPoints: [resolve('src/areas/workflows/workflowRunStore.ts')], bundle: true,+ platform: 'node', format: 'cjs', write: false,+ plugins: [{ name: 'aliases', setup(build) { build.onResolve({ filter: /.*/ }, (args) => aliases.has(args.path) ? { path: aliases.get(args.path) } : null) } }],+})).outputFiles[0].text)+const { useWorkflowRunStore } = createRequire(import.meta.url)(outfile)++test('scene model uses typed artifact route and preserves scene output', async () => {+ const posts = []+ globalThis.window = { electron: {+ settings: { get: async () => ({ workspaceDir: '/workspace' }) },+ fs: { deleteDirectory: async () => ({ success: true }), listFiles: async () => [], readFileBase64: async () => { throw new Error('scene must not be read as image bytes') } },+ } }+ globalThis.__sceneClient = {+ post: async (url, body) => { posts.push({ url, body }); return { data: { job_id: 'scene-job' } } },+ get: async () => ({ data: { status: 'done', progress: 100, output_url: '/workspace/Workflows/result/scene-manifest.json' } }),+ }+ const workflow = {+ id: 'wf', name: 'Scene', description: '', createdAt: '', updatedAt: '',+ nodes: [+ { id: 'source', type: 'sceneNode', position: { x: 0, y: 0 }, data: { enabled: true, params: { manifestPath: 'Workflows/input/scene-manifest.json' } } },+ { id: 'model', type: 'extensionNode', position: { x: 1, y: 0 }, data: { enabled: true, extensionId: 'pixal/world', params: {} } },+ ],+ edges: [{ id: 'e', source: 'source', target: 'model' }],+ }+ const extension = { id: 'pixal/world', name: 'World', type: 'model', input: 'scene', output: 'scene', params: [] }+ await useWorkflowRunStore.getState().run(workflow, [extension])+ assert.equal(posts[0].url, '/generate/from-artifact')+ assert.deepEqual(posts[0].body, {+ input_kind: 'scene', input_path: 'Workflows/input/scene-manifest.json',+ model_id: 'pixal/world', collection: 'Workflows', params: {},+ })+ assert.equal(useWorkflowRunStore.getState().runState.outputPath, '/workspace/Workflows/result/scene-manifest.json')+ assert.equal(useWorkflowRunStore.getState().runState.outputUrl, undefined)+})diff --git a/apps/forge-desktop/src/areas/workflows/workflowSceneSource.test.mjs b/apps/forge-desktop/src/areas/workflows/workflowSceneSource.test.mjsnew file mode 100644index 000000000..778e13d3e--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/workflowSceneSource.test.mjs@@ -0,0 +1,70 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++const outfile = join(mkdtempSync(join(tmpdir(), 'modly-scene-source-')), 'scene.cjs')+writeFileSync(outfile, buildSync({ entryPoints: [resolve('src/areas/workflows/workflowSceneSource.ts')], bundle: true, platform: 'node', format: 'cjs', write: false }).outputFiles[0].text)+const {+ applySceneValidationResult,+ invalidateValidatedScenePath,+ resolveSceneSourceManifest,+} = createRequire(import.meta.url)(outfile)+const encoded = Buffer.from(JSON.stringify({ schema: 'modly.scene-manifest.v1', sceneRoot: '.', assets: [] })).toString('base64')++test('Load Scene resolves directory and manifest without image bytes', async () => {+ for (const scenePath of ['Workflows/room', 'Workflows/room/scene-manifest.json']) {+ const result = await resolveSceneSourceManifest({ scenePath, workspaceDir: '/workspace', readFileBase64: async () => encoded })+ assert.equal(result.ok, true)+ assert.equal(result.manifestWorkspacePath, 'Workflows/room/scene-manifest.json')+ }+})++test('Load Scene refuses unsafe paths before reading', async () => {+ let reads = 0+ for (const scenePath of ['../outside', '/etc/passwd', 'C:/outside', 'Workflows/%2e%2e', 'Workflows/room/']) {+ const result = await resolveSceneSourceManifest({ scenePath, workspaceDir: '/workspace', readFileBase64: async () => { reads++; return encoded } })+ assert.equal(result.ok, false, scenePath)+ }+ assert.equal(reads, 0)+})++test('editing a validated Load Scene path clears every derived scene reference', () => {+ const params = invalidateValidatedScenePath({+ path: 'Workflows/old',+ manifestPath: 'Workflows/old/scene-manifest.json',+ sceneRoot: '.',+ sourceKind: 'directory',+ }, 'Workflows/new')++ assert.equal(params.path, 'Workflows/new')+ assert.equal(params.manifestPath, undefined)+ assert.equal(params.sceneRoot, undefined)+ assert.equal(params.sourceKind, undefined)+})++test('an async validation result cannot overwrite a subsequently edited path', async () => {+ const oldResolution = await resolveSceneSourceManifest({+ scenePath: 'Workflows/old',+ workspaceDir: '/workspace',+ readFileBase64: async () => encoded,+ })+ assert.equal(oldResolution.ok, true)++ const currentParams = invalidateValidatedScenePath({+ path: 'Workflows/old',+ manifestPath: 'Workflows/old/scene-manifest.json',+ sceneRoot: '.',+ sourceKind: 'directory',+ }, 'Workflows/new')++ assert.equal(+ applySceneValidationResult(currentParams, 'Workflows/old', oldResolution),+ undefined,+ )+ assert.equal(currentParams.path, 'Workflows/new')+ assert.equal(currentParams.manifestPath, undefined)+})diff --git a/apps/forge-desktop/src/areas/workflows/workflowSceneSource.ts b/apps/forge-desktop/src/areas/workflows/workflowSceneSource.tsnew file mode 100644index 000000000..efe2b3ed0--- /dev/null+++ b/apps/forge-desktop/src/areas/workflows/workflowSceneSource.ts@@ -0,0 +1,246 @@+import type { SceneArtifactManifestInitialView, SceneArtifactManifestPreview, SceneArtifactManifestV1 } from '../../shared/types/artifacts'++export const SCENE_MANIFEST_FILE_NAME = 'scene-manifest.json'++export type SceneSourceKind = 'manifest' | 'directory'++export type ResolveSceneSourceSuccess = {+ ok: true+ sourceKind: SceneSourceKind+ inputWorkspacePath: string+ manifestWorkspacePath: string+ manifestAbsolutePath: string+ sceneRoot: string+ manifest: SceneArtifactManifestV1+}++export type ResolveSceneSourceFailure = {+ ok: false+ error: string+}++export type ResolveSceneSourceResult = ResolveSceneSourceSuccess | ResolveSceneSourceFailure++export function applySceneValidationResult(+ currentParams: Record<string, unknown>,+ validatedPath: string,+ resolution: ResolveSceneSourceResult,+): Record<string, unknown> | undefined {+ if (currentParams.path !== validatedPath) return undefined++ if (!resolution.ok) {+ return {+ ...currentParams,+ manifestPath: undefined,+ sceneRoot: undefined,+ sourceKind: undefined,+ error: resolution.error,+ }+ }++ return {+ ...currentParams,+ path: resolution.inputWorkspacePath,+ manifestPath: resolution.manifestWorkspacePath,+ sceneRoot: resolution.sceneRoot,+ sourceKind: resolution.sourceKind,+ error: undefined,+ }+}++export function invalidateValidatedScenePath(+ params: Record<string, unknown>,+ nextPath: string,+): Record<string, unknown> {+ return {+ ...params,+ path: nextPath,+ manifestPath: undefined,+ sceneRoot: undefined,+ sourceKind: undefined,+ error: undefined,+ }+}++type ResolveSceneSourceArgs = {+ scenePath: string+ workspaceDir: string+ readFileBase64: (filePath: string) => Promise<string>+}++function isAbsolutePath(value: string): boolean {+ return value.startsWith('/') || /^[A-Za-z]:\//.test(value)+}++function trimTrailingSlashes(value: string): string {+ return value.replace(/\/+$/, '')+}++function isSafeRelativePath(value: unknown, allowDot = false): value is string {+ if (typeof value !== 'string' || !value || value !== value.trim() || value.includes('\u0000')) return false+ const normalized = value.replace(/\\/g, '/')+ if (allowDot && normalized === '.') return true+ if (isAbsolutePath(normalized) || /^[A-Za-z][A-Za-z0-9+.-]*:/.test(normalized)+ || /%(?:25|2e|2f|5c|00)/i.test(normalized) || /%(?![0-9a-f]{2})/i.test(normalized)) return false+ return normalized.split('/').every((segment) => segment.length > 0 && segment !== '.' && segment !== '..')+}++function normalizeWorkspaceRelativePath(value: string | undefined, workspaceDir: string): string | undefined {+ const normalizedValue = value?.replace(/\\/g, '/')+ if (!normalizedValue) return undefined++ const normalizedWorkspace = trimTrailingSlashes(workspaceDir.replace(/\\/g, '/'))+ let relativePath: string | undefined++ if (normalizedValue.startsWith('/workspace/')) {+ relativePath = normalizedValue.slice('/workspace/'.length)+ } else if (normalizedValue === normalizedWorkspace) {+ return undefined+ } else if (normalizedValue.startsWith(`${normalizedWorkspace}/`)) {+ relativePath = normalizedValue.slice(normalizedWorkspace.length + 1)+ } else if (!isAbsolutePath(normalizedValue)) {+ relativePath = normalizedValue+ }++ if (!relativePath) return undefined+ return isSafeRelativePath(relativePath) ? relativePath : undefined+}++function resolveSceneSourceKind(inputWorkspacePath: string): SceneSourceKind | undefined {+ if (inputWorkspacePath === SCENE_MANIFEST_FILE_NAME || inputWorkspacePath.endsWith(`/${SCENE_MANIFEST_FILE_NAME}`)) {+ return 'manifest'+ }+ if (inputWorkspacePath.toLowerCase().endsWith('.json')) return undefined+ return 'directory'+}++function decodeBase64Utf8(base64: string): string {+ const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0))+ return new TextDecoder().decode(bytes)+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}++function isSafePreviewReference(value: unknown): value is string {+ return isSafeRelativePath(value)+}++function isSceneManifestPreview(value: unknown): value is SceneArtifactManifestPreview {+ return isPlainObject(value)+ && (!('image' in value) || isSafePreviewReference(value.image))+ && (!('video' in value) || isSafePreviewReference(value.video))+}++function isFiniteTriple(value: unknown): value is [number, number, number] {+ return Array.isArray(value) && value.length === 3+ && value.every((component) => typeof component === 'number' && Number.isFinite(component))+}++function isSceneManifestInitialView(value: unknown): value is SceneArtifactManifestInitialView {+ if (!isPlainObject(value)) return false+ const { position, target, up } = value+ if (!isFiniteTriple(position) || !isFiniteTriple(target)) return false+ if (position.every((component, index) => component === target[index])) return false+ return up === undefined || (isFiniteTriple(up) && up.some((component) => component !== 0))+}++function normalizeSceneRoot(sceneRoot: unknown): string | undefined {+ return isSafeRelativePath(sceneRoot, true) ? sceneRoot.replace(/\\/g, '/') : undefined+}++function validateSceneManifest(manifest: unknown): { ok: true; manifest: SceneArtifactManifestV1; sceneRoot: string } | { ok: false; error: string } {+ if (!isPlainObject(manifest)) {+ return { ok: false, error: 'Scene manifest must be a JSON object.' }+ }+ if (manifest.schema !== 'modly.scene-manifest.v1') {+ return { ok: false, error: 'Scene manifest schema must be modly.scene-manifest.v1.' }+ }++ const rawSceneRoot = manifest.sceneRoot+ const sceneRoot = normalizeSceneRoot(rawSceneRoot)+ if (typeof rawSceneRoot !== 'string' || !sceneRoot) {+ return { ok: false, error: 'Scene manifest sceneRoot must be a safe relative path.' }+ }+ if (!Array.isArray(manifest.assets)) {+ return { ok: false, error: 'Scene manifest assets must be an array.' }+ }+ if (manifest.assets.some((asset) => isPlainObject(asset)+ && (('workspacePath' in asset && !isSafeRelativePath(asset.workspacePath))+ || ('path' in asset && !isSafeRelativePath(asset.path))))) {+ return { ok: false, error: 'Scene manifest asset paths must be safe relative file references.' }+ }++ const { preview, initialView, ...metadata } = manifest+ if (preview !== undefined && !isPlainObject(preview)) {+ return { ok: false, error: 'Scene manifest preview must be a JSON object.' }+ }+ if (preview !== undefined && !isSceneManifestPreview(preview)) {+ return { ok: false, error: 'Scene manifest preview image/video must be safe relative file references.' }+ }+ if (initialView !== undefined && !isPlainObject(initialView)) {+ return { ok: false, error: 'Scene manifest initialView must be a JSON object.' }+ }+ if (initialView !== undefined && !isSceneManifestInitialView(initialView)) {+ return { ok: false, error: 'Scene manifest initialView requires distinct finite numeric position/target triples and optional non-zero finite up.' }+ }++ return {+ ok: true,+ sceneRoot,+ manifest: {+ ...metadata,+ schema: 'modly.scene-manifest.v1',+ sceneRoot: rawSceneRoot,+ assets: manifest.assets,+ ...(preview !== undefined ? { preview } : {}),+ ...(initialView !== undefined ? { initialView } : {}),+ },+ }+}++export async function resolveSceneSourceManifest(args: ResolveSceneSourceArgs): Promise<ResolveSceneSourceResult> {+ const inputWorkspacePath = normalizeWorkspaceRelativePath(args.scenePath, args.workspaceDir)+ if (!inputWorkspacePath) {+ return { ok: false, error: 'Load Scene requires a safe workspace-relative scene path.' }+ }++ const sourceKind = resolveSceneSourceKind(inputWorkspacePath)+ if (!sourceKind) {+ return { ok: false, error: `Load Scene accepts ${SCENE_MANIFEST_FILE_NAME} or a scene directory.` }+ }++ const manifestWorkspacePath = sourceKind === 'manifest'+ ? inputWorkspacePath+ : `${inputWorkspacePath}/${SCENE_MANIFEST_FILE_NAME}`+ const normalizedWorkspace = trimTrailingSlashes(args.workspaceDir.replace(/\\/g, '/'))+ const manifestAbsolutePath = `${normalizedWorkspace}/${manifestWorkspacePath}`++ let manifestRaw: string+ try {+ manifestRaw = decodeBase64Utf8(await args.readFileBase64(manifestAbsolutePath))+ } catch (error) {+ return { ok: false, error: `Unable to read scene manifest: ${String(error)}` }+ }++ let parsed: unknown+ try {+ parsed = JSON.parse(manifestRaw)+ } catch (error) {+ return { ok: false, error: `Scene manifest is not valid JSON: ${String(error)}` }+ }++ const validation = validateSceneManifest(parsed)+ if (!validation.ok) return validation++ return {+ ok: true,+ sourceKind,+ inputWorkspacePath,+ manifestWorkspacePath,+ manifestAbsolutePath,+ sceneRoot: validation.sceneRoot,+ manifest: validation.manifest,+ }+}diff --git a/apps/forge-desktop/src/assets/fonts/atkinson-hyperlegible/AtkinsonHyperlegible-Bold.woff2 b/apps/forge-desktop/src/assets/fonts/atkinson-hyperlegible/AtkinsonHyperlegible-Bold.woff2new file mode 100644index 000000000..3edf0a174Binary files /dev/null and b/apps/forge-desktop/src/assets/fonts/atkinson-hyperlegible/AtkinsonHyperlegible-Bold.woff2 differdiff --git a/apps/forge-desktop/src/assets/fonts/atkinson-hyperlegible/AtkinsonHyperlegible-Regular.woff2 b/apps/forge-desktop/src/assets/fonts/atkinson-hyperlegible/AtkinsonHyperlegible-Regular.woff2new file mode 100644index 000000000..d3ef5be8aBinary files /dev/null and b/apps/forge-desktop/src/assets/fonts/atkinson-hyperlegible/AtkinsonHyperlegible-Regular.woff2 differdiff --git a/apps/forge-desktop/src/assets/fonts/atkinson-hyperlegible/OFL.txt b/apps/forge-desktop/src/assets/fonts/atkinson-hyperlegible/OFL.txtnew file mode 100644index 000000000..2befc89b0--- /dev/null+++ b/apps/forge-desktop/src/assets/fonts/atkinson-hyperlegible/OFL.txt@@ -0,0 +1,92 @@+Copyright 2020 Braille Institute of America, Inc.++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/apps/forge-desktop/src/assets/workflow-helper.png b/apps/forge-desktop/src/assets/workflow-helper.pngnew file mode 100644index 000000000..599fc28b3Binary files /dev/null and b/apps/forge-desktop/src/assets/workflow-helper.png differdiff --git a/apps/forge-desktop/src/index.html b/apps/forge-desktop/src/index.htmlnew file mode 100644index 000000000..6e778cf02--- /dev/null+++ b/apps/forge-desktop/src/index.html@@ -0,0 +1,13 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: file:; connect-src 'self' blob: http://127.0.0.1:8765 http://localhost:8080 https://api.github.com; worker-src 'self' blob:" />+ <title>Modly</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="./main.tsx"></script>+ </body>+</html>diff --git a/apps/forge-desktop/src/main.tsx b/apps/forge-desktop/src/main.tsxnew file mode 100644index 000000000..65e866610--- /dev/null+++ b/apps/forge-desktop/src/main.tsx@@ -0,0 +1,18 @@+import React from 'react'+import ReactDOM from 'react-dom/client'+import App from './App'+import '@styles/globals.css'+import '@xyflow/react/dist/style.css'++window.addEventListener('error', (e) => {+ window.electron.log.error(`${e.message} — ${e.filename}:${e.lineno}`)+})+window.addEventListener('unhandledrejection', (e) => {+ window.electron.log.error(`Unhandled promise rejection: ${String(e.reason)}`)+})++ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(+ <React.StrictMode>+ <App />+ </React.StrictMode>+)diff --git a/apps/forge-desktop/src/shared/components/layout/MainLayout.tsx b/apps/forge-desktop/src/shared/components/layout/MainLayout.tsxnew file mode 100644index 000000000..da5bcd9c5--- /dev/null+++ b/apps/forge-desktop/src/shared/components/layout/MainLayout.tsx@@ -0,0 +1,20 @@+import TopBar from './TopBar'+import Sidebar from './Sidebar'+import Router from '@shared/router/Router'++export default function MainLayout(): JSX.Element {++ return (+ <div className="flex flex-col h-full bg-surface-500">+ <TopBar />++ <div className="flex flex-1 overflow-hidden">+ <Sidebar />++ <main className="flex flex-1 overflow-hidden">+ <Router />+ </main>+ </div>+ </div>+ )+}diff --git a/apps/forge-desktop/src/shared/components/layout/MemoryIndicator.tsx b/apps/forge-desktop/src/shared/components/layout/MemoryIndicator.tsxnew file mode 100644index 000000000..fe09eac12--- /dev/null+++ b/apps/forge-desktop/src/shared/components/layout/MemoryIndicator.tsx@@ -0,0 +1,66 @@+import { useEffect, useState } from 'react'++const GB = 1024 ** 3++function fmtGB(bytes: number): string {+ return (bytes / GB).toFixed(1)+}++export default function MemoryIndicator(): JSX.Element | null {+ const [mem, setMem] = useState<{ total: number; used: number; available: number } | null>(null)++ useEffect(() => {+ let cancelled = false+ const tick = async () => {+ try {+ const next = await window.electron.system.memory()+ if (!cancelled) setMem(next)+ } catch {+ // Renderer should not break if memory sampling fails.+ }+ }+ tick()+ const id = setInterval(tick, 2000)+ return () => {+ cancelled = true+ clearInterval(id)+ }+ }, [])++ if (!mem) return null++ const pct = mem.total > 0 ? Math.min(100, Math.round((mem.used / mem.total) * 100)) : 0++ let barColor = 'bg-emerald-500'+ let textColor = 'text-zinc-300'+ if (pct >= 90) {+ barColor = 'bg-red-500'+ textColor = 'text-red-300'+ } else if (pct >= 75) {+ barColor = 'bg-amber-500'+ textColor = 'text-amber-300'+ }++ const tooltip =+ `Used: ${fmtGB(mem.used)} GB\n` ++ `Available: ${fmtGB(mem.available)} GB\n` ++ `Total: ${fmtGB(mem.total)} GB`++ return (+ <div+ className="flex items-center gap-2 mr-3 px-2.5 py-1 rounded-md bg-zinc-800/60 border border-zinc-700/60 no-drag"+ title={tooltip}+ >+ <span className="text-[10px] font-medium text-zinc-500 tracking-wide uppercase">RAM</span>+ <div className="w-20 h-1.5 bg-zinc-900 rounded-full overflow-hidden">+ <div+ className={`h-full ${barColor} transition-all duration-500 ease-out`}+ style={{ width: `${pct}%` }}+ />+ </div>+ <span className={`text-[11px] tabular-nums ${textColor}`}>+ {fmtGB(mem.used)} / {fmtGB(mem.total)} GB+ </span>+ </div>+ )+}diff --git a/apps/forge-desktop/src/shared/components/layout/Sidebar.tsx b/apps/forge-desktop/src/shared/components/layout/Sidebar.tsxnew file mode 100644index 000000000..767b2b017--- /dev/null+++ b/apps/forge-desktop/src/shared/components/layout/Sidebar.tsx@@ -0,0 +1,76 @@+import { useNavStore, type Page } from '@shared/stores/navStore'++const NAV_ITEMS: { id: Page; label: string; icon: JSX.Element }[] = [+ {+ id: 'generate',+ label: 'Generate',+ icon: (+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">+ <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" />+ </svg>+ )+ },+ {+ id: 'workflows',+ label: 'Workflows',+ icon: (+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">+ <rect x="3" y="3" width="6" height="5" rx="1" />+ <rect x="3" y="11" width="6" height="5" rx="1" />+ <rect x="3" y="19" width="6" height="2" rx="1" />+ <path d="M9 5.5h3.5a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H9" />+ <rect x="13.5" y="3" width="7.5" height="16" rx="1" />+ </svg>+ )+ },+ {+ id: 'models',+ label: 'Extensions',+ icon: (+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">+ <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />+ <polyline points="3.27 6.96 12 12.01 20.73 6.96" />+ <line x1="12" y1="22.08" x2="12" y2="12" />+ </svg>+ )+ },+ {+ id: 'settings',+ label: 'Settings',+ icon: (+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">+ <circle cx="12" cy="12" r="3" />+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />+ </svg>+ )+ }+]++export default function Sidebar(): JSX.Element {+ const { currentPage, navigate } = useNavStore()++ return (+ <aside className="flex flex-col w-14 bg-surface-500 border-r border-zinc-800 py-2">+ {NAV_ITEMS.map((item) => {+ const active = currentPage === item.id+ return (+ <button+ key={item.id}+ title={item.label}+ onClick={() => navigate(item.id)}+ className={`+ relative flex flex-col items-center justify-center gap-1 h-12 mx-1 my-0.5 rounded+ transition-colors text-[9px] leading-none+ ${active+ ? 'bg-accent/20 text-accent-light'+ : 'text-zinc-500 hover:text-zinc-100 hover:bg-zinc-800'}+ `}+ >+ {item.icon}+ {item.label}+ </button>+ )+ })}+ </aside>+ )+}diff --git a/apps/forge-desktop/src/shared/components/layout/TopBar.tsx b/apps/forge-desktop/src/shared/components/layout/TopBar.tsxnew file mode 100644index 000000000..c73fd02a0--- /dev/null+++ b/apps/forge-desktop/src/shared/components/layout/TopBar.tsx@@ -0,0 +1,103 @@+import { useEffect, useState } from 'react'+import { useAppStore } from '@shared/stores/appStore'+import MemoryIndicator from './MemoryIndicator'++export default function TopBar(): JSX.Element {+ const { patchUpdateReady, platform, showRamIndicator } = useAppStore()+ const isMac = platform === 'darwin'++ const [isMaximized, setIsMaximized] = useState(false)++ useEffect(() => {+ window.electron.window.isMaximized().then(setIsMaximized)+ window.electron.window.onMaximizeChange(setIsMaximized)+ return () => window.electron.window.offMaximizeChange()+ }, [])++ const handleMinimize = () => window.electron.window.minimize()+ const handleMaximize = () => window.electron.window.maximize()+ const handleClose = () => window.electron.window.close()++ return (+ <header className="flex items-center h-10 px-4 bg-surface-400 border-b border-zinc-800 drag-region shrink-0">+ {/* App name */}+ <div className={`flex items-center gap-2 no-drag ${isMac ? 'pl-[72px]' : ''}`}>+ <svg width="26" height="26" viewBox="0 0 609 609" xmlns="http://www.w3.org/2000/svg" className="shrink-0">+ <defs>+ <linearGradient id="tlg" x1="700" y1="5700" x2="5900" y2="750" gradientUnits="userSpaceOnUse">+ <stop offset="0%" stopColor="#c084fc"/>+ <stop offset="45%" stopColor="#9333ea"/>+ <stop offset="100%" stopColor="#4c1d95"/>+ </linearGradient>+ </defs>+ <g transform="translate(0,609) scale(0.1,-0.1)" fill="url(#tlg)" stroke="none">+ <path d="M2964 5671 c-20 -9 -918 -521 -1604 -914 -173 -100 -362 -207 -420 -239 -58 -32 -118 -73 -133 -91 -58 -67 -57 -45 -57 -1067 0 -831 2 -938 16 -958 l15 -22 758 0 c417 0 761 3 764 6 12 13 -26 67 -283 399 -64 83 -120 156 -124 163 -5 7 4 32 22 60 16 26 238 396 493 822 254 426 569 951 699 1165 308 506 305 502 290 520 -7 8 -72 48 -144 87 -124 69 -135 73 -201 75 -38 2 -79 -1 -91 -6z"/>+ <path d="M3683 5328 c-18 -23 -833 -1306 -833 -1312 0 -12 83 -15 485 -21 230 -3 420 -7 421 -8 4 -5 451 -755 657 -1102 438 -739 668 -1120 691 -1143 l23 -24 71 36 c91 46 139 88 152 134 14 50 14 2403 0 2453 -20 72 -48 98 -215 193 -766 440 -1414 806 -1427 806 -9 0 -20 -6 -25 -12z"/>+ <path d="M4037 2838 c-25 -33 -443 -702 -467 -747 l-12 -24 -1384 4 c-1247 4 -1385 2 -1399 -12 -44 -44 -21 -170 42 -231 21 -20 203 -132 408 -249 385 -220 1034 -594 1310 -754 88 -51 183 -105 210 -121 28 -15 88 -49 134 -76 158 -90 177 -86 475 84 127 72 416 236 641 363 226 128 507 287 625 354 212 121 250 145 250 163 0 5 -40 73 -88 151 -49 78 -177 286 -284 462 -393 643 -407 664 -430 665 -4 0 -18 -15 -31 -32z"/>+ </g>+ </svg>+ <span className="text-sm font-semibold text-zinc-100">Modly</span>+ </div>++ {/* Spacer */}+ <div className="flex-1" />++ {/* Memory indicator */}+ {showRamIndicator && <MemoryIndicator />}++ {/* Patch update badge */}+ {patchUpdateReady && (+ <div className="flex items-center gap-2 mr-3 px-3 py-1 rounded-full bg-accent/15 border border-accent/30 text-xs text-accent-light no-drag">+ <span>Update ready</span>+ <button+ onClick={() => window.electron.updater.quitAndInstall()}+ className="ml-1 px-2 py-0.5 rounded-full bg-accent hover:bg-accent-dark text-white text-[11px] font-medium transition-colors"+ >+ Restart+ </button>+ </div>+ )}++ {/* Window controls — Mac uses the native traffic-light buttons on the left */}+ {!isMac && (+ <div className="flex items-center gap-1 no-drag">+ <button+ onClick={handleMinimize}+ className="w-8 h-8 flex items-center justify-center rounded hover:bg-zinc-700 text-zinc-400 hover:text-zinc-100 transition-colors"+ aria-label="Minimize"+ >+ <svg width="10" height="1" viewBox="0 0 10 1" fill="currentColor">+ <rect width="10" height="1" />+ </svg>+ </button>+ <button+ onClick={handleMaximize}+ className="w-8 h-8 flex items-center justify-center rounded hover:bg-zinc-700 text-zinc-400 hover:text-zinc-100 transition-colors"+ aria-label={isMaximized ? 'Restore' : 'Maximize'}+ >+ {isMaximized ? (+ <svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor">+ <rect x="2.5" y="0.5" width="7" height="7" />+ <path d="M0.5 2.5v7h7" />+ </svg>+ ) : (+ <svg width="9" height="9" viewBox="0 0 9 9" fill="none" stroke="currentColor">+ <rect x="0.5" y="0.5" width="8" height="8" />+ </svg>+ )}+ </button>+ <button+ onClick={handleClose}+ className="w-8 h-8 flex items-center justify-center rounded hover:bg-red-600 text-zinc-400 hover:text-white transition-colors"+ aria-label="Close"+ >+ <svg width="9" height="9" viewBox="0 0 9 9" fill="none" stroke="currentColor" strokeWidth="1.2">+ <line x1="0" y1="0" x2="9" y2="9" />+ <line x1="9" y1="0" x2="0" y2="9" />+ </svg>+ </button>+ </div>+ )}+ </header>+ )+}diff --git a/apps/forge-desktop/src/shared/components/ui/ColorPicker.tsx b/apps/forge-desktop/src/shared/components/ui/ColorPicker.tsxnew file mode 100644index 000000000..e268083ac--- /dev/null+++ b/apps/forge-desktop/src/shared/components/ui/ColorPicker.tsx@@ -0,0 +1,45 @@+import { useRef } from 'react'++interface ColorPickerProps {+ value: string+ onChange: (color: string) => void+ size?: 'sm' | 'md'+}++export function ColorPicker({ value, onChange, size = 'sm' }: ColorPickerProps): JSX.Element {+ const inputRef = useRef<HTMLInputElement>(null)++ const dim = size === 'sm' ? 'w-5 h-5' : 'w-6 h-6'++ return (+ <button+ type="button"+ onClick={() => inputRef.current?.click()}+ className={`${dim} rounded border border-zinc-600 hover:border-zinc-400 transition-colors shrink-0 relative overflow-hidden`}+ style={{ backgroundColor: value }}+ title={value}+ >+ {/* Checkerboard behind transparent colors */}+ <span+ className="absolute inset-0 -z-10"+ style={{+ backgroundImage:+ 'linear-gradient(45deg, #555 25%, transparent 25%),' ++ 'linear-gradient(-45deg, #555 25%, transparent 25%),' ++ 'linear-gradient(45deg, transparent 75%, #555 75%),' ++ 'linear-gradient(-45deg, transparent 75%, #555 75%)',+ backgroundSize: '6px 6px',+ backgroundPosition: '0 0, 0 3px, 3px -3px, -3px 0',+ }}+ />+ <input+ ref={inputRef}+ type="color"+ value={value}+ onChange={(e) => onChange(e.target.value)}+ className="absolute opacity-0 w-0 h-0 pointer-events-none"+ tabIndex={-1}+ />+ </button>+ )+}diff --git a/apps/forge-desktop/src/shared/components/ui/ConfirmModal.tsx b/apps/forge-desktop/src/shared/components/ui/ConfirmModal.tsxnew file mode 100644index 000000000..e09990a87--- /dev/null+++ b/apps/forge-desktop/src/shared/components/ui/ConfirmModal.tsx@@ -0,0 +1,86 @@+import { createPortal } from 'react-dom'++interface ConfirmModalProps {+ title: string+ description?: string+ confirmLabel?: string+ cancelLabel?: string+ variant?: 'danger' | 'default'+ onConfirm: () => void+ onCancel: () => void+}++export function ConfirmModal({+ title,+ description,+ confirmLabel = 'Confirm',+ cancelLabel = 'Cancel',+ variant = 'default',+ onConfirm,+ onCancel,+}: ConfirmModalProps): JSX.Element {+ return createPortal(+ <div+ className="fixed inset-0 z-[9999] flex items-center justify-center"+ onMouseDown={(e) => { if (e.target === e.currentTarget) onCancel() }}+ >+ {/* Backdrop */}+ <div className="absolute inset-0 bg-zinc-950/70 backdrop-blur-sm animate-fade-in" />++ {/* Modal */}+ <div className="relative w-80 rounded-2xl bg-zinc-900 border border-accent/20 shadow-2xl shadow-accent/5 overflow-hidden animate-slide-up-center">++ <div className="px-5 py-5 flex flex-col gap-4">++ {/* Icon + title */}+ <div className="flex items-start gap-3">+ <div className={`w-10 h-10 rounded-xl flex items-center justify-center shrink-0 ${+ variant === 'danger'+ ? 'bg-accent/10 border border-accent/20'+ : 'bg-accent/10 border border-accent/20'+ }`}>+ {variant === 'danger' ? (+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-accent-light">+ <polyline points="3 6 5 6 21 6" />+ <path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6" />+ <path d="M10 11v6M14 11v6" />+ <path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2" />+ </svg>+ ) : (+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-accent-light">+ <circle cx="12" cy="12" r="10" />+ <line x1="12" y1="8" x2="12" y2="12" />+ <line x1="12" y1="16" x2="12.01" y2="16" />+ </svg>+ )}+ </div>++ <div className="flex flex-col gap-1 pt-0.5">+ <h2 className="text-base font-semibold text-zinc-100 leading-tight">{title}</h2>+ {description && (+ <p className="text-xs text-zinc-500 leading-relaxed">{description}</p>+ )}+ </div>+ </div>++ {/* Actions */}+ <div className="flex gap-2.5">+ <button+ onClick={onCancel}+ className="flex-1 py-2.5 rounded-xl bg-zinc-800 hover:bg-zinc-700/80 text-zinc-400 hover:text-zinc-200 text-sm font-medium transition-colors border border-zinc-700/50"+ >+ {cancelLabel}+ </button>+ <button+ onClick={onConfirm}+ className="flex-1 py-2.5 rounded-xl bg-accent hover:bg-accent-dark text-white text-sm font-semibold transition-colors shadow-lg shadow-accent/20"+ >+ {confirmLabel}+ </button>+ </div>+ </div>+ </div>+ </div>,+ document.body+ )+}diff --git a/apps/forge-desktop/src/shared/components/ui/ErrorModal.tsx b/apps/forge-desktop/src/shared/components/ui/ErrorModal.tsxnew file mode 100644index 000000000..164ed8d01--- /dev/null+++ b/apps/forge-desktop/src/shared/components/ui/ErrorModal.tsx@@ -0,0 +1,57 @@+import { useState } from 'react'+import { useAppStore } from '@shared/stores/appStore'++export function ErrorModal(): JSX.Element | null {+ const { errorModal, hideError } = useAppStore()+ const [copied, setCopied] = useState(false)++ if (!errorModal) return null++ const handleCopy = () => {+ navigator.clipboard.writeText(errorModal).then(() => {+ setCopied(true)+ setTimeout(() => setCopied(false), 2000)+ })+ }++ return (+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">+ <div className="w-full max-w-lg mx-4 bg-surface-300 border border-zinc-700/60 rounded-xl shadow-2xl flex flex-col">+ {/* Header */}+ <div className="flex items-center gap-3 px-5 py-4 border-b border-zinc-700/50">+ <div className="w-7 h-7 rounded-full bg-red-500/15 border border-red-500/30 flex items-center justify-center shrink-0">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-red-400">+ <circle cx="12" cy="12" r="10" />+ <line x1="12" y1="8" x2="12" y2="12" />+ <line x1="12" y1="16" x2="12.01" y2="16" />+ </svg>+ </div>+ <span className="text-sm font-semibold text-zinc-100">An error occurred</span>+ </div>++ {/* Error message — selectable */}+ <div className="px-5 py-4">+ <pre className="text-xs text-red-400 bg-red-950/30 border border-red-900/30 rounded-lg px-4 py-3 max-h-60 overflow-y-auto whitespace-pre-wrap break-words select-text font-mono leading-relaxed">+ {errorModal}+ </pre>+ </div>++ {/* Actions */}+ <div className="flex items-center justify-end gap-2 px-5 pb-4">+ <button+ onClick={handleCopy}+ className="px-4 py-2 text-xs font-semibold rounded-lg bg-zinc-700/60 hover:bg-zinc-700 text-zinc-200 transition-colors"+ >+ {copied ? 'Copied!' : 'Copy'}+ </button>+ <button+ onClick={hideError}+ className="px-4 py-2 text-xs font-semibold rounded-lg bg-accent hover:bg-accent-dark text-white transition-colors"+ >+ Dismiss+ </button>+ </div>+ </div>+ </div>+ )+}diff --git a/apps/forge-desktop/src/shared/components/ui/FieldLabel.tsx b/apps/forge-desktop/src/shared/components/ui/FieldLabel.tsxnew file mode 100644index 000000000..35a16569f--- /dev/null+++ b/apps/forge-desktop/src/shared/components/ui/FieldLabel.tsx@@ -0,0 +1,29 @@+import { Tooltip } from './Tooltip'++interface FieldLabelProps {+ label: string+ tooltip?: string+ children?: React.ReactNode+}++export function FieldLabel({ label, tooltip, children }: FieldLabelProps): JSX.Element {+ return (+ <div className="flex items-center w-full">+ <span className="text-sm text-zinc-300">{label}</span>+ {children && <span className="ml-1.5 text-xs text-zinc-600">{children}</span>}+ {tooltip && (+ <span className="ml-auto">+ <Tooltip content={tooltip}>+ <span className="w-5 h-5 rounded-full flex items-center justify-center text-zinc-600 hover:text-accent-light transition-colors cursor-default select-none">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">+ <circle cx="12" cy="12" r="10" />+ <line x1="12" y1="16" x2="12" y2="12" />+ <line x1="12" y1="8" x2="12.01" y2="8" />+ </svg>+ </span>+ </Tooltip>+ </span>+ )}+ </div>+ )+}diff --git a/apps/forge-desktop/src/shared/components/ui/ModelLibraryModal.tsx b/apps/forge-desktop/src/shared/components/ui/ModelLibraryModal.tsxnew file mode 100644index 000000000..28d689996--- /dev/null+++ b/apps/forge-desktop/src/shared/components/ui/ModelLibraryModal.tsx@@ -0,0 +1,429 @@+import { useCallback, useEffect, useRef, useState } from 'react'+import { createPortal } from 'react-dom'+import { useAppStore } from '@shared/stores/appStore'+import { useAgentStore } from '@shared/stores/agentStore'+import { useLlmModels, type LlmModel } from '@shared/stores/llmModelsStore'+import { useLlmDownloadsStore } from '@shared/services/llmDownloads'+import { formatBytes as fmtBytes } from '@shared/utils/format'+import { SegmentedControl } from '@shared/ui'+import { SseProgressBar } from './SseProgressBar'+import { vramFit } from './vramFit'+import { agentGrade } from './agentGrade'++// ─── Types ────────────────────────────────────────────────────────────────────++// Single source of truth lives in the shared catalog store; re-exported here so+// existing importers (AgentSection) keep resolving `LlmModel` from this module.+export type { LlmModel }++interface LlmStatus {+ vram_gb: number | null+}++type Filter = 'all' | 'fits' | 'vision' | 'cad'++// ─── Helpers ──────────────────────────────────────────────────────────────────++export function formatBytes(n?: number): string {+ return n ? fmtBytes(n) : '—'+}++type Tone = 'accent' | 'warn' | 'muted' | 'outline'++const TONES: Record<Tone, string> = {+ accent: 'bg-accent/15 text-accent-light border-accent/30',+ warn: 'bg-amber-500/10 text-amber-400 border-amber-500/30',+ muted: 'bg-zinc-800 text-zinc-400 border-zinc-700',+ outline: 'bg-transparent text-accent-light border-accent/40',+}++function Tag({ tone, colors, icon, title, children }: {+ tone?: Tone+ /** Explicit color classes, for verdicts that bring their own (vramFit). */+ colors?: string+ icon?: React.ReactNode+ title?: string+ children: React.ReactNode+}): JSX.Element {+ return (+ <span title={title} className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md border text-[10px] font-medium ${colors ?? TONES[tone ?? 'muted']}`}>+ {icon}+ {children}+ </span>+ )+}++const ICONS = {+ check: <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><polyline points="20 6 9 17 4 12" /></svg>,+ warn: <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="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" /><line x1="12" y1="9" x2="12" y2="13" /><line x1="12" y1="17" x2="12.01" y2="17" /></svg>,+ star: <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polygon points="12 2 15.1 8.3 22 9.3 17 14.1 18.2 21 12 17.8 5.8 21 7 14.1 2 9.3 8.9 8.3 12 2" /></svg>,+ eye: <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" /><circle cx="12" cy="12" r="3" /></svg>,+ cube: <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" /></svg>,+ file: <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><polyline points="14 2 14 8 20 8" /></svg>,+}++const outlineBtnCls = 'inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-lg border border-accent/40 text-accent-light text-xs font-medium hover:bg-accent/10 hover:border-accent/60 transition-colors disabled:opacity-50'+const ghostBtnCls = 'px-3.5 py-1.5 rounded-lg border border-zinc-700 text-zinc-300 text-xs font-medium hover:text-white hover:border-zinc-500 transition-colors'++// ─── Component ────────────────────────────────────────────────────────────────++export function ModelLibraryModal({ onClose }: { onClose: () => void }): JSX.Element {+ const apiUrl = useAppStore((s) => s.apiUrl)+ const localModel = useAgentStore((s) => s.localModel)+ const setLocalModel = useAgentStore((s) => s.setLocalModel)++ const [status, setStatus] = useState<LlmStatus | null>(null)+ const [adding, setAdding] = useState(false)+ const [error, setError] = useState<string | null>(null)+ const [query, setQuery] = useState('')+ const [filter, setFilter] = useState<Filter>('all')++ // The model list comes from the shared catalog store, so a download or delete+ // here immediately updates every other picker (chat, extension params,+ // chat) and vice-versa — no independent per-surface fetch.+ const { models, refresh: refreshModels } = useLlmModels()++ // Downloads live in a module-level store (src/shared/services/llmDownloads.ts)+ // so they keep running — and stay visible on reopen — after this modal closes.+ const downloads = useLlmDownloadsStore((s) => s.downloads)+ const downloadError = useLlmDownloadsStore((s) => s.error)+ const startDownload = useLlmDownloadsStore((s) => s.start)+ const pauseDownload = useLlmDownloadsStore((s) => s.pause)+ const cancelDownload = useLlmDownloadsStore((s) => s.cancel)+ const dismissDownloadError = useLlmDownloadsStore((s) => s.dismissError)++ // Aborts every in-flight fetch (status/model list + any SSE stream) when the+ // modal unmounts, so closing it mid-download doesn't leak a fetch or call+ // setState on a component that's gone.+ const aliveRef = useRef(true)+ const abortControllersRef = useRef(new Set<AbortController>())+ const dialogRef = useRef<HTMLDivElement>(null)++ function withAbort<T>(run: (signal: AbortSignal) => Promise<T>): Promise<T> {+ const controller = new AbortController()+ abortControllersRef.current.add(controller)+ return run(controller.signal).finally(() => { abortControllersRef.current.delete(controller) })+ }++ useEffect(() => {+ aliveRef.current = true+ const controllers = abortControllersRef.current+ return () => {+ aliveRef.current = false+ for (const controller of controllers) controller.abort()+ controllers.clear()+ }+ }, [])++ // Escape closes the modal; Tab is trapped inside it while it's open.+ useEffect(() => {+ function onKeyDown(e: KeyboardEvent) {+ if (e.key === 'Escape') { onClose(); return }+ if (e.key !== 'Tab' || !dialogRef.current) return+ const focusable = dialogRef.current.querySelectorAll<HTMLElement>(+ 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',+ )+ if (focusable.length === 0) return+ const first = focusable[0]+ const last = focusable[focusable.length - 1]+ if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus() }+ else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus() }+ }+ document.addEventListener('keydown', onKeyDown)+ dialogRef.current?.focus()+ return () => document.removeEventListener('keydown', onKeyDown)+ }, [onClose])++ const refresh = useCallback(async () => {+ void refreshModels() // shared model catalog (propagates to every picker)+ try {+ const s = await withAbort((signal) =>+ fetch(`${apiUrl}/llm/status`, { signal }).then((r) => r.json()),+ )+ if (!aliveRef.current) return+ setStatus(s)+ } catch {+ if (!aliveRef.current) return+ setStatus(null)+ }+ }, [apiUrl, refreshModels])++ // Once, on open (and if the API URL changes) — `refresh` is stable, see+ // useLlmModels. It used to be rebuilt on every render, so this effect re-ran+ // on every render and each pass forced another /llm/models + /llm/status.+ useEffect(() => { void refresh() }, [refresh])++ async function handleAdd() {+ setAdding(true)+ setError(null)+ try {+ const res = await window.electron.agent.addModel()+ if (!aliveRef.current) return+ if (res.error) setError(res.error)+ if (res.success) void refresh()+ } finally {+ if (aliveRef.current) setAdding(false)+ }+ }++ async function handleDelete(id: string) {+ await fetch(`${apiUrl}/llm/models/${encodeURIComponent(id)}`, { method: 'DELETE' }).catch(() => {})+ void refresh()+ }++ // Downloads run in the shared store, possibly finishing while this modal is+ // closed — refresh the model list whenever one drops out (done/error/cancelled)+ // while we're mounted, so "downloaded" flips without waiting for a remount.+ const prevDownloadIdsRef = useRef<Set<string>>(new Set())+ useEffect(() => {+ const prev = prevDownloadIdsRef.current+ const current = new Set(Object.keys(downloads).filter((id) => downloads[id] !== undefined))+ let finished = false+ for (const id of prev) if (!current.has(id)) finished = true+ prevDownloadIdsRef.current = current+ if (finished) void refresh()+ }, [downloads, refresh])++ // VRAM is only known on NVIDIA (nvidia-smi); without it there is no fit verdict+ // to show or filter on.+ const vramGb = status?.vram_gb ?? null++ const filterOptions: { value: Filter; label: string }[] = [+ { value: 'all', label: 'All' },+ ...(vramGb ? [{ value: 'fits' as const, label: 'Fits my GPU' }] : []),+ { value: 'vision', label: 'Vision' },+ { value: 'cad', label: 'CAD' },+ ]++ const q = query.trim().toLowerCase()+ const matches = (m: LlmModel): boolean => {+ const tags = m.tags ?? []+ if (filter === 'vision' && !tags.includes('vision')) return false+ if (filter === 'cad' && !tags.includes('cad')) return false+ if (filter === 'fits') {+ const fit = vramFit(m.vram_estimate_mb, vramGb)+ if (!fit || fit.label === "Won't fit") return false+ }+ return !q || m.name.toLowerCase().includes(q) || (m.description ?? '').toLowerCase().includes(q)+ }++ const installed = models.filter((m) => m.downloaded && matches(m))+ const suggested = models.filter((m) => !m.downloaded && matches(m))+ const filtering = filter !== 'all' || q !== ''++ function renderCard(m: LlmModel): JSX.Element {+ const dl = downloads[m.id]+ const tags = m.tags ?? []+ const inUse = m.downloaded && localModel === m.id+ // Code/CAD models are tools for workflow nodes, not chat models: the chat's+ // own picker leaves them out, so they cannot become the agent's model here.+ const nodeOnly = tags.some((t) => t === 'code' || t === 'cad')+ const fit = vramFit(m.vram_estimate_mb, vramGb)+ // Size and VRAM say nothing about how well a model drives the agent — a 4B+ // outscores a 20B here. The tooltip keeps a measured rate and an estimate+ // visibly apart.+ const grade = agentGrade(m)++ return (+ <div+ key={m.id}+ className={`rounded-xl border bg-surface-300 px-4 py-3.5 flex flex-col gap-2.5 transition-colors ${+ inUse ? 'border-accent/50' : 'border-zinc-800 hover:border-zinc-700'+ }`}+ >+ <div className="flex items-start justify-between gap-3">+ <p className="text-[13px] font-semibold text-zinc-100 leading-snug break-words">{m.name}</p>+ {inUse && (+ <Tag tone="accent" icon={<span className="w-1.5 h-1.5 rounded-full bg-accent-light" />}>In use</Tag>+ )}+ </div>++ <div className="flex flex-wrap gap-1">+ {tags.includes('default') && <Tag tone="outline" icon={ICONS.star}>Recommended</Tag>}+ {fit && <Tag colors={fit.className} icon={fit.label === 'Fits' ? ICONS.check : ICONS.warn}>{fit.label}</Tag>}+ {tags.includes('vision') && <Tag tone="muted" icon={ICONS.eye}>Vision</Tag>}+ {tags.includes('cad') && <Tag tone="muted" icon={ICONS.cube}>CAD</Tag>}+ {m.source === 'custom' && <Tag tone="muted" icon={ICONS.file}>Custom</Tag>}+ {grade && <Tag tone="muted" title={grade.title}>{grade.label}</Tag>}+ </div>++ {m.description && (+ <p className="text-[11px] text-zinc-400 leading-relaxed line-clamp-3" title={m.description}>{m.description}</p>+ )}++ <div className="mt-auto pt-1 flex items-center justify-between gap-2 text-[10px] font-mono text-zinc-500">+ <span className="truncate">{[m.size_bytes ? formatBytes(m.size_bytes) : null, m.quant].filter(Boolean).join(' · ')}</span>+ {m.vram_estimate_mb ? (+ <span className="shrink-0">+ ~{(m.vram_estimate_mb / 1024).toFixed(1)}{vramGb ? ` / ${vramGb}` : ''} GB VRAM+ </span>+ ) : null}+ </div>++ {dl && <SseProgressBar event={dl} />}++ <div className="flex items-center gap-2 pt-0.5">+ {m.downloaded ? (+ <>+ {inUse ? (+ <span className="text-[11px] text-zinc-500">Used by the chat agent</span>+ ) : nodeOnly ? (+ <span className="text-[11px] text-zinc-500">For workflow nodes, not the chat</span>+ ) : (+ <button onClick={() => setLocalModel(m.id)} className={outlineBtnCls}>Select</button>+ )}+ <button+ onClick={() => handleDelete(m.id)}+ title="Delete model file"+ aria-label={`Delete ${m.name}`}+ className="ml-auto p-1.5 rounded-lg text-zinc-600 hover:text-red-400 hover:bg-red-950/40 transition-colors"+ >+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <polyline points="3 6 5 6 21 6" /><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />+ </svg>+ </button>+ </>+ ) : dl ? (+ <>+ {dl.paused ? (+ <button onClick={() => startDownload(m.id)} className={ghostBtnCls}>Resume</button>+ ) : (+ <button onClick={() => void pauseDownload(m.id)} className={ghostBtnCls}>Pause</button>+ )}+ <button onClick={() => void cancelDownload(m.id)} className={`${ghostBtnCls} hover:!text-red-400`}>Cancel</button>+ </>+ ) : (+ <button onClick={() => startDownload(m.id)} className={outlineBtnCls}>+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="7 10 12 15 17 10" /><line x1="12" y1="15" x2="12" y2="3" />+ </svg>+ Download+ </button>+ )}+ </div>+ </div>+ )+ }++ return createPortal(+ <div+ className="fixed inset-0 z-[9999] flex items-center justify-center"+ onMouseDown={(e) => { if (e.target === e.currentTarget) onClose() }}+ >+ <div className="absolute inset-0 bg-zinc-950/70 backdrop-blur-sm animate-fade-in" />++ <div+ ref={dialogRef}+ role="dialog"+ aria-modal="true"+ aria-label="Models"+ tabIndex={-1}+ className="relative w-[1000px] max-w-[94vw] max-h-[88vh] rounded-2xl bg-zinc-900 border border-zinc-700/60 shadow-[0_30px_60px_rgba(0,0,0,0.5)] overflow-hidden animate-slide-up-center flex flex-col focus:outline-none"+ >++ {/* Header */}+ <div className="px-5 pt-5 pb-4 border-b border-zinc-800/80 shrink-0 flex flex-col gap-4">+ <div className="flex items-start justify-between gap-4">+ <div>+ <h2 className="text-lg font-semibold text-zinc-100 leading-tight">Models</h2>+ <p className="text-xs text-zinc-500 mt-0.5">+ Local models shared by the whole app — chat agent and extensions.+ </p>+ </div>+ <div className="flex items-center gap-2 shrink-0">+ {vramGb != null && (+ // self-stretch: as tall as the Add button beside it, whatever its padding.+ <span className="self-stretch inline-flex items-center gap-1.5 px-2.5 rounded-md bg-zinc-800 border border-zinc-700 text-[11px] font-medium text-zinc-300">+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-500">+ <rect x="2" y="6" width="20" height="12" rx="2" /><line x1="6" y1="10" x2="6" y2="14" /><line x1="10" y1="10" x2="10" y2="14" /><line x1="14" y1="10" x2="14" y2="14" />+ </svg>+ {vramGb} GB VRAM+ </span>+ )}+ <button+ onClick={() => void handleAdd()}+ disabled={adding}+ className="px-3.5 py-1.5 rounded-lg bg-accent hover:bg-accent-dark text-white text-[12px] font-medium transition-colors disabled:opacity-50"+ >+ {adding ? 'Adding…' : 'Add'}+ </button>+ <button onClick={onClose} aria-label="Close" className="ml-1 p-1.5 rounded-lg text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800 transition-colors">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">+ <line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />+ </svg>+ </button>+ </div>+ </div>++ <div className="flex items-center gap-3 flex-wrap">+ <div className="relative w-80 max-w-full">+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500 pointer-events-none">+ <circle cx="11" cy="11" r="7" /><line x1="21" y1="21" x2="16.65" y2="16.65" />+ </svg>+ <input+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Search models"+ className="w-full bg-zinc-800 border border-zinc-700 text-zinc-200 text-xs rounded-lg pl-8 pr-3 py-2 placeholder:text-zinc-500 focus:outline-none focus:border-accent/50"+ />+ </div>+ <SegmentedControl value={filter} onChange={setFilter} options={filterOptions} ariaLabel="Filter models" />+ </div>++ {status === null && (+ <p className="text-[11px] text-zinc-500 flex items-center gap-2">+ Cannot reach the Modly API.+ {/* The library does not poll, so a backend that was still starting+ * up needs a way back in short of reopening the modal. */}+ <button onClick={() => { void refresh() }} className="text-accent-light hover:underline underline-offset-2">+ Retry+ </button>+ </p>+ )}+ {(error || downloadError) && (+ <p className="text-[11px] text-red-400 flex items-center gap-2">+ <span className="flex-1">{error || downloadError}</span>+ <button+ onClick={() => { setError(null); dismissDownloadError() }}+ className="shrink-0 text-zinc-500 hover:text-zinc-300 transition-colors"+ >+ Dismiss+ </button>+ </p>+ )}+ </div>++ {/* Installed first, then the catalog's suggestions not yet downloaded */}+ <div className="px-5 py-4 overflow-y-auto flex flex-col gap-6">+ {([+ {+ title: 'Installed',+ items: installed,+ empty: filtering ? 'No installed model matches.' : 'No model installed yet — add a .gguf file or download a suggestion below.',+ },+ {+ title: 'Suggested',+ items: suggested,+ empty: filtering ? 'No suggested model matches.' : 'Every suggested model is installed.',+ },+ ]).map((section) => (+ <div key={section.title} className="flex flex-col gap-3">+ <h3 className="text-[10.5px] font-semibold uppercase tracking-widest text-zinc-500">+ {section.title}+ <span className="ml-2 text-zinc-700">{section.items.length}</span>+ </h3>+ {section.items.length > 0 ? (+ <div className="grid grid-cols-[repeat(auto-fill,minmax(270px,1fr))] gap-3">+ {section.items.map(renderCard)}+ </div>+ ) : (+ <p className="text-[11px] text-zinc-600">{section.empty}</p>+ )}+ </div>+ ))}+ </div>+ </div>+ </div>,+ document.body,+ )+}diff --git a/apps/forge-desktop/src/shared/components/ui/NumberInput.tsx b/apps/forge-desktop/src/shared/components/ui/NumberInput.tsxnew file mode 100644index 000000000..3630c6394--- /dev/null+++ b/apps/forge-desktop/src/shared/components/ui/NumberInput.tsx@@ -0,0 +1,99 @@+import { useRef, useState } from 'react'++/**+ * Text-based numeric inputs for extension params. They keep the raw text the+ * user is typing (so "-", "0." or "1," don't get swallowed) and only emit once+ * it parses. External value changes (e.g. reset) re-sync the text.+ */++export function IntInput({ value, onChange, className }: { value: number; onChange: (v: number) => void; className: string }) {+ const [text, setText] = useState(String(value))+ const prevValue = useRef(value)+ if (prevValue.current !== value && parseInt(text, 10) !== value) {+ prevValue.current = value+ setText(String(value))+ }+ return (+ <input+ type="text"+ inputMode="numeric"+ value={text}+ onChange={(e) => {+ const raw = e.target.value+ if (raw !== '' && raw !== '-' && !/^-?\d+$/.test(raw)) return+ setText(raw)+ const n = parseInt(raw, 10)+ if (!isNaN(n)) { prevValue.current = n; onChange(n) }+ }}+ className={className}+ />+ )+}++/**+ * Float input. When the param declares both `min` and `max`, a range slider is+ * shown next to the text field; typed values are clamped to those bounds.+ */+export function FloatInput({ value, onChange, className, min, max, step, label }: {+ value: number+ onChange: (v: number) => void+ className: string+ min?: number+ max?: number+ step?: number+ label: string+}) {+ const [text, setText] = useState(String(value))+ const prevValue = useRef(value)+ if (prevValue.current !== value && parseFloat(text.replace(',', '.')) !== value) {+ prevValue.current = value+ setText(String(value))+ }++ const clamp = (n: number) => Math.min(max ?? Infinity, Math.max(min ?? -Infinity, n))+ const emit = (n: number) => {+ const clamped = clamp(n)+ prevValue.current = clamped+ onChange(clamped)+ }++ const textInput = (+ <input+ type="text"+ inputMode="decimal"+ value={text}+ onChange={(e) => {+ const raw = e.target.value.replace(',', '.')+ if (raw !== '' && raw !== '-' && raw !== '.' && !/^-?\d*\.?\d*$/.test(raw)) return+ setText(e.target.value)+ const num = parseFloat(raw)+ if (!isNaN(num)) emit(num)+ }}+ // Show the clamped value once the user is done typing an out-of-range one.+ onBlur={() => { if (parseFloat(text.replace(',', '.')) !== value) setText(String(value)) }}+ className={className}+ />+ )++ if (min === undefined || max === undefined || max <= min) return textInput++ return (+ <div className="flex items-center gap-1.5 w-full">+ <input+ type="range"+ min={min}+ max={max}+ step={step && step > 0 ? step : (max - min) / 100}+ value={Number.isFinite(value) ? clamp(value) : min}+ onChange={(e) => {+ const num = e.currentTarget.valueAsNumber+ if (Number.isFinite(num)) { setText(String(num)); emit(num) }+ }}+ aria-label={label}+ // nodrag: inside a React Flow node, dragging the thumb would move the node.+ className="nodrag min-w-0 flex-1 accent-accent cursor-pointer"+ />+ <div className="w-16 shrink-0">{textInput}</div>+ </div>+ )+}diff --git a/apps/forge-desktop/src/shared/components/ui/PickerIcon.tsx b/apps/forge-desktop/src/shared/components/ui/PickerIcon.tsxnew file mode 100644index 000000000..8893c3a07--- /dev/null+++ b/apps/forge-desktop/src/shared/components/ui/PickerIcon.tsx@@ -0,0 +1,38 @@+import type { PickerIntent } from '@shared/types/electron.d'++/**+ * Glyph for a param's browse button, matching the dialog it opens so the button+ * advertises what it does (folder = the historical default).+ */+export function PickerIcon({ intent, size = 11 }: { intent: PickerIntent; size?: number }): JSX.Element {+ const common = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2 }++ if (intent === 'image') {+ return (+ <svg {...common}>+ <rect x="3" y="3" width="18" height="18" rx="2"/>+ <circle cx="8.5" cy="8.5" r="1.5"/>+ <polyline points="21 15 16 10 5 21"/>+ </svg>+ )+ }+ if (intent === 'mesh') {+ return (+ <svg {...common}>+ <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/>+ </svg>+ )+ }+ if (intent === 'text') {+ return (+ <svg {...common}>+ <path d="M17 6.1H3M21 12.1H3M15.1 18H3"/>+ </svg>+ )+ }+ return (+ <svg {...common}>+ <path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>+ </svg>+ )+}diff --git a/apps/forge-desktop/src/shared/components/ui/SseProgressBar.tsx b/apps/forge-desktop/src/shared/components/ui/SseProgressBar.tsxnew file mode 100644index 000000000..60f8596b8--- /dev/null+++ b/apps/forge-desktop/src/shared/components/ui/SseProgressBar.tsx@@ -0,0 +1,21 @@+import type { SseEvent } from '@shared/services/llmDownloads'+import { formatBytes } from '@shared/utils/format'++/** Progress of an SSE-driven download or install (engine, GGUF models). */+export function SseProgressBar({ event }: { event: SseEvent }): JSX.Element {+ return (+ <div className="flex flex-col gap-1">+ <div className="flex items-center justify-between text-[10px] text-zinc-500">+ <span className="truncate">{event.status}</span>+ <span className="shrink-0">+ {event.totalBytes+ ? `${formatBytes(event.bytesDownloaded ?? 0)} / ${formatBytes(event.totalBytes)}`+ : `${event.percent ?? 0}%`}+ </span>+ </div>+ <div className="h-1 bg-zinc-800 rounded-full overflow-hidden">+ <div className="h-full bg-accent rounded-full transition-all" style={{ width: `${event.percent ?? 0}%` }} />+ </div>+ </div>+ )+}diff --git a/apps/forge-desktop/src/shared/components/ui/Toast.tsx b/apps/forge-desktop/src/shared/components/ui/Toast.tsxnew file mode 100644index 000000000..5a40f5b68--- /dev/null+++ b/apps/forge-desktop/src/shared/components/ui/Toast.tsx@@ -0,0 +1,45 @@+import { useEffect } from 'react'+import { useAppStore } from '@shared/stores/appStore'++export function Toast(): JSX.Element | null {+ const { toast, hideToast } = useAppStore()++ useEffect(() => {+ if (!toast) return+ const timer = window.setTimeout(() => hideToast(), toast.durationMs ?? 2800)+ return () => window.clearTimeout(timer)+ // eslint-disable-next-line react-hooks/exhaustive-deps -- key off id/duration, not the toast object identity+ }, [toast?.id, toast?.durationMs, hideToast])++ if (!toast) return null++ return (+ <div className="fixed right-4 bottom-4 z-50 pointer-events-none">+ <div className="pointer-events-auto max-w-sm rounded-xl border border-amber-500/30 bg-zinc-900/96 shadow-2xl backdrop-blur-sm">+ <div className="flex items-start gap-3 px-4 py-3">+ <div className="mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-amber-500/30 bg-amber-500/12">+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-amber-300">+ <path d="M10.29 3.86 1.82 18A2 2 0 0 0 3.53 21h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z" />+ <line x1="12" y1="9" x2="12" y2="13" />+ <line x1="12" y1="17" x2="12.01" y2="17" />+ </svg>+ </div>+ <div className="min-w-0 flex-1">+ <p className="text-[11px] font-semibold uppercase tracking-[0.12em] text-amber-200/80">Workflow Check</p>+ <p className="mt-1 text-sm leading-5 text-zinc-100">{toast.message}</p>+ </div>+ <button+ onClick={hideToast}+ className="shrink-0 rounded-md p-1 text-zinc-500 transition-colors hover:bg-zinc-800 hover:text-zinc-200"+ aria-label="Dismiss notification"+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <line x1="18" y1="6" x2="6" y2="18" />+ <line x1="6" y1="6" x2="18" y2="18" />+ </svg>+ </button>+ </div>+ </div>+ </div>+ )+}diff --git a/apps/forge-desktop/src/shared/components/ui/Tooltip.tsx b/apps/forge-desktop/src/shared/components/ui/Tooltip.tsxnew file mode 100644index 000000000..53eafd2d0--- /dev/null+++ b/apps/forge-desktop/src/shared/components/ui/Tooltip.tsx@@ -0,0 +1,52 @@+import { useRef, useState } from 'react'+import { createPortal } from 'react-dom'++interface TooltipProps {+ content: string+ children: React.ReactNode+}++export function Tooltip({ content, children }: TooltipProps): JSX.Element {+ const [visible, setVisible] = useState(false)+ const [coords, setCoords] = useState({ x: 0, y: 0 })+ const triggerRef = useRef<HTMLSpanElement>(null)++ const show = () => {+ if (!triggerRef.current) return+ const rect = triggerRef.current.getBoundingClientRect()+ setCoords({+ x: rect.right + 10,+ y: rect.top + rect.height / 2,+ })+ setVisible(true)+ }++ return (+ <>+ <span+ ref={triggerRef}+ onMouseEnter={show}+ onMouseLeave={() => setVisible(false)}+ className="inline-flex"+ >+ {children}+ </span>++ {visible &&+ createPortal(+ <div+ className="fixed z-[9999] pointer-events-none"+ style={{ left: coords.x, top: coords.y, transform: 'translateY(-50%)' }}+ >+ <div className="relative max-w-[220px] px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700/80 shadow-xl">+ {/* Arrow */}+ <div className="absolute right-full top-1/2 -translate-y-1/2 border-[5px] border-transparent border-r-zinc-700/80" />+ <div className="absolute right-full top-1/2 -translate-y-1/2 translate-x-px border-[5px] border-transparent border-r-zinc-900" />+ <p className="text-xs text-zinc-300 leading-relaxed whitespace-normal">{content}</p>+ </div>+ </div>,+ document.body+ )}+ </>+ )+}diff --git a/apps/forge-desktop/src/shared/components/ui/UpdateModal.tsx b/apps/forge-desktop/src/shared/components/ui/UpdateModal.tsxnew file mode 100644index 000000000..3aa7dd67f--- /dev/null+++ b/apps/forge-desktop/src/shared/components/ui/UpdateModal.tsx@@ -0,0 +1,91 @@+import { createPortal } from 'react-dom'+import logo from '../../../../resources/icons/icon.png'++interface UpdateModalProps {+ currentVersion: string+ latestVersion: string+ onDismiss: () => void+}++export function UpdateModal({ currentVersion, latestVersion, onDismiss }: UpdateModalProps): JSX.Element {+ const handleDownload = (): void => {+ window.open('https://github.com/lightningpixel/modly/releases', '_blank')+ }++ return createPortal(+ <div+ className="fixed inset-0 z-[9999] flex items-center justify-center"+ onMouseDown={(e) => { if (e.target === e.currentTarget) onDismiss() }}+ >+ <div className="absolute inset-0 bg-zinc-950/70 backdrop-blur-sm animate-fade-in" />++ <div className="relative w-[440px] rounded-2xl bg-zinc-900 border border-accent/20 shadow-2xl shadow-accent/10 overflow-hidden animate-slide-up-center">++ {/* Header band */}+ <div className="relative px-6 pt-6 pb-5 border-b border-zinc-800">+ <div className="absolute inset-0 bg-gradient-to-br from-accent/10 via-transparent to-transparent pointer-events-none" />++ <div className="relative flex items-center gap-4">+ <img src={logo} alt="Modly" className="w-12 h-12 rounded-xl shrink-0" />+ <div>+ <h2 className="text-lg font-semibold text-zinc-100 leading-tight">New update available</h2>+ <p className="text-sm text-zinc-500 mt-0.5">A new version of Modly is ready to download.</p>+ </div>+ </div>+ </div>++ {/* Version info */}+ <div className="px-6 py-5 flex flex-col gap-4">++ <div className="flex items-center gap-3 p-4 rounded-xl bg-zinc-800/60 border border-zinc-700/50">+ <div className="flex-1 flex flex-col items-center gap-1">+ <span className="text-[11px] uppercase tracking-widest text-zinc-500 font-medium">Current</span>+ <span className="text-base font-mono font-semibold text-zinc-400">+ {currentVersion ? `v${currentVersion}` : '—'}+ </span>+ </div>++ <div className="text-zinc-600">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <line x1="5" y1="12" x2="19" y2="12" />+ <polyline points="12 5 19 12 12 19" />+ </svg>+ </div>++ <div className="flex-1 flex flex-col items-center gap-1">+ <span className="text-[11px] uppercase tracking-widest text-accent-light font-medium">Latest</span>+ <span className="text-base font-mono font-semibold text-zinc-100">{latestVersion}</span>+ </div>+ </div>++ <p className="text-xs text-zinc-500 leading-relaxed">+ Download the latest release from GitHub to get bug fixes, improvements, and new features.+ </p>++ {/* Actions */}+ <div className="flex gap-3 pt-1">+ <button+ onClick={onDismiss}+ className="flex-1 py-3 rounded-xl bg-zinc-800 hover:bg-zinc-700/80 text-zinc-400 hover:text-zinc-200 text-sm font-medium transition-colors border border-zinc-700/50"+ >+ Later+ </button>+ <button+ onClick={handleDownload}+ className="flex-1 py-3 rounded-xl bg-accent hover:bg-accent-dark text-white text-sm font-semibold transition-colors shadow-lg shadow-accent/20 flex items-center justify-center gap-2"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />+ <polyline points="7 10 12 15 17 10" />+ <line x1="12" y1="15" x2="12" y2="3" />+ </svg>+ Download+ </button>+ </div>++ </div>+ </div>+ </div>,+ document.body+ )+}diff --git a/apps/forge-desktop/src/shared/components/ui/agentGrade.test.mjs b/apps/forge-desktop/src/shared/components/ui/agentGrade.test.mjsnew file mode 100644index 000000000..3ee1aee42--- /dev/null+++ b/apps/forge-desktop/src/shared/components/ui/agentGrade.test.mjs@@ -0,0 +1,53 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++// Same bundling trick as vramFit.test.mjs — a pure helper, no React deps.+function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-agentgrade-test-')), 'agentGrade.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('src/shared/components/ui/agentGrade.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++const { agentGrade } = loadModule()++test('a model without a tier gets no badge at all', () => {+ assert.equal(agentGrade(undefined), null)+ assert.equal(agentGrade({}), null)+ assert.equal(agentGrade({ agent_tier: 'brilliant' }), null) // unknown tier, not a badge+})++test('a measured model shows its own score', () => {+ const g = agentGrade({ agent_tier: 'excellent', agent_score: 0.98, agent_source: 'measured' })+ assert.equal(g.label, 'Agent: excellent (98%)')+ assert.match(g.title, /Modly's tool-calling suite/)+})++test('an unmeasured model never borrows the credibility of a measurement', () => {+ const g = agentGrade({ agent_tier: 'solid', agent_score: 0.9, agent_source: 'estimate' })+ assert.equal(g.label, 'Agent: solid') // no percentage+ assert.match(g.title, /not measured in Modly/)+})++test('the note is carried into the tooltip', () => {+ const g = agentGrade({ agent_tier: 'limited', agent_source: 'estimate', agent_note: 'older generation' })+ assert.match(g.title, /older generation/)+ assert.equal(g.label, 'Agent: limited')+})++test('each tier gets its own colour', () => {+ const classes = ['excellent', 'solid', 'limited'].map((t) => agentGrade({ agent_tier: t }).className)+ assert.equal(new Set(classes).size, 3)+})diff --git a/apps/forge-desktop/src/shared/components/ui/agentGrade.ts b/apps/forge-desktop/src/shared/components/ui/agentGrade.tsnew file mode 100644index 000000000..874b103da--- /dev/null+++ b/apps/forge-desktop/src/shared/components/ui/agentGrade.ts@@ -0,0 +1,44 @@+/**+ * How well a model drives the agent — the one thing the model list never said.+ *+ * Size and VRAM are already shown, and both are poor proxies: a 4B tops the+ * tool-calling tests while a 20B sits below it. `agent_tier` comes from the+ * catalog; when Modly's own eval suite has been run against the model, the+ * measured pass rate is shown with it, and everything else is flagged as an+ * estimate so the two are never confused.+ */++export type AgentTier = 'excellent' | 'solid' | 'limited'++export interface AgentGradeInput {+ agent_tier?: string | null+ agent_score?: number | null // 0..1, Modly's eval suite+ agent_note?: string | null+ agent_source?: string | null // 'measured' | 'estimate'+}++export interface AgentGrade {+ label: string+ className: string+ title: string+}++const TIERS: Record<AgentTier, { label: string; className: string }> = {+ excellent: { label: 'Agent: excellent', className: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-400' },+ solid: { label: 'Agent: solid', className: 'border-amber-500/30 bg-amber-500/10 text-amber-400' },+ limited: { label: 'Agent: limited', className: 'border-zinc-600/40 bg-zinc-600/10 text-zinc-400' },+}++export function agentGrade(m: AgentGradeInput | null | undefined): AgentGrade | null {+ const tier = m?.agent_tier as AgentTier | undefined+ if (!tier || !(tier in TIERS)) return null+ const { label, className } = TIERS[tier]++ const measured = m?.agent_source === 'measured' && typeof m?.agent_score === 'number'+ const score = measured ? `${Math.round((m!.agent_score as number) * 100)}% on Modly's tool-calling suite` : null+ const title = [score ?? 'Estimated from published benchmarks — not measured in Modly', m?.agent_note]+ .filter(Boolean)+ .join(' · ')++ return { label: measured ? `${label} (${Math.round((m!.agent_score as number) * 100)}%)` : label, className, title }+}diff --git a/apps/forge-desktop/src/shared/components/ui/index.ts b/apps/forge-desktop/src/shared/components/ui/index.tsnew file mode 100644index 000000000..7c3a11478--- /dev/null+++ b/apps/forge-desktop/src/shared/components/ui/index.ts@@ -0,0 +1,7 @@+export { Tooltip } from './Tooltip'+export { FieldLabel } from './FieldLabel'+export { ConfirmModal } from './ConfirmModal'+export { ColorPicker } from './ColorPicker'+export { PickerIcon } from './PickerIcon'+export { Toast } from './Toast'+export { IntInput, FloatInput } from './NumberInput'diff --git a/apps/forge-desktop/src/shared/components/ui/vramFit.test.mjs b/apps/forge-desktop/src/shared/components/ui/vramFit.test.mjsnew file mode 100644index 000000000..551fd69d2--- /dev/null+++ b/apps/forge-desktop/src/shared/components/ui/vramFit.test.mjs@@ -0,0 +1,48 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++// Bundle the pure vramFit helper (no React deps) into CJS — same approach as+// autoWire.test.mjs / preflight.test.mjs.+function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-vramfit-test-')), 'vramFit.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('src/shared/components/ui/vramFit.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++const { vramFit } = loadModule()++test('returns null when the estimate or VRAM is unknown', () => {+ assert.equal(vramFit(undefined, 12), null)+ assert.equal(vramFit(4200, undefined), null)+ assert.equal(vramFit(4200, null), null)+ assert.equal(vramFit(0, 12), null)+})++test('"Fits" when the model sits at or under 90% of VRAM', () => {+ // 12 GB → 12288 MB; 90% = 11059 MB+ assert.equal(vramFit(4200, 12).label, 'Fits')+ assert.equal(vramFit(11059, 12).label, 'Fits')+})++test('"Tight" between 90% and 100% of VRAM', () => {+ assert.equal(vramFit(11060, 12).label, 'Tight')+ assert.equal(vramFit(12288, 12).label, 'Tight')+})++test('"Won\'t fit" above 100% of VRAM', () => {+ assert.equal(vramFit(13500, 12).label, "Won't fit")+ assert.equal(vramFit(12289, 12).label, "Won't fit")+})diff --git a/apps/forge-desktop/src/shared/components/ui/vramFit.ts b/apps/forge-desktop/src/shared/components/ui/vramFit.tsnew file mode 100644index 000000000..1f5c9bc07--- /dev/null+++ b/apps/forge-desktop/src/shared/components/ui/vramFit.ts@@ -0,0 +1,20 @@+/**+ * "Does this model fit in VRAM?" verdict, computed from the model's estimated+ * footprint against the detected VRAM. Only meaningful on GPUs we can measure+ * (NVIDIA via nvidia-smi); returns null otherwise so no misleading badge shows+ * on Vulkan/CPU where `vramGb` is unknown.+ */+export interface VramFit {+ label: string+ className: string+}++export function vramFit(estimateMb?: number, vramGb?: number | null): VramFit | null {+ if (!estimateMb || !vramGb) return null+ const vramMb = vramGb * 1024+ if (estimateMb <= vramMb * 0.9)+ return { label: 'Fits', className: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-400' }+ if (estimateMb <= vramMb)+ return { label: 'Tight', className: 'border-amber-500/30 bg-amber-500/10 text-amber-400' }+ return { label: "Won't fit", className: 'border-red-500/30 bg-red-500/10 text-red-400' }+}diff --git a/apps/forge-desktop/src/shared/hooks/useApi.test.mjs b/apps/forge-desktop/src/shared/hooks/useApi.test.mjsnew file mode 100644index 000000000..45afc06c5--- /dev/null+++ b/apps/forge-desktop/src/shared/hooks/useApi.test.mjs@@ -0,0 +1,134 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++// Bundle useApi.ts with stubbed dependencies:+// - axios → records requests and returns canned responses+// - appStore → useAppStore returns a fixed apiUrl (no React runtime)+// The stub modules communicate with the test through globalThis.+function loadUseApi() {+ const dir = mkdtempSync(join(tmpdir(), 'modly-useapi-test-'))++ const axiosStub = join(dir, 'axios-stub.mjs')+ writeFileSync(axiosStub, `+ function record(base, method, url, body) {+ const full = (base ?? '') + url+ globalThis.__calls.push({ method, url: full, body })+ const r = globalThis.__responses[full]+ return Promise.resolve({ data: r ?? {} })+ }+ export default {+ create: (cfg) => ({+ get: (url) => record(cfg?.baseURL, 'get', url),+ post: (url, body) => record(cfg?.baseURL, 'post', url, body),+ }),+ }+ `, 'utf8')++ const storeStub = join(dir, 'store-stub.mjs')+ writeFileSync(storeStub, `+ export const useAppStore = (sel) => sel({ apiUrl: 'http://test.local' })+ export const GenerationOptions = {}+ `, 'utf8')++ const outfile = join(dir, 'useApi.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('src/shared/hooks/useApi.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ alias: {+ axios: axiosStub,+ '@shared/stores/appStore': storeStub,+ },+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile).useApi+}++function reset() {+ globalThis.__calls = []+ globalThis.__responses = {}+}++// ─── Tests ───────────────────────────────────────────────────────────────────++test('exposes every method consumed by the app (regression: getAllModelsStatus)', () => {+ reset()+ const api = loadUseApi()()+ for (const name of [+ 'generateFromImage', 'pollJobStatus', 'cancelJob', 'getModelStatus',+ 'getAllModelsStatus', 'downloadModel', 'optimizeMesh', 'smoothMesh', 'importMesh',+ ]) {+ assert.equal(typeof api[name], 'function', `useApi() must expose ${name}`)+ }+})++test('getAllModelsStatus hits /model/all and returns the payload', async () => {+ reset()+ globalThis.__responses['http://test.local/model/all'] = [{ id: 'm1', name: 'M1', downloaded: true }]+ const api = loadUseApi()()++ const result = await api.getAllModelsStatus()++ assert.deepEqual(globalThis.__calls, [{ method: 'get', url: 'http://test.local/model/all', body: undefined }])+ assert.deepEqual(result, [{ id: 'm1', name: 'M1', downloaded: true }])+})++test('pollJobStatus maps output_url → outputUrl', async () => {+ reset()+ globalThis.__responses['http://test.local/generate/status/job1'] = {+ status: 'done', progress: 100, output_url: '/workspace/out.glb',+ }+ const api = loadUseApi()()++ const result = await api.pollJobStatus('job1')++ assert.equal(result.status, 'done')+ assert.equal(result.outputUrl, '/workspace/out.glb')+})++test('optimizeMesh maps face_count → faceCount and posts target_faces', async () => {+ reset()+ globalThis.__responses['http://test.local/optimize/mesh'] = { url: '/o.glb', face_count: 5000 }+ const api = loadUseApi()()++ const result = await api.optimizeMesh('/in.glb', 5000)++ const call = globalThis.__calls[0]+ assert.equal(call.url, 'http://test.local/optimize/mesh')+ assert.deepEqual(call.body, { path: '/in.glb', target_faces: 5000 })+ assert.deepEqual(result, { url: '/o.glb', faceCount: 5000 })+})++test('cancelJob posts to the cancel endpoint and swallows errors', async () => {+ reset()+ const api = loadUseApi()()+ await api.cancelJob('job9')+ assert.equal(globalThis.__calls[0].url, 'http://test.local/generate/cancel/job9')+})++test('generateFromImage posts multipart and maps job_id → jobId', async () => {+ reset()+ globalThis.__responses['http://test.local/generate/from-image'] = { job_id: 'job42' }+ // generateFromImage builds a Blob/FormData from base64 image data.+ const api = loadUseApi()()++ const options = {+ modelId: 'model-x', remesh: 'none', enableTexture: false,+ textureResolution: 1024, modelParams: {},+ }+ const result = await api.generateFromImage('/img.png', options, btoa('fake-png-bytes'))++ const call = globalThis.__calls[0]+ assert.equal(call.url, 'http://test.local/generate/from-image')+ assert.ok(call.body instanceof FormData)+ assert.equal(call.body.get('model_id'), 'model-x')+ assert.equal(result.jobId, 'job42')+})diff --git a/apps/forge-desktop/src/shared/hooks/useApi.ts b/apps/forge-desktop/src/shared/hooks/useApi.tsnew file mode 100644index 000000000..f013f1c11--- /dev/null+++ b/apps/forge-desktop/src/shared/hooks/useApi.ts@@ -0,0 +1,133 @@+import axios from 'axios'+import { useAppStore, GenerationOptions } from '@shared/stores/appStore'++export function useApi() {+ const apiUrl = useAppStore((s) => s.apiUrl)++ const client = axios.create({ baseURL: apiUrl })++ async function generateFromImage(+ imagePath: string,+ options: GenerationOptions,+ imageData?: string,+ signal?: AbortSignal,+ ): Promise<{ jobId: string }> {+ // Use provided base64 (drag & drop) or read from disk via IPC+ const base64 = imageData ?? await window.electron.fs.readFileBase64(imagePath)+ const byteArray = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0))+ const blob = new Blob([byteArray], { type: 'image/png' })+ const filename = imagePath.split(/[\\/]/).pop() ?? 'image.png'++ const formData = new FormData()+ formData.append('image', blob, filename)+ formData.append('model_id', options.modelId)+ formData.append('remesh', options.remesh)+ formData.append('enable_texture', String(options.enableTexture))+ formData.append('texture_resolution', String(options.textureResolution))+ formData.append('params', JSON.stringify(options.modelParams))+ const { data } = await client.post<{ job_id: string }>('/generate/from-image', formData, {+ headers: { 'Content-Type': 'multipart/form-data' },+ signal,+ })++ return { jobId: data.job_id }+ }++ async function pollJobStatus(jobId: string): Promise<{+ status: 'pending' | 'running' | 'done' | 'error' | 'cancelled'+ progress: number+ step?: string+ outputUrl?: string+ error?: string+ }> {+ const { data } = await client.get(`/generate/status/${jobId}`)+ return { ...data, outputUrl: data.output_url }+ }++ async function getModelStatus(): Promise<{+ downloaded: boolean+ name: string+ size_gb: number+ progress?: number+ }> {+ const { data } = await client.get('/model/status')+ return data+ }++ async function getAllModelsStatus(): Promise<{ id: string; name: string; downloaded: boolean }[]> {+ const { data } = await client.get('/model/all')+ return data+ }++ async function downloadModel(+ onProgress?: (pct: number) => void+ ): Promise<void> {+ const response = await client.get('/model/download', {+ responseType: 'stream'+ })++ const reader = response.data+ reader.on('data', (chunk: Buffer) => {+ try {+ const line = chunk.toString().replace('data: ', '').trim()+ if (line) {+ const { progress } = JSON.parse(line)+ onProgress?.(progress)+ }+ } catch {+ // ignore parse errors+ }+ })++ await new Promise<void>((resolve, reject) => {+ reader.on('end', resolve)+ reader.on('error', reject)+ })+ }++ async function optimizeMesh(+ path: string,+ targetFaces: number,+ ): Promise<{ url: string; faceCount: number }> {+ const { data } = await client.post<{ url: string; face_count: number }>('/optimize/mesh', {+ path,+ target_faces: targetFaces,+ })+ return { url: data.url, faceCount: data.face_count }+ }++ async function cancelJob(jobId: string): Promise<void> {+ await client.post(`/generate/cancel/${jobId}`).catch(() => {})+ }++ async function smoothMesh(+ path: string,+ iterations: number,+ ): Promise<{ url: string }> {+ const { data } = await client.post<{ url: string }>('/optimize/smooth', {+ path,+ iterations,+ })+ return { url: data.url }+ }++ async function importMesh(filePath: string): Promise<{ url: string }> {+ const { data } = await client.post<{ url: string }>('/optimize/import-by-path', { path: filePath })+ return { url: data.url }+ }++ // Bakes a world-space 4x4 transform into the GLB geometry.+ // `matrix` is row-major (4 rows of 4), matching the backend's reshape.+ async function transformMesh(+ path: string,+ matrix: number[][],+ ): Promise<{ url: string }> {+ const { data } = await client.post<{ url: string }>('/optimize/transform', {+ path,+ matrix,+ })+ return { url: data.url }+ }++ return { generateFromImage, pollJobStatus, cancelJob, getModelStatus, getAllModelsStatus, downloadModel, optimizeMesh, smoothMesh, importMesh, transformMesh }+}diff --git a/apps/forge-desktop/src/shared/hooks/useGeneration.ts b/apps/forge-desktop/src/shared/hooks/useGeneration.tsnew file mode 100644index 000000000..6f3d3a375--- /dev/null+++ b/apps/forge-desktop/src/shared/hooks/useGeneration.ts@@ -0,0 +1,108 @@+import { useCallback, useRef } from 'react'+import { useAppStore } from '@shared/stores/appStore'+import { useApi } from './useApi'+import { showCompletionNotification, showErrorNotification } from '@shared/utils/notification'++export function useGeneration() {+ const { currentJob, setCurrentJob, updateCurrentJob, generationOptions, selectedImageData, pushMeshUrl, clearMeshHistory } = useAppStore()+ const { generateFromImage, pollJobStatus, cancelJob } = useApi()+ const cancelledRef = useRef(false)+ const abortControllerRef = useRef<AbortController | null>(null)++ const startGeneration = useCallback(+ async (imagePath: string) => {+ cancelledRef.current = false+ abortControllerRef.current = new AbortController()+ clearMeshHistory()+ const job = {+ id: crypto.randomUUID(),+ imageFile: imagePath,+ status: 'uploading' as const,+ progress: 0,+ createdAt: Date.now(),+ modelId: generationOptions.modelId,+ generationOptions,+ }+ setCurrentJob(job)++ try {+ const { jobId } = await generateFromImage(imagePath, generationOptions, selectedImageData ?? undefined, abortControllerRef.current.signal)++ if (cancelledRef.current) {+ await cancelJob(jobId)+ setCurrentJob(null)+ return+ }++ updateCurrentJob({ status: 'generating', progress: 0 })++ await pollUntilDone(jobId)+ } catch (err) {+ if (cancelledRef.current) {+ setCurrentJob(null)+ return+ }+ let errorMessage: string+ if (err && typeof err === 'object' && 'response' in err) {+ const axiosErr = err as { response?: { data?: { detail?: string } }; message: string }+ errorMessage = axiosErr.response?.data?.detail ?? axiosErr.message+ } else {+ errorMessage = err instanceof Error ? err.message : String(err)+ }+ updateCurrentJob({+ status: 'error',+ error: errorMessage+ })+ void showErrorNotification(errorMessage, 'Generation failed')+ }+ },+ // eslint-disable-next-line react-hooks/exhaustive-deps -- useApi re-creates its fns each render, so this re-memoizes anyway (values stay fresh)+ [generateFromImage, pollJobStatus, cancelJob, setCurrentJob, updateCurrentJob]+ )++ const pollUntilDone = async (jobId: string) => {+ while (true) {+ await new Promise((r) => setTimeout(r, 1000))++ if (cancelledRef.current) {+ await cancelJob(jobId)+ setCurrentJob(null)+ break+ }++ const result = await pollJobStatus(jobId)++ if (result.status === 'cancelled') {+ setCurrentJob(null)+ break+ }++ if (result.status === 'done') {+ updateCurrentJob({ status: 'done', progress: 100, outputUrl: result.outputUrl, originalOutputUrl: result.outputUrl })+ if (result.outputUrl) pushMeshUrl(result.outputUrl)+ void showCompletionNotification('Generation complete')+ break+ }++ if (result.status === 'error') {+ updateCurrentJob({ status: 'error', error: result.error })+ void showErrorNotification(result.error ?? 'Unknown error', 'Generation failed')+ break+ }++ updateCurrentJob({+ progress: result.progress,+ step: result.step,+ })+ }+ }++ const cancelGeneration = useCallback(() => {+ cancelledRef.current = true+ abortControllerRef.current?.abort()+ }, [])++ const reset = useCallback(() => setCurrentJob(null), [setCurrentJob])++ return { currentJob, startGeneration, cancelGeneration, reset }+}diff --git a/apps/forge-desktop/src/shared/router/Router.tsx b/apps/forge-desktop/src/shared/router/Router.tsxnew file mode 100644index 000000000..0b4f31df2--- /dev/null+++ b/apps/forge-desktop/src/shared/router/Router.tsx@@ -0,0 +1,16 @@+import { Suspense } from 'react'+import { useNavStore } from '@shared/stores/navStore'+import { ROUTES } from './routes'++export default function Router(): JSX.Element {+ const currentPage = useNavStore((s) => s.currentPage)+ const { component: Page, wrapperClass } = ROUTES[currentPage]++ return (+ <Suspense fallback={null}>+ <div className={wrapperClass}>+ <Page />+ </div>+ </Suspense>+ )+}diff --git a/apps/forge-desktop/src/shared/router/routes.tsx b/apps/forge-desktop/src/shared/router/routes.tsxnew file mode 100644index 000000000..732920bfe--- /dev/null+++ b/apps/forge-desktop/src/shared/router/routes.tsx@@ -0,0 +1,19 @@+import { lazy } from 'react'+import type { Page } from '@shared/stores/navStore'++const GeneratePage = lazy(() => import('@areas/generate/GeneratePage'))+const WorkflowsPage = lazy(() => import('@areas/workflows/WorkflowsPage'))+const ModelsPage = lazy(() => import('@areas/models/ModelsPage'))+const SettingsPage = lazy(() => import('@areas/settings/SettingsPage'))++export interface RouteConfig {+ component: React.ComponentType+ wrapperClass: string+}++export const ROUTES: Record<Page, RouteConfig> = {+ generate: { component: GeneratePage, wrapperClass: 'flex flex-1 overflow-hidden' },+ workflows: { component: WorkflowsPage, wrapperClass: 'flex flex-1 overflow-hidden' },+ models: { component: ModelsPage, wrapperClass: 'flex-1 overflow-y-auto' },+ settings: { component: SettingsPage, wrapperClass: 'flex-1 overflow-hidden' },+}diff --git a/apps/forge-desktop/src/shared/services/llmDownloads.ts b/apps/forge-desktop/src/shared/services/llmDownloads.tsnew file mode 100644index 000000000..18de4412f--- /dev/null+++ b/apps/forge-desktop/src/shared/services/llmDownloads.ts@@ -0,0 +1,104 @@+import { create } from 'zustand'+import { useAppStore } from '@shared/stores/appStore'++// GGUF model downloads must survive the Model Library modal being closed and+// reopened — the backend already keeps downloading in the background once+// started (see api/routers/llm.py), it just needs a watcher that isn't tied to+// a component's lifecycle. This module-level store owns that watch, the same+// way agentChat.ts owns the chat's SSE stream outside React.++export interface SseEvent {+ percent?: number+ status?: string+ bytesDownloaded?: number+ totalBytes?: number+ error?: string+ cancelled?: boolean+ paused?: boolean+}++/** Reads one SSE `data: {...}` frame at a time and calls `onEvent` for each. */+export async function consumeSse(url: string, onEvent: (data: SseEvent) => void, signal?: AbortSignal): Promise<void> {+ const res = await fetch(url, { signal })+ if (!res.ok || !res.body) throw new Error(`HTTP ${res.status}`)+ const reader = res.body.getReader()+ const decoder = new TextDecoder()+ let buf = ''+ outer: for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ buf += decoder.decode(value, { stream: true })+ const parts = buf.split('\n\n')+ buf = parts.pop() ?? ''+ for (const part of parts) {+ const line = part.split('\n').find((l) => l.startsWith('data: '))+ if (!line) continue+ let data: SseEvent+ try { data = JSON.parse(line.slice(6)) } catch { continue /* malformed frame */ }+ onEvent(data)+ // The stream stays open after an error frame — stop reading instead of+ // spinning on a download the server has already given up on.+ if (data.error) { void reader.cancel().catch(() => {}); break outer }+ }+ }+}++interface LlmDownloadsStore {+ downloads: Record<string, SseEvent | undefined>+ error: string | null+ start: (modelId: string) => void+ pause: (modelId: string) => Promise<void>+ cancel: (modelId: string) => Promise<void>+ dismissError: () => void+}++// Model ids this renderer is currently watching. The backend is reconnect-safe+// (a GET while a download is already in flight attaches instead of restarting+// it), this just avoids opening a second redundant connection from this same+// store if start() is called twice in a row (e.g. StrictMode double-invoke).+const _watching = new Set<string>()++export const useLlmDownloadsStore = create<LlmDownloadsStore>((set) => ({+ downloads: {},+ error: null,++ start(modelId) {+ if (_watching.has(modelId)) return+ _watching.add(modelId)+ const apiUrl = useAppStore.getState().apiUrl++ // Resuming from a paused entry: reset it to a live "connecting" state so the+ // Resume button flips back to Pause immediately, before the first SSE frame.+ set((s) => ({ downloads: { ...s.downloads, [modelId]: { percent: s.downloads[modelId]?.percent ?? 0, status: 'Starting…' } } }))++ let last: SseEvent | undefined+ void consumeSse(`${apiUrl}/llm/download?model_id=${encodeURIComponent(modelId)}`, (e) => {+ if (e.error) { set({ error: e.error }); return }+ last = e+ set((s) => ({ downloads: { ...s.downloads, [modelId]: e } }))+ })+ .catch((e) => set({ error: e instanceof Error ? e.message : String(e) }))+ .finally(() => {+ _watching.delete(modelId)+ // Keep the paused entry so a Resume button stays visible; the .part file+ // is preserved server-side and start() resumes it. Any other terminal+ // (done/cancelled/error) drops the row.+ set((s) => ({ downloads: { ...s.downloads, [modelId]: last?.paused ? last : undefined } }))+ })+ },++ async pause(modelId) {+ const apiUrl = useAppStore.getState().apiUrl+ await fetch(`${apiUrl}/llm/download/pause?model_id=${encodeURIComponent(modelId)}`, { method: 'POST' }).catch(() => {})+ },++ async cancel(modelId) {+ const apiUrl = useAppStore.getState().apiUrl+ await fetch(`${apiUrl}/llm/download/cancel?model_id=${encodeURIComponent(modelId)}`, { method: 'POST' }).catch(() => {})+ // A paused download has no live watcher to hit its .finally cleanup — drop+ // the row here so Cancel visibly clears it.+ set((s) => ({ downloads: { ...s.downloads, [modelId]: undefined } }))+ },++ dismissError: () => set({ error: null }),+}))diff --git a/apps/forge-desktop/src/shared/stores/agentStore.ts b/apps/forge-desktop/src/shared/stores/agentStore.tsnew file mode 100644index 000000000..23b2cfc0b--- /dev/null+++ b/apps/forge-desktop/src/shared/stores/agentStore.ts@@ -0,0 +1,155 @@+import { create } from 'zustand'+import { persist, createJSONStorage } from 'zustand/middleware'++export type ThinkingMode = 'auto' | 'on' | 'off'++export type ProviderId = 'local' | 'ollama' | 'openai' | 'anthropic' | 'mistral' | 'groq' | 'openrouter' | 'custom'++export interface ExternalConfig {+ apiKey: string+ model: string+ baseUrl?: string // only used by 'custom'+}++export const PROVIDERS: Record<ProviderId, { label: string; baseUrl: string; noKey?: boolean }> = {+ local: { label: 'Local (llama.cpp)', baseUrl: '' },+ // Ollama serves an OpenAI-compatible API — reuses models already pulled with it.+ ollama: { label: 'Ollama', baseUrl: 'http://localhost:11434/v1', noKey: true },+ openai: { label: 'ChatGPT (OpenAI)', baseUrl: 'https://api.openai.com/v1' },+ anthropic: { label: 'Claude (Anthropic)', baseUrl: 'https://api.anthropic.com/v1' },+ mistral: { label: 'Mistral', baseUrl: 'https://api.mistral.ai/v1' },+ groq: { label: 'Groq', baseUrl: 'https://api.groq.com/openai/v1' },+ openrouter: { label: 'OpenRouter', baseUrl: 'https://openrouter.ai/api/v1' },+ custom: { label: 'Custom endpoint', baseUrl: '' },+}++export const DEFAULT_LOCAL_MODEL = 'qwen3-4b'++// Catalog ids removed in the Qwen3/gpt-oss refresh → their closest replacement+const RETIRED_LOCAL_MODELS: Record<string, string> = {+ 'qwen2.5-3b': 'qwen3-4b',+ 'qwen2.5-7b': 'qwen3-4b',+ 'qwen2.5-14b': 'qwen3-14b',+ 'llama-3.1-8b': 'qwen3-4b',+ 'deepseek-r1-distill-qwen-7b': 'qwen3-14b',+}++/** Resolve the base URL for a provider (custom uses its own field). */+export function providerBaseUrl(provider: ProviderId, external: ExternalConfig | undefined): string {+ if (provider === 'custom') return external?.baseUrl ?? ''+ return PROVIDERS[provider].baseUrl+}++interface AgentSettings {+ provider: ProviderId+ localModel: string // catalog id or custom:<file>+ external: Partial<Record<ProviderId, ExternalConfig>>+ defaultThinking: ThinkingMode++ setProvider: (provider: ProviderId) => void+ setLocalModel: (model: string) => void+ setExternal: (provider: ProviderId, cfg: ExternalConfig) => void+ setDefaultThinking: (mode: ThinkingMode) => void+}++// ─── Secure persistence ────────────────────────────────────────────────────────+// External provider API keys are the one sensitive field in this store. They're+// encrypted at rest via Electron's safeStorage (OS keychain/DPAPI/libsecret) —+// everything else (provider, localModel, defaultThinking) stays plain, it isn't+// a secret. The ciphertext itself still lives in localStorage as a hex string;+// only the plaintext key never touches disk unencrypted.++type PersistedExternal = Partial<Record<ProviderId, ExternalConfig>>++function hasSecureStore(): boolean {+ return typeof window !== 'undefined' && !!window.electron?.secureStore+}++async function transformApiKeys(+ external: PersistedExternal | undefined,+ transform: (key: string) => Promise<string | null>,+): Promise<PersistedExternal | undefined> {+ if (!external || !hasSecureStore()) return external+ const entries = await Promise.all(+ Object.entries(external).map(async ([provider, cfg]) => {+ if (!cfg?.apiKey) return [provider, cfg] as const+ const key = await transform(cfg.apiKey)+ // null = stored blob we can't decrypt here (different OS user/machine).+ // Drop it: sending a ciphertext as an Authorization header just 401s, and+ // keeping it in state would re-encrypt it on the next write.+ return [provider, { ...cfg, apiKey: key ?? '' }] as const+ }),+ )+ return Object.fromEntries(entries) as PersistedExternal+}++const secureAgentStorage = {+ getItem: async (name: string): Promise<string | null> => {+ const raw = localStorage.getItem(name)+ if (!raw) return raw+ try {+ const envelope = JSON.parse(raw)+ if (envelope?.state?.external) {+ envelope.state.external = await transformApiKeys(envelope.state.external, (k) => window.electron.secureStore.decrypt(k))+ }+ return JSON.stringify(envelope)+ } catch {+ return raw+ }+ },+ setItem: async (name: string, value: string): Promise<void> => {+ try {+ const envelope = JSON.parse(value)+ if (envelope?.state?.external) {+ envelope.state.external = await transformApiKeys(envelope.state.external, (k) => window.electron.secureStore.encrypt(k))+ }+ localStorage.setItem(name, JSON.stringify(envelope))+ } catch {+ localStorage.setItem(name, value)+ }+ },+ removeItem: async (name: string): Promise<void> => { localStorage.removeItem(name) },+}++export const useAgentStore = create<AgentSettings>()(+ persist(+ (set) => ({+ provider: 'local',+ localModel: DEFAULT_LOCAL_MODEL,+ external: {},+ defaultThinking: 'auto',++ setProvider: (provider) => set({ provider }),+ setLocalModel: (model) => set({ localModel: model }),+ setExternal: (provider, cfg) => set((s) => ({ external: { ...s.external, [provider]: cfg } })),+ setDefaultThinking: (mode) => set({ defaultThinking: mode }),+ }),+ {+ name: 'modly-agent-settings',+ version: 3,+ storage: createJSONStorage(() => secureAgentStorage),+ // v0 stored { ollamaUrl, defaultModel } — drop them, keep only thinking.+ // v2 retired the Qwen2.5/Llama3.1 catalog ids.+ // v3 is a shape-less bump: the version change alone forces one re-persist+ // through secureAgentStorage.setItem, which encrypts any legacy+ // plaintext API key saved before safeStorage existed. Self-limiting —+ // once stored as v3 it never re-runs, so it costs one write, not one per boot.+ migrate: (persisted: unknown, version) => {+ if (version === 0 && persisted && typeof persisted === 'object') {+ const old = persisted as { defaultThinking?: ThinkingMode }+ return {+ provider: 'local' as ProviderId,+ localModel: DEFAULT_LOCAL_MODEL,+ external: {},+ defaultThinking: old.defaultThinking ?? 'auto',+ }+ }+ const state = persisted as AgentSettings+ if (version < 2 && state?.localModel && RETIRED_LOCAL_MODELS[state.localModel]) {+ return { ...state, localModel: RETIRED_LOCAL_MODELS[state.localModel] }+ }+ return state+ },+ },+ ),+)diff --git a/apps/forge-desktop/src/shared/stores/appStore.ts b/apps/forge-desktop/src/shared/stores/appStore.tsnew file mode 100644index 000000000..bb5ddd0e0--- /dev/null+++ b/apps/forge-desktop/src/shared/stores/appStore.ts@@ -0,0 +1,321 @@+import { create } from 'zustand'+import { persist } from 'zustand/middleware'++export type UiScale = 'small' | 'medium' | 'large' | 'very-large'+export type BackendStatus = 'not_started' | 'starting' | 'ready' | 'error'+export type SetupStatus = 'idle' | 'checking' | 'needed' | 'installing' | 'done' | 'error'+export interface SetupProgress { step: string; percent: number; currentPackage?: string }++export type GenerationStatus =+ | 'idle'+ | 'uploading'+ | 'generating'+ | 'done'+ | 'error'++export interface GenerationJob {+ id: string+ imageFile: string+ status: GenerationStatus+ progress: number+ step?: string+ outputUrl?: string+ originalOutputUrl?: string // mesh URL before any optimization+ thumbnailUrl?: string+ modelId?: string // model used for this generation+ originalTriangles?: number // polygon count of the original mesh+ generationOptions?: GenerationOptions+ error?: string+ createdAt: number+}++export interface GenerationOptions {+ modelId: string+ remesh: 'quad' | 'triangle' | 'none'+ enableTexture: boolean+ textureResolution: number+ modelParams: Record<string, any>+}++export interface LightSettings {+ mainIntensity: number+ mainColor: string+ fillIntensity: number+ fillColor: string+ ambientIntensity: number+ envIntensity: number+}++export interface PointLight {+ id: string+ position: [number, number, number]+ color: string+ intensity: number+}++export interface AppToast {+ id: number+ message: string+ durationMs?: number+}++const DEFAULT_OPTIONS: GenerationOptions = {+ modelId: '',+ remesh: 'quad',+ enableTexture: false,+ textureResolution: 512,+ modelParams: {},+}++export const DEFAULT_LIGHT_SETTINGS: LightSettings = {+ // Matches the offline debug renderer's flat studio rig: two soft directional+ // lights (key ~0.8 / fill ~0.35) + high ambient (0.45) that lifts dark albedo+ // (black cat) out of "void" shadows, NO IBL (envIntensity 0).+ // All live-adjustable from the Lighting popover (Reset returns here).+ mainIntensity: 0.8,+ mainColor: '#ffffff',+ fillIntensity: 0.35,+ fillColor: '#ffffff',+ ambientIntensity: 0.45,+ envIntensity: 0.0,+}++interface AppState {+ // Backend+ backendStatus: BackendStatus+ apiUrl: string+ backendError: string | null++ // Current generation+ currentJob: GenerationJob | null++ // Selected image (shared between ImageUpload and the Generate button)+ selectedImagePath: string | null+ setSelectedImagePath: (path: string | null) => void+ selectedImagePreviewUrl: string | null+ setSelectedImagePreviewUrl: (url: string | null) => void+ selectedImageData: string | null // base64 content for drag & drop (when path is unavailable)+ setSelectedImageData: (data: string | null) => void++ // Generation options+ generationOptions: GenerationOptions++ // Mesh stats (set by Viewer3D, read by GenerationHUD)+ meshStats: { vertices: number; triangles: number } | null+ setMeshStats: (stats: { vertices: number; triangles: number } | null) => void++ // Mesh selection (set by Viewer3D click, read by the Generate tools bar)+ meshSelected: boolean+ setMeshSelected: (selected: boolean) => void++ // Setup+ setupStatus: SetupStatus+ setupProgress: SetupProgress | null+ setupError: string | null+ defaultDataDir: string+ platform: string+ arch: string+ checkSetup: () => Promise<void>+ runSetup: () => Promise<void>+ saveDataDir: (baseDir: string) => Promise<void>++ // Patch auto-update+ patchUpdateReady: boolean+ setPatchUpdateReady: (ready: boolean) => void++ // Error modal+ errorModal: string | null+ showError: (message: string) => void+ hideError: () => void++ // Toast+ toast: AppToast | null+ showToast: (message: string, durationMs?: number) => void+ hideToast: () => void++ // Mesh URL history (undo/redo)+ meshHistory: string[]+ historyIndex: number+ pushMeshUrl: (url: string) => void+ undoMesh: () => void+ redoMesh: () => void+ clearMeshHistory: () => void++ // UI preferences+ showRamIndicator: boolean+ setShowRamIndicator: (v: boolean) => void++ // Accessibility+ useAtkinsonFont: boolean+ setUseAtkinsonFont: (v: boolean) => void+ uiScale: UiScale+ setUiScale: (v: UiScale) => void++ // 3D viewer lighting+ lightSettings: LightSettings+ setLightSettings: (settings: LightSettings) => void+ pointLights: PointLight[]+ setPointLights: (lights: PointLight[]) => void++ // Actions+ initApp: () => Promise<void>+ setCurrentJob: (job: GenerationJob | null) => void+ updateCurrentJob: (patch: Partial<GenerationJob>) => void+ setGenerationOptions: (patch: Partial<GenerationOptions>) => void+}++export const useAppStore = create<AppState>()(+ persist(+ (set, get) => ({+ backendStatus: 'not_started',+ apiUrl: '',+ backendError: null,++ setupStatus: 'idle',+ setupProgress: null,+ setupError: null,+ defaultDataDir: '',+ platform: '',+ arch: '',++ checkSetup: async () => {+ set({ setupStatus: 'checking' })+ const { needed, defaultDataDir, platform, arch } = await window.electron.setup.check()+ set({ setupStatus: needed ? 'needed' : 'done', defaultDataDir, platform, arch })+ },++ saveDataDir: async (baseDir: string) => {+ await window.electron.setup.saveDataDir(baseDir)+ get().runSetup()+ },++ runSetup: async () => {+ set({ setupStatus: 'installing', setupProgress: null, setupError: null })++ window.electron.setup.offProgress()+ window.electron.setup.offComplete()+ window.electron.setup.offError()++ window.electron.setup.onProgress((data) => {+ set({ setupProgress: data })+ })+ window.electron.setup.onComplete(() => {+ set({ setupStatus: 'done', setupProgress: null })+ })+ window.electron.setup.onError((data) => {+ set({ setupStatus: 'error', setupError: data.message })+ })++ // Fire and forget — progress comes via IPC events+ window.electron.setup.run()+ },++ patchUpdateReady: false,+ setPatchUpdateReady: (ready) => set({ patchUpdateReady: ready }),++ errorModal: null,+ showError: (message) => set({ errorModal: message }),+ hideError: () => set({ errorModal: null }),++ toast: null,+ showToast: (message, durationMs) => set({ toast: { id: Date.now(), message, durationMs } }),+ hideToast: () => set({ toast: null }),++ meshHistory: [],+ historyIndex: -1,++ pushMeshUrl: (url) => {+ const { meshHistory, historyIndex } = get()+ const next = [...meshHistory.slice(0, historyIndex + 1), url]+ set({ meshHistory: next, historyIndex: next.length - 1 })+ },++ undoMesh: () => {+ const { meshHistory, historyIndex } = get()+ if (historyIndex <= 0) return+ const newIndex = historyIndex - 1+ set({ historyIndex: newIndex })+ get().updateCurrentJob({ outputUrl: meshHistory[newIndex] })+ },++ redoMesh: () => {+ const { meshHistory, historyIndex } = get()+ if (historyIndex >= meshHistory.length - 1) return+ const newIndex = historyIndex + 1+ set({ historyIndex: newIndex })+ get().updateCurrentJob({ outputUrl: meshHistory[newIndex] })+ },++ clearMeshHistory: () => set({ meshHistory: [], historyIndex: -1 }),++ showRamIndicator: true,+ setShowRamIndicator: (v) => set({ showRamIndicator: v }),++ useAtkinsonFont: false,+ setUseAtkinsonFont: (v) => set({ useAtkinsonFont: v }),+ uiScale: 'medium',+ setUiScale: (v) => set({ uiScale: v }),++ lightSettings: DEFAULT_LIGHT_SETTINGS,+ setLightSettings: (settings) => set({ lightSettings: settings }),+ pointLights: [],+ setPointLights: (lights) => set({ pointLights: lights }),++ currentJob: null,+ selectedImagePath: null,+ setSelectedImagePath: (path) => set({ selectedImagePath: path }),+ selectedImagePreviewUrl: null,+ setSelectedImagePreviewUrl: (url) => set({ selectedImagePreviewUrl: url }),+ selectedImageData: null,+ setSelectedImageData: (data) => set({ selectedImageData: data }),+ generationOptions: DEFAULT_OPTIONS,+ meshStats: null,+ setMeshStats: (stats) => set({ meshStats: stats }),+ meshSelected: false,+ setMeshSelected: (selected) => set({ meshSelected: selected }),+ initApp: async () => {+ set({ backendStatus: 'starting', backendError: null })++ window.electron.python.offCrashed()+ window.electron.python.onCrashed(({ code }) => {+ const msg = `FastAPI process crashed unexpectedly (exit code: ${code ?? 'unknown'})`+ set({ backendStatus: 'error', apiUrl: '', backendError: msg })+ get().showError(msg)+ })++ try {+ const result = await window.electron.python.start()+ if (!result.success) throw new Error(result.error ?? 'Failed to start backend')+ const { apiUrl } = await window.electron.app.info()+ set({ backendStatus: 'ready', apiUrl })+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err)+ set({ backendStatus: 'error', backendError: msg })+ get().showError(msg)+ }+ },++ setCurrentJob: (job) => set({ currentJob: job, meshStats: job === null ? null : get().meshStats }),++ updateCurrentJob: (patch) => {+ const current = get().currentJob+ if (!current) return+ set({ currentJob: { ...current, ...patch } })+ },++ setGenerationOptions: (patch) => {+ set((state) => ({ generationOptions: { ...state.generationOptions, ...patch } }))+ },+ }),+ {+ name: 'modly-store',+ partialize: (state) => ({+ generationOptions: state.generationOptions,+ showRamIndicator: state.showRamIndicator,+ useAtkinsonFont: state.useAtkinsonFont,+ uiScale: state.uiScale,+ lightSettings: state.lightSettings,+ }),+ }+ )+)diff --git a/apps/forge-desktop/src/shared/stores/extensionsStore.test.mjs b/apps/forge-desktop/src/shared/stores/extensionsStore.test.mjsnew file mode 100644index 000000000..068dc923f--- /dev/null+++ b/apps/forge-desktop/src/shared/stores/extensionsStore.test.mjs@@ -0,0 +1,49 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-ext-store-test-')), 'extensionsStore.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('src/shared/stores/extensionsStore.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++test('extension list keeps an interrupted model in the model store with recovery metadata', () => {+ const { partitionExtensionsByType } = loadModule()+ const pendingModel = {+ type: 'model',+ id: 'pixal3d',+ name: 'Pixal3D',+ trusted: false,+ builtin: false,+ nodes: [{ id: 'generate' }],+ corrupted: true,+ manifestError: 'incomplete',+ }+ const processExtension = {+ type: 'process',+ id: 'mesh-tool',+ name: 'Mesh Tool',+ trusted: false,+ builtin: false,+ entry: 'processor.js',+ nodes: [{ id: 'simplify' }],+ }++ const result = partitionExtensionsByType([pendingModel, processExtension])++ assert.deepEqual(result.modelExtensions, [pendingModel])+ assert.deepEqual(result.processExtensions, [processExtension])+})diff --git a/apps/forge-desktop/src/shared/stores/extensionsStore.ts b/apps/forge-desktop/src/shared/stores/extensionsStore.tsnew file mode 100644index 000000000..ada611f2d--- /dev/null+++ b/apps/forge-desktop/src/shared/stores/extensionsStore.ts@@ -0,0 +1,215 @@+import { create } from 'zustand'+import type { ModelExtension, ProcessExtension, AnyExtension } from '@shared/types/electron.d'++// ─── Re-exports for consumers ─────────────────────────────────────────────────++export type { ModelExtension, ProcessExtension, AnyExtension }+++export type InstallStep = 'downloading' | 'extracting' | 'validating' | 'setting_up' | 'done' | 'error'++export interface InstallProgress {+ step: InstallStep+ percent?: number+ extensionId?: string+ message?: string+}++// ─── Store ────────────────────────────────────────────────────────────────────++interface ExtensionsStore {+ modelExtensions: ModelExtension[]+ processExtensions: ProcessExtension[]+ loading: boolean+ installProgress: InstallProgress | null+ installError: string | null+ loadErrors: Record<string, string>+ /** Installed weight variant ids, keyed by "ext_id/node_id", for nodes that declare variants */+ installedWeightVariants: Record<string, string[]>++ loadExtensions: () => Promise<void>+ refreshInstalledWeightVariants: () => Promise<void>+ installFromGitHub: (url: string) => Promise<{ success: boolean; error?: string }>+ installFromLocal: () => Promise<{ success: boolean; error?: string; cancelled?: boolean; needsRepair?: boolean }>+ uninstall: (extensionId: string) => Promise<{ success: boolean; error?: string }>+ reload: () => Promise<void>+ clearInstallState: () => void+}++export function partitionExtensionsByType(list: AnyExtension[]): {+ modelExtensions: ModelExtension[]+ processExtensions: ProcessExtension[]+} {+ return {+ modelExtensions: list.filter((extension): extension is ModelExtension =>+ extension.type === 'model',+ ),+ processExtensions: list.filter((extension): extension is ProcessExtension =>+ extension.type === 'process',+ ),+ }+}++export const useExtensionsStore = create<ExtensionsStore>((set, get) => ({+ modelExtensions: [],+ processExtensions: [],+ loading: false,+ installProgress: null,+ installError: null,+ loadErrors: {},+ installedWeightVariants: {},++ // ── Load list ──────────────────────────────────────────────────────────────++ async loadExtensions() {+ set({ loading: true })+ try {+ const list = (await window.electron.extensions.list()) as AnyExtension[]+ const extensions = partitionExtensionsByType(list)+ set({+ ...extensions,+ loading: false,+ })+ await get().refreshInstalledWeightVariants()+ } catch {+ set({ loading: false })+ }+ },++ async refreshInstalledWeightVariants() {+ const entries = await Promise.all(+ get().modelExtensions.flatMap((ext) => ext.nodes+ .filter((node) => node.weightVariants)+ .map(async (node) => {+ const fullId = `${ext.id}/${node.id}`+ return [fullId, await window.electron.model.installedWeightVariants(fullId)] as const+ })),+ )+ // A node whose state could not be read stays absent: undefined reads as "unknown",+ // which the UI keeps neutral, while [] would claim no variant is installed.+ set({+ installedWeightVariants: Object.fromEntries(+ entries.filter((entry): entry is readonly [string, string[]] => entry[1] !== null),+ ),+ })+ },++ // ── Install from GitHub ────────────────────────────────────────────────────++ async installFromGitHub(url: string) {+ return installExtension(() => window.electron.extensions.installFromGitHub(url), set)+ },++ // ── Install from local folder ──────────────────────────────────────────────++ async installFromLocal() {+ const result = await installExtension(() => window.electron.extensions.installFromLocal(), set)+ // If user cancelled the folder picker, treat as a no-op (not an error)+ if ((result as any).cancelled) {+ set({ installProgress: null, installError: null })+ return { success: false, cancelled: true }+ }+ return result+ },++ // ── Uninstall ──────────────────────────────────────────────────────────────++ async uninstall(extensionId: string) {+ const result = await window.electron.extensions.uninstall(extensionId)+ if (result.success) {+ set((state) => ({+ modelExtensions: state.modelExtensions.filter((e) => e.id !== extensionId),+ processExtensions: state.processExtensions.filter((e) => e.id !== extensionId),+ }))+ }+ return result+ },++ // ── Reload (rescan extensions dir + Python registry) ──────────────────────++ async reload() {+ const result = await window.electron.extensions.reload()+ if (result.success) {+ set({ loadErrors: result.errors ?? {} })+ }+ await get().loadExtensions()+ },++ // ── Helpers ────────────────────────────────────────────────────────────────++ clearInstallState() {+ set({ installProgress: null, installError: null })+ },+}))++async function installExtension(+ invoke: () => Promise<{+ success: boolean+ error?: string+ extension?: AnyExtension+ extensionId?: string+ needsRepair?: boolean+ }>,+ set: (partial: Partial<ExtensionsStore> | ((state: ExtensionsStore) => Partial<ExtensionsStore>)) => void,+) {+ set({ installProgress: { step: 'downloading', percent: 0 }, installError: null })++ window.electron.extensions.onInstallProgress((data) => {+ if (data.step === 'error') {+ set({ installProgress: null, installError: data.message ?? 'Unknown error' })+ } else {+ set({ installProgress: data as InstallProgress })+ }+ })++ try {+ const result = await invoke()++ if (result.success && result.extension) {+ const ext = result.extension as AnyExtension+ set((state) => {+ if (ext.type === 'process') {+ const filtered = state.processExtensions.filter((e) => e.id !== ext.id)+ return {+ processExtensions: [...filtered, ext],+ modelExtensions: state.modelExtensions.filter((e) => e.id !== ext.id),+ installProgress: { step: 'done', extensionId: result.extensionId },+ installError: null,+ }+ } else {+ const filtered = state.modelExtensions.filter((e) => e.id !== ext.id)+ return {+ modelExtensions: [...filtered, ext],+ processExtensions: state.processExtensions.filter((e) => e.id !== ext.id),+ installProgress: { step: 'done', extensionId: result.extensionId },+ installError: null,+ }+ }+ })+ } else if (result.needsRepair && result.extension) {+ const ext = result.extension as AnyExtension+ const error = result.error ?? 'Extension setup is incomplete. Click Repair and retry.'+ set((state) => ({+ modelExtensions: ext.type === 'model'+ ? [...state.modelExtensions.filter((entry) => entry.id !== ext.id), ext]+ : state.modelExtensions.filter((entry) => entry.id !== ext.id),+ processExtensions: ext.type === 'process'+ ? [...state.processExtensions.filter((entry) => entry.id !== ext.id), ext]+ : state.processExtensions.filter((entry) => entry.id !== ext.id),+ loadErrors: { ...state.loadErrors, [ext.id]: error },+ installProgress: null,+ installError: error,+ }))+ } else {+ set({ installProgress: null, installError: result.error ?? 'Installation failed' })+ }++ return result+ } catch (err) {+ const error = String(err)+ set({ installProgress: null, installError: error })+ return { success: false, error }+ } finally {+ window.electron.extensions.offInstallProgress()+ }+}diff --git a/apps/forge-desktop/src/shared/stores/llmModelsStore.react.test.mjs b/apps/forge-desktop/src/shared/stores/llmModelsStore.react.test.mjsnew file mode 100644index 000000000..b8c305f9c--- /dev/null+++ b/apps/forge-desktop/src/shared/stores/llmModelsStore.react.test.mjs@@ -0,0 +1,82 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { createRequire } from 'node:module'+import { setupDom, loadModule, mount } from '../../../scripts/react-test-env.mjs'++setupDom()+const React = createRequire(import.meta.url)('react')++/** A fresh module per test: the catalog store caches across calls by design, so+ * a shared instance would make each test depend on the ones before it. */+const freshHook = () => loadModule('src/shared/stores/llmModelsStore.ts').useLlmModels++/** Counts every request the hook makes, and answers with a fixed catalog. */+function countingFetch() {+ const calls = []+ globalThis.fetch = (url) => {+ calls.push(String(url))+ return Promise.resolve({ json: () => Promise.resolve({ models: [{ id: 'qwen3-4b', downloaded: true }] }) })+ }+ return calls+}++test('the hook fetches the catalog once, however many times it renders', async () => {+ const useLlmModels = freshHook()+ const calls = countingFetch()+ const Probe = () => { useLlmModels(); return null }++ const view = await mount(React.createElement(Probe))+ await view.rerender()+ await view.rerender()+ await view.flush()++ assert.equal(calls.length, 1)+ await view.unmount()+})++test('refresh and the model list keep their identity across renders', async () => {+ // The regression: `refresh` was rebuilt on every render, so any caller+ // holding it in a dependency array re-ran its effect forever.+ const useLlmModels = freshHook()+ countingFetch()+ const seen = []+ const Probe = () => { seen.push(useLlmModels()); return null }++ const view = await mount(React.createElement(Probe))+ await view.flush()+ await view.rerender()++ const last = seen[seen.length - 1]+ const previous = seen[seen.length - 2]+ assert.equal(last.refresh, previous.refresh)+ assert.equal(last.models, previous.models)+ await view.unmount()+})++test('a consumer that refreshes from an effect settles instead of looping', async () => {+ // Exactly the shape of ModelLibraryModal: an effect keyed on `refresh` that+ // stores something in state. With an unstable `refresh` this rendered — and+ // fetched — without end; the modal flickered for as long as it was open.+ const useLlmModels = freshHook()+ const calls = countingFetch()+ let renders = 0++ const Modal = () => {+ const { refresh } = useLlmModels()+ const [, setStatus] = React.useState(null)+ renders+++ // Fails fast and says why: an unstable `refresh` makes this loop forever,+ // and a test that hangs for a minute before dying explains nothing.+ if (renders > 50) throw new Error('render loop — the effect keeps re-running')+ React.useEffect(() => { void refresh(); setStatus({ checkedAt: renders }) }, [refresh])+ return null+ }++ const view = await mount(React.createElement(Modal))+ await view.flush()+ await view.flush()++ assert.equal(calls.length, 2) // the hook's own load, plus one forced refresh+ assert.ok(renders < 10, `expected a handful of renders, got ${renders}`)+ await view.unmount()+})diff --git a/apps/forge-desktop/src/shared/stores/llmModelsStore.test.mjs b/apps/forge-desktop/src/shared/stores/llmModelsStore.test.mjsnew file mode 100644index 000000000..372d42bad--- /dev/null+++ b/apps/forge-desktop/src/shared/stores/llmModelsStore.test.mjs@@ -0,0 +1,106 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++// Bundle the store with its real zustand dependency — same approach as+// workflowsStore.test.mjs. Only fetchModels() is exercised, so the React hook+// at the bottom of the module is never rendered.+function loadStore() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-llmstore-test-')), 'llmModelsStore.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('src/shared/stores/llmModelsStore.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile).useLlmModelsStore+}++/** A /llm/models endpoint whose answers are released one at a time. */+function deferredFetch() {+ const calls = []+ globalThis.fetch = () => {+ let release+ const body = new Promise((r) => { release = r })+ calls.push({ release })+ return Promise.resolve({ json: () => body })+ }+ return calls+}++const model = (id, downloaded) => ({+ id, name: id, hf_filename: `${id}.gguf`, downloaded, source: 'catalog',+})++test('concurrent plain fetches share one request', async () => {+ const useStore = loadStore()+ const calls = deferredFetch()++ const a = useStore.getState().fetchModels('http://api')+ const b = useStore.getState().fetchModels('http://api')+ assert.equal(calls.length, 1)++ calls[0].release({ models: [model('qwen', false)] })+ await Promise.all([a, b])+ assert.equal(useStore.getState().models[0].downloaded, false)+})++test('a forced refresh re-fetches instead of joining the pending request', async () => {+ const useStore = loadStore()+ const calls = deferredFetch()++ // Mount-time fetch, still in flight when the download finishes.+ const initial = useStore.getState().fetchModels('http://api')+ const refreshed = useStore.getState().fetchModels('http://api', { force: true })++ calls[0].release({ models: [model('qwen', false)] })+ await initial+ assert.equal(calls.length, 2, 'force must issue its own request')++ calls[1].release({ models: [model('qwen', true)] })+ await refreshed+ // Joining the pre-download request left `downloaded: false`, and the preflight+ // kept refusing to run the workflow.+ assert.equal(useStore.getState().models[0].downloaded, true)+})++test('a forced refresh still settles when the pending request fails', async () => {+ const useStore = loadStore()+ const calls = []+ globalThis.fetch = () => {+ let settle+ const p = new Promise((resolve, reject) => { settle = { resolve, reject } })+ calls.push(settle)+ return p+ }++ const initial = useStore.getState().fetchModels('http://api')+ const refreshed = useStore.getState().fetchModels('http://api', { force: true })++ calls[0].reject(new Error('offline'))+ await initial+ calls[1].resolve({ json: async () => ({ models: [model('qwen', true)] }) })+ await refreshed++ assert.equal(useStore.getState().models[0].downloaded, true)+ assert.equal(useStore.getState().error, null)+})++test('a cached catalog is not re-fetched without force', async () => {+ const useStore = loadStore()+ const calls = deferredFetch()++ const first = useStore.getState().fetchModels('http://api')+ calls[0].release({ models: [model('qwen', true)] })+ await first++ await useStore.getState().fetchModels('http://api')+ assert.equal(calls.length, 1)+})diff --git a/apps/forge-desktop/src/shared/stores/llmModelsStore.ts b/apps/forge-desktop/src/shared/stores/llmModelsStore.tsnew file mode 100644index 000000000..89da3ed1c--- /dev/null+++ b/apps/forge-desktop/src/shared/stores/llmModelsStore.ts@@ -0,0 +1,112 @@+import { create } from 'zustand'+import { useCallback, useEffect, useMemo } from 'react'+import { useAppStore } from './appStore'++export interface LlmModel {+ id: string+ name: string+ description?: string+ hf_filename: string+ size_bytes?: number+ quant?: string+ vram_estimate_mb?: number+ downloaded: boolean+ source: 'catalog' | 'custom'+ tags?: string[]+ /** How well this model drives the agent — see components/ui/agentGrade.ts.+ * `agent_score` is only shown when `agent_source` is 'measured', i.e. the+ * model was actually run against Modly's own eval suite. */+ agent_tier?: 'excellent' | 'solid' | 'limited'+ agent_score?: number+ agent_source?: 'measured' | 'estimate'+ agent_note?: string+}++interface LlmModelsStore {+ models: LlmModel[]+ loading: boolean+ error: string | null+ fetchedApiUrl: string | null+ fetchModels: (apiUrl: string, opts?: { force?: boolean }) => Promise<void>+}++// Module-level so concurrent callers (multiple nodes/components mounting at+// once) share one in-flight request instead of firing N identical fetches.+let inFlight: Promise<void> | null = null+// Identifies the request currently owning `inFlight`, so a superseded one does+// not clear a newer forced refresh on its way out.+let inFlightId = 0++export const useLlmModelsStore = create<LlmModelsStore>((set, get) => ({+ models: [],+ loading: false,+ error: null,+ fetchedApiUrl: null,++ async fetchModels(apiUrl, opts) {+ const state = get()+ if (!opts?.force && state.fetchedApiUrl === apiUrl && state.models.length > 0) return+ // A forced refresh follows a mutation (download finished, model deleted), so+ // it must not settle for a request issued BEFORE it: joining the in-flight+ // one kept the pre-mutation `downloaded` flags, and the preflight went on+ // reporting "…isn't downloaded" for a model that had just landed.+ const pending = inFlight+ if (pending && !opts?.force) return pending++ set({ loading: true, error: null })+ const id = ++inFlightId+ const request = (async () => {+ if (pending) {+ await pending.catch(() => {})+ set({ loading: true, error: null }) // the request we waited on may have failed+ }+ try {+ const res = await fetch(`${apiUrl}/llm/models`)+ const data: { models?: LlmModel[] } = await res.json()+ set({ models: data.models ?? [], fetchedApiUrl: apiUrl, loading: false, error: null })+ } catch (e) {+ set({ error: e instanceof Error ? e.message : String(e), loading: false })+ } finally {+ if (inFlightId === id) inFlight = null+ }+ })()+ inFlight = request+ return request+ },+}))++/**+ * Shared local-LLM catalog: fetched once per apiUrl and cached across every+ * consumer (LLM node, extension param pickers, chat model picker, Settings…)+ * instead of each component firing its own `/llm/models` request.+ *+ * `tag` mirrors the backend's own filter (`GET /llm/models?tag=`): custom+ * GGUFs are always kept since their capabilities aren't known ahead of time.+ */+export function useLlmModels(tag?: string): {+ models: LlmModel[]+ loading: boolean+ error: string | null+ refresh: () => Promise<void>+} {+ const apiUrl = useAppStore((s) => s.apiUrl)+ const models = useLlmModelsStore((s) => s.models)+ const loading = useLlmModelsStore((s) => s.loading)+ const error = useLlmModelsStore((s) => s.error)+ const fetchModels = useLlmModelsStore((s) => s.fetchModels)++ useEffect(() => { void fetchModels(apiUrl) }, [apiUrl, fetchModels])++ // Both memoised because callers put them in dependency arrays. A `refresh`+ // rebuilt on every render made ModelLibraryModal's `useEffect(…, [refresh])`+ // re-run on every render: each pass forced a /llm/models + /llm/status fetch,+ // whose setState triggered the next one. The modal flickered and hammered the+ // API for as long as it stayed open.+ const filtered = useMemo(+ () => (tag ? models.filter((m) => m.source === 'custom' || (m.tags ?? []).includes(tag)) : models),+ [models, tag],+ )+ const refresh = useCallback(() => fetchModels(apiUrl, { force: true }), [apiUrl, fetchModels])++ return { models: filtered, loading, error, refresh }+}diff --git a/apps/forge-desktop/src/shared/stores/navStore.ts b/apps/forge-desktop/src/shared/stores/navStore.tsnew file mode 100644index 000000000..62afa2f58--- /dev/null+++ b/apps/forge-desktop/src/shared/stores/navStore.ts@@ -0,0 +1,19 @@+import { create } from 'zustand'++export type Page = 'generate' | 'workflows' | 'models' | 'settings'++interface NavState {+ currentPage: Page+ extensionToOpen: string | null+ navigate: (page: Page) => void+ openExtension: (extensionId: string) => void+ clearExtensionToOpen: () => void+}++export const useNavStore = create<NavState>((set) => ({+ currentPage: 'generate',+ extensionToOpen: null,+ navigate: (page) => set({ currentPage: page }),+ openExtension: (extensionId) => set({ currentPage: 'models', extensionToOpen: extensionId }),+ clearExtensionToOpen: () => set({ extensionToOpen: null }),+}))diff --git a/apps/forge-desktop/src/shared/stores/workflowsStore.test.mjs b/apps/forge-desktop/src/shared/stores/workflowsStore.test.mjsnew file mode 100644index 000000000..964e5d587--- /dev/null+++ b/apps/forge-desktop/src/shared/stores/workflowsStore.test.mjs@@ -0,0 +1,148 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++// Bundle the store with its real zustand dependency; the only other import is a+// type-only one (electron.d) which esbuild erases. The store reads the global+// `window.electron.workflows.*` bridge, which we stub per test.+function loadStore() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-wfstore-test-')), 'workflowsStore.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('src/shared/stores/workflowsStore.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile).useWorkflowsStore+}++function stubBridge(workflows = {}) {+ globalThis.window = { electron: { workflows } }+}++const migrated = (id, over = {}) => ({+ id, name: id.toUpperCase(), description: '', nodes: [], edges: [],+ createdAt: '', updatedAt: '', ...over,+})++const legacyBlocks = (id) => ({+ id, name: id.toUpperCase(), description: '', input: 'image',+ blocks: [{ id: `${id}-blk`, extension: 'pack/x', enabled: true, params: {} }],+ createdAt: '', updatedAt: '',+})++// ─── load(): dedupe + migrate ──────────────────────────────────────────────────++test('load dedupes workflows that share an id, keeping the first', async () => {+ const useStore = loadStore()+ stubBridge({+ list: async () => [migrated('a', { name: 'FIRST' }), migrated('a', { name: 'SECOND' }), migrated('b')],+ })++ await useStore.getState().load()+ const { workflows, loading } = useStore.getState()++ assert.equal(loading, false)+ assert.deepEqual(workflows.map((w) => w.id), ['a', 'b'])+ assert.equal(workflows[0].name, 'FIRST') // the duplicate is dropped, first wins+})++test('load migrates legacy block-format workflows into nodes + edges', async () => {+ const useStore = loadStore()+ stubBridge({ list: async () => [legacyBlocks('w')] })++ await useStore.getState().load()+ const wf = useStore.getState().workflows[0]++ assert.deepEqual(wf.nodes.map((n) => n.type), ['inputNode', 'extensionNode'])+ assert.equal(wf.nodes[0].id, 'input-w')+ assert.equal(wf.nodes[1].id, 'w-blk')+ assert.equal(wf.edges.length, 1)+ assert.deepEqual({ source: wf.edges[0].source, target: wf.edges[0].target }, { source: 'input-w', target: 'w-blk' })+})++test('load flips loading back to false when the bridge throws', async () => {+ const useStore = loadStore()+ stubBridge({ list: async () => { throw new Error('disk error') } })++ await useStore.getState().load()+ assert.equal(useStore.getState().loading, false)+})++// ─── save(): insert vs update ──────────────────────────────────────────────────++test('save inserts a new workflow at the front, updates an existing one in place', async () => {+ const useStore = loadStore()+ stubBridge({ save: async () => ({ success: true }) })+ useStore.setState({ workflows: [migrated('a'), migrated('b')] })++ await useStore.getState().save(migrated('c'))+ assert.deepEqual(useStore.getState().workflows.map((w) => w.id), ['c', 'a', 'b'])++ await useStore.getState().save(migrated('b', { name: 'B2' }))+ const wf = useStore.getState().workflows.find((w) => w.id === 'b')+ assert.equal(wf.name, 'B2')+ assert.equal(useStore.getState().workflows.length, 3) // no duplicate+})++test('save does not touch state when the bridge reports failure', async () => {+ const useStore = loadStore()+ stubBridge({ save: async () => ({ success: false, error: 'nope' }) })+ useStore.setState({ workflows: [migrated('a')] })++ const result = await useStore.getState().save(migrated('z'))+ assert.equal(result.success, false)+ assert.deepEqual(useStore.getState().workflows.map((w) => w.id), ['a'])+})++// ─── remove(): filter + active reset ────────────────────────────────────────────++test('remove drops the workflow and clears activeId when it was the active one', async () => {+ const useStore = loadStore()+ stubBridge({ delete: async () => ({ success: true }) })+ useStore.setState({ workflows: [migrated('a'), migrated('b')], activeId: 'a' })++ await useStore.getState().remove('a')+ assert.deepEqual(useStore.getState().workflows.map((w) => w.id), ['b'])+ assert.equal(useStore.getState().activeId, null)+})++test('remove keeps activeId when a different workflow is deleted', async () => {+ const useStore = loadStore()+ stubBridge({ delete: async () => ({ success: true }) })+ useStore.setState({ workflows: [migrated('a'), migrated('b')], activeId: 'b' })++ await useStore.getState().remove('a')+ assert.equal(useStore.getState().activeId, 'b')+})++// ─── importFile() + setActive() ────────────────────────────────────────────────++test('importFile migrates, moves the workflow to the front, and makes it active', async () => {+ const useStore = loadStore()+ stubBridge({ import: async () => ({ success: true, workflow: legacyBlocks('imp') }) })+ useStore.setState({ workflows: [migrated('a')], activeId: 'a' })++ await useStore.getState().importFile()+ const { workflows, activeId } = useStore.getState()++ assert.deepEqual(workflows.map((w) => w.id), ['imp', 'a'])+ assert.equal(activeId, 'imp')+ assert.deepEqual(workflows[0].nodes.map((n) => n.type), ['inputNode', 'extensionNode'])+})++test('setActive updates only activeId', () => {+ const useStore = loadStore()+ stubBridge()+ useStore.setState({ workflows: [migrated('a')], activeId: null })++ useStore.getState().setActive('a')+ assert.equal(useStore.getState().activeId, 'a')+})diff --git a/apps/forge-desktop/src/shared/stores/workflowsStore.ts b/apps/forge-desktop/src/shared/stores/workflowsStore.tsnew file mode 100644index 000000000..f6fb829cc--- /dev/null+++ b/apps/forge-desktop/src/shared/stores/workflowsStore.ts@@ -0,0 +1,333 @@+import { create } from 'zustand'+import type { Workflow, WFNode, WFEdge } from '@shared/types/electron.d'++interface WorkflowsStore {+ workflows: Workflow[]+ loading: boolean+ activeId: string | null+ /** Workflows shown as tabs. Closing a tab only removes it here — the file stays on disk. */+ openIds: string[]+ /** Folder names for the workflow browser (workflows reference them via their `folder` field) */+ folders: string[]+ /** Folder name → display color (tab stripes + folder icons) */+ folderColors: Record<string, string>+ /** Folder names pinned to the top of the workflow browser */+ bookmarkedFolders: string[]++ load: () => Promise<void>+ save: (workflow: Workflow) => Promise<{ success: boolean; error?: string }>+ remove: (id: string) => Promise<{ success: boolean; error?: string }>+ importFile: () => Promise<{ success: boolean; error?: string; workflow?: Workflow }>+ exportFile: (workflow: Workflow) => Promise<{ success: boolean; error?: string }>+ setActive: (id: string | null) => void+ /** Add a workflow to the tab bar (if needed) and make it active. */+ openWorkflow: (id: string) => void+ /** Remove a workflow from the tab bar without deleting it. */+ closeWorkflow: (id: string) => void+ /** Reorder tabs: move dragId to targetId's position. */+ moveOpenTab: (dragId: string, targetId: string) => void+ /** Create a browser folder (kept even while empty; persisted in localStorage). */+ addFolder: (name: string) => void+ /** Remove a browser folder name (workflows inside must be moved out first by the caller). */+ removeFolder: (name: string) => void+ /** Set a folder's display color. */+ setFolderColor: (name: string, color: string) => void+ /** Pin/unpin a folder at the top of the workflow browser. */+ toggleFolderBookmark: (name: string) => void+}++/** Palette for folder colors (tab stripes / folder icons). */+export const FOLDER_COLORS = ['#38bdf8', '#34d399', '#fbbf24', '#f87171', '#a78bfa', '#f472b6', '#94a3b8']++// Empty folders have no workflow referencing them, so their names (and colors)+// are persisted separately in localStorage to survive reloads.+const FOLDERS_KEY = 'modly-workflow-folders'++function readStoredFolders(): { names: string[]; colors: Record<string, string>; bookmarked: string[] } {+ try {+ const raw = JSON.parse(localStorage.getItem(FOLDERS_KEY) ?? '[]')+ // Legacy format: plain array of names+ if (Array.isArray(raw)) {+ return { names: raw.filter((f): f is string => typeof f === 'string'), colors: {}, bookmarked: [] }+ }+ if (raw && typeof raw === 'object') {+ const names = Array.isArray(raw.names) ? raw.names.filter((f: unknown): f is string => typeof f === 'string') : []+ const colors = raw.colors && typeof raw.colors === 'object' ? raw.colors as Record<string, string> : {}+ const bookmarked = Array.isArray(raw.bookmarked) ? raw.bookmarked.filter((f: unknown): f is string => typeof f === 'string') : []+ return { names, colors, bookmarked }+ }+ return { names: [], colors: {}, bookmarked: [] }+ } catch {+ return { names: [], colors: {}, bookmarked: [] }+ }+}++function storeFolders(names: string[], colors: Record<string, string>, bookmarked: string[]): void {+ try { localStorage.setItem(FOLDERS_KEY, JSON.stringify({ names, colors, bookmarked })) } catch { /* quota/private mode */ }+}++/** Least-used palette color, so new folders spread across the palette. */+function nextFolderColor(colors: Record<string, string>): string {+ const used = Object.values(colors)+ return [...FOLDER_COLORS].sort((a, b) =>+ used.filter((c) => c === a).length - used.filter((c) => c === b).length,+ )[0]+}++// ─── Legacy migration ─────────────────────────────────────────────────────────++interface LegacyBlock {+ id: string+ extension: string+ enabled: boolean+ params: Record<string, unknown>+}++interface LegacyWorkflow {+ id: string+ name: string+ description: string+ input?: 'image' | 'text'+ blocks?: LegacyBlock[]+ nodes?: WFNode[]+ edges?: WFEdge[]+ createdAt: string+ updatedAt: string+}++// Source-only nodes have no target handle; sink-only nodes have no source handle.+// An edge into/out of the wrong side can't resolve a handle and makes React Flow+// warn ("Couldn't create edge for target handle id: null") on every render.+export const NODE_TYPES_WITHOUT_TARGET = new Set(['imageNode', 'textNode', 'meshNode', 'sceneNode', 'inputNode', 'forEachNode'])+export const NODE_TYPES_WITHOUT_SOURCE = new Set(['outputNode', 'previewNode'])++function sanitizeEdges(nodes: WFNode[], edges: WFEdge[]): WFEdge[] {+ const typeOf = new Map(nodes.map((n) => [n.id, n.type]))+ return edges+ .filter((e) => {+ const source = typeOf.get(e.source)+ const target = typeOf.get(e.target)+ if (!source || !target) return false // dangling endpoint+ if (NODE_TYPES_WITHOUT_TARGET.has(target)) return false // target can't receive+ if (NODE_TYPES_WITHOUT_SOURCE.has(source)) return false // source can't emit+ return true+ })+ .map((e) => {+ // ExtensionNodes use id'd handles (input-0 / output). Repair edges that lost+ // them (e.g. older palette auto-wiring) so React Flow can place them instead+ // of warning "Couldn't create edge for target handle id: null".+ const patch: Partial<WFEdge> = {}+ if (typeOf.get(e.target) === 'extensionNode' && e.targetHandle == null) patch.targetHandle = 'input-0'+ if (typeOf.get(e.source) === 'extensionNode' && e.sourceHandle == null) patch.sourceHandle = 'output'+ return Object.keys(patch).length ? { ...e, ...patch } : e+ })+}++function migrateWorkflow(raw: LegacyWorkflow): Workflow {+ // Already migrated+ if (raw.nodes && raw.edges) {+ return { ...raw, nodes: raw.nodes, edges: sanitizeEdges(raw.nodes, raw.edges) } as Workflow+ }++ // Migrate from old blocks format+ const blocks = raw.blocks ?? []+ const inputType = raw.input ?? 'image'++ const inputNode: WFNode = {+ id: 'input-' + raw.id,+ type: 'inputNode',+ position: { x: 250, y: 50 },+ data: { inputType, enabled: true, params: {} },+ }++ const extNodes: WFNode[] = blocks.map((b, i) => ({+ id: b.id,+ type: 'extensionNode',+ position: { x: 250, y: 150 + i * 220 },+ data: { extensionId: b.extension, enabled: b.enabled, params: b.params },+ }))++ const allNodes = [inputNode, ...extNodes]++ const edges: WFEdge[] = allNodes.slice(0, -1).map((n, i) => ({+ id: `e-${n.id}-${allNodes[i + 1].id}`,+ source: n.id,+ target: allNodes[i + 1].id,+ }))++ return {+ id: raw.id,+ name: raw.name,+ description: raw.description,+ nodes: allNodes,+ edges,+ createdAt: raw.createdAt,+ updatedAt: raw.updatedAt,+ }+}++// ─── Store ────────────────────────────────────────────────────────────────────++export const useWorkflowsStore = create<WorkflowsStore>((set) => ({+ workflows: [],+ loading: false,+ activeId: null,+ openIds: [],+ folders: readStoredFolders().names,+ folderColors: readStoredFolders().colors,+ bookmarkedFolders: readStoredFolders().bookmarked,++ async load() {+ set({ loading: true })+ try {+ const raw = await window.electron.workflows.list()+ // Dedupe by id: two files on disk can share an internal id (e.g. a copied+ // workflow), which would produce duplicate React keys. Keep the first+ // (the list arrives sorted by updatedAt desc, so the most recent wins).+ const seen = new Set<string>()+ const list: Workflow[] = []+ for (const entry of raw as LegacyWorkflow[]) {+ const wf = migrateWorkflow(entry)+ if (seen.has(wf.id)) continue+ seen.add(wf.id)+ list.push(wf)+ }+ set((s) => {+ // Keep already-open tabs that still exist; on a fresh session open the+ // most recent workflow (the list arrives sorted by updatedAt desc).+ const openIds = s.openIds.length > 0+ ? s.openIds.filter((id) => list.some((w) => w.id === id))+ : (list.length > 0 ? [list[0].id] : [])+ const activeId = s.activeId && openIds.includes(s.activeId) ? s.activeId : (openIds[0] ?? null)+ // Folders referenced by workflows always exist, even if localStorage was cleared+ const folders = [...new Set([...s.folders, ...list.map((w) => w.folder).filter((f): f is string => !!f)])]+ storeFolders(folders, s.folderColors, s.bookmarkedFolders)+ return { workflows: list, loading: false, openIds, activeId, folders }+ })+ } catch {+ set({ loading: false })+ }+ },++ async save(workflow) {+ const result = await window.electron.workflows.save(workflow)+ if (result.success) {+ set((s) => {+ const idx = s.workflows.findIndex((w) => w.id === workflow.id)+ if (idx === -1) return { workflows: [workflow, ...s.workflows] }+ const next = [...s.workflows]+ next[idx] = workflow+ return { workflows: next }+ })+ }+ return result+ },++ async remove(id) {+ const result = await window.electron.workflows.delete(id)+ if (result.success) {+ set((s) => {+ const openIds = s.openIds.filter((x) => x !== id)+ return {+ workflows: s.workflows.filter((w) => w.id !== id),+ openIds,+ activeId: s.activeId === id ? (openIds[0] ?? null) : s.activeId,+ }+ })+ }+ return result+ },++ async importFile() {+ const result = await window.electron.workflows.import()+ if (result.success && result.workflow) {+ const wf = migrateWorkflow(result.workflow as LegacyWorkflow)+ set((s) => {+ const filtered = s.workflows.filter((w) => w.id !== wf.id)+ return {+ workflows: [wf, ...filtered],+ openIds: s.openIds.includes(wf.id) ? s.openIds : [...s.openIds, wf.id],+ activeId: wf.id,+ }+ })+ }+ return result+ },++ async exportFile(workflow) {+ return window.electron.workflows.export(workflow)+ },++ setActive(id) {+ set({ activeId: id })+ },++ openWorkflow(id) {+ set((s) => ({+ openIds: s.openIds.includes(id) ? s.openIds : [...s.openIds, id],+ activeId: id,+ }))+ },++ closeWorkflow(id) {+ set((s) => {+ const idx = s.openIds.indexOf(id)+ const openIds = s.openIds.filter((x) => x !== id)+ // When closing the active tab, activate the nearest remaining neighbour+ const activeId = s.activeId === id+ ? (openIds[Math.min(Math.max(idx, 0), openIds.length - 1)] ?? null)+ : s.activeId+ return { openIds, activeId }+ })+ },++ moveOpenTab(dragId, targetId) {+ set((s) => {+ if (dragId === targetId || !s.openIds.includes(dragId)) return s+ const ids = s.openIds.filter((x) => x !== dragId)+ const idx = ids.indexOf(targetId)+ if (idx === -1) return s+ ids.splice(idx, 0, dragId)+ return { openIds: ids }+ })+ },++ addFolder(name) {+ set((s) => {+ if (s.folders.includes(name)) return s+ const folders = [...s.folders, name]+ const folderColors = { ...s.folderColors, [name]: nextFolderColor(s.folderColors) }+ storeFolders(folders, folderColors, s.bookmarkedFolders)+ return { folders, folderColors }+ })+ },++ removeFolder(name) {+ set((s) => {+ const folders = s.folders.filter((f) => f !== name)+ const folderColors = { ...s.folderColors }+ delete folderColors[name]+ const bookmarkedFolders = s.bookmarkedFolders.filter((f) => f !== name)+ storeFolders(folders, folderColors, bookmarkedFolders)+ return { folders, folderColors, bookmarkedFolders }+ })+ },++ setFolderColor(name, color) {+ set((s) => {+ const folderColors = { ...s.folderColors, [name]: color }+ storeFolders(s.folders, folderColors, s.bookmarkedFolders)+ return { folderColors }+ })+ },++ toggleFolderBookmark(name) {+ set((s) => {+ const bookmarkedFolders = s.bookmarkedFolders.includes(name)+ ? s.bookmarkedFolders.filter((f) => f !== name)+ : [...s.bookmarkedFolders, name]+ storeFolders(s.folders, s.folderColors, bookmarkedFolders)+ return { bookmarkedFolders }+ })+ },+}))diff --git a/apps/forge-desktop/src/shared/types/artifacts.ts b/apps/forge-desktop/src/shared/types/artifacts.tsnew file mode 100644index 000000000..57c6b8d4f--- /dev/null+++ b/apps/forge-desktop/src/shared/types/artifacts.ts@@ -0,0 +1,20 @@+export interface ArtifactProvenance {+ workflowId?: string+ workflowNodeId?: string+ source?: string+ [key: string]: unknown+}++export interface SceneArtifactManifestPreview { image?: string; video?: string }+export interface SceneArtifactManifestInitialView {+ position: [number, number, number]+ target: [number, number, number]+ up?: [number, number, number]+}+export interface SceneArtifactManifestV1 {+ schema: 'modly.scene-manifest.v1'+ sceneRoot: string+ assets: unknown[]+ preview?: SceneArtifactManifestPreview+ initialView?: SceneArtifactManifestInitialView+}diff --git a/apps/forge-desktop/src/shared/types/assetLibrary.test.ts b/apps/forge-desktop/src/shared/types/assetLibrary.test.tsnew file mode 100644index 000000000..8a6e7494d--- /dev/null+++ b/apps/forge-desktop/src/shared/types/assetLibrary.test.ts@@ -0,0 +1,126 @@+import assert from 'node:assert/strict'+import test from 'node:test'++import {+ ASSET_CAPABILITIES,+ ASSET_ENTRY_STATES,+ ASSET_LIBRARY_MANIFEST_CAPABILITIES,+ ASSET_LIBRARY_PREVIEW_KINDS,+ ASSET_LIBRARY_SOURCE_SCOPES,+} from './assetLibrary.ts'+import type {+ AssetLibraryEntry,+ AssetLibraryListResult,+ AssetLibraryOpenRequest,+ AssetLibraryReadResult,+ AssetLibrarySourceLink,+} from './assetLibrary.ts'++test('declares capability-first asset taxonomy without extension categories', () => {+ assert.deepEqual(ASSET_CAPABILITIES, [+ 'mesh',+ 'rigged-mesh',+ 'animation-motion',+ 'landmarks-sidecar',+ 'generated-world',+ 'scene-manifest',+ ])+ assert.deepEqual(ASSET_ENTRY_STATES, ['ready', 'unknown-metadata', 'unsupported', 'unsafe'])+ assert.deepEqual(ASSET_LIBRARY_PREVIEW_KINDS, ['3d-model', 'text', 'binary', 'none'])+ assert.deepEqual(ASSET_LIBRARY_SOURCE_SCOPES, ['workflows', 'exports'])+ assert.deepEqual(ASSET_LIBRARY_MANIFEST_CAPABILITIES, ['generated-world', 'scene-manifest'])+ assert.equal((ASSET_CAPABILITIES as readonly string[]).includes('glb'), false)+ assert.equal((ASSET_CAPABILITIES as readonly string[]).includes('splat'), false)+})++test('AssetLibraryEntry keeps capability, source scope, provenance, warnings, and openability explicit', () => {+ const entry = {+ id: 'library:Workflows/checkpoints/hero.glb',+ workspacePath: 'Workflows/checkpoints/hero.glb',+ displayName: 'hero.glb',+ sourceScope: 'workflows',+ capability: 'rigged-mesh',+ state: 'ready',+ previewKind: '3d-model',+ provenance: { workflowId: 'wf-1', workflowNodeId: 'node-1' },+ warnings: ['Rig metadata was inferred from a sidecar.'],+ openable: true,+ } satisfies AssetLibraryEntry++ const list = { success: true, entries: [entry] } satisfies AssetLibraryListResult+ assert.equal(list.entries[0]?.capability, 'rigged-mesh')+ assert.equal(list.entries[0]?.sourceScope, 'workflows')+ assert.equal(list.entries[0]?.provenance?.workflowId, 'wf-1')+ assert.equal(list.entries[0]?.warnings[0], 'Rig metadata was inferred from a sidecar.')+ assert.equal(list.entries[0]?.openable, true)+})++test('structured results preserve renderer-visible error codes and read previews', () => {+ const failure = {+ success: false,+ error: { code: 'unsafe-path', message: 'Workspace path escapes the allowed roots.' },+ } satisfies AssetLibraryListResult+ const read = {+ success: true,+ entry: {+ id: 'library:Exports/model.ply',+ workspacePath: 'Exports/model.ply',+ displayName: 'model.ply',+ sourceScope: 'exports',+ capability: 'mesh',+ state: 'ready',+ previewKind: 'binary',+ warnings: [],+ openable: false,+ nonOpenableReason: '.ply workspace assets are list-only in this release.',+ },+ preview: { kind: 'binary', byteLength: 12, binaryKind: 'ply', message: 'Binary preview is unavailable.' },+ } satisfies AssetLibraryReadResult++ assert.equal(failure.error.code, 'unsafe-path')+ assert.equal(read.preview.kind, 'binary')+ assert.equal(read.entry.openable, false)+})++test('AssetLibraryEntry carries library-owned source, manifest, artifact, version, and provenance metadata', () => {+ const source = {+ workspacePath: 'Workflows/checkpoints/hero.glb',+ displayName: 'hero.glb',+ role: 'source-mesh',+ } satisfies AssetLibrarySourceLink+ const entry = {+ id: 'library:Workflows/checkpoints/hero.landmarks.v1.json',+ workspacePath: 'Workflows/checkpoints/hero.landmarks.v1.json',+ displayName: 'hero.landmarks.v1.json',+ sourceScope: 'workflows',+ capability: 'landmarks-sidecar',+ state: 'ready',+ previewKind: 'text',+ source,+ manifest: {+ workspacePath: 'Workflows/checkpoints/hero.scene.json',+ capability: 'scene-manifest',+ },+ artifactId: 'artifact-hero',+ versionId: 'version-1',+ provenance: { workflowId: 'wf-1', workflowNodeId: 'node-1', source: 'library-sidecar' },+ warnings: [],+ openable: false,+ } satisfies AssetLibraryEntry++ assert.equal(entry.source?.workspacePath, 'Workflows/checkpoints/hero.glb')+ assert.equal(entry.manifest?.capability, 'scene-manifest')+ assert.equal(entry.artifactId, 'artifact-hero')+ assert.equal(entry.versionId, 'version-1')+ assert.equal(entry.provenance?.source, 'library-sidecar')+})++test('read and open requests can carry a sourceWorkspacePath for linked-source opens', () => {+ const request = {+ workspacePath: 'Workflows/checkpoints/hero.landmarks.v1.json',+ sourceWorkspacePath: 'Workflows/checkpoints/hero.glb',+ } satisfies AssetLibraryOpenRequest++ assert.equal(request.workspacePath, 'Workflows/checkpoints/hero.landmarks.v1.json')+ assert.equal(request.sourceWorkspacePath, 'Workflows/checkpoints/hero.glb')+})diff --git a/apps/forge-desktop/src/shared/types/assetLibrary.ts b/apps/forge-desktop/src/shared/types/assetLibrary.tsnew file mode 100644index 000000000..fb5a602d6--- /dev/null+++ b/apps/forge-desktop/src/shared/types/assetLibrary.ts@@ -0,0 +1,83 @@+import type { ArtifactProvenance } from './artifacts'++export const ASSET_CAPABILITIES = [+ 'mesh',+ 'rigged-mesh',+ 'animation-motion',+ 'landmarks-sidecar',+ 'generated-world',+ 'scene-manifest',+] as const++export const ASSET_ENTRY_STATES = ['ready', 'unknown-metadata', 'unsupported', 'unsafe'] as const+export const ASSET_LIBRARY_PREVIEW_KINDS = ['3d-model', 'text', 'binary', 'none'] as const+export const ASSET_LIBRARY_SOURCE_SCOPES = ['workflows', 'exports'] as const+export const ASSET_LIBRARY_MANIFEST_CAPABILITIES = ['generated-world', 'scene-manifest'] as const++export type AssetCapability = typeof ASSET_CAPABILITIES[number]+export type AssetEntryState = typeof ASSET_ENTRY_STATES[number]+export type AssetLibraryPreviewKind = typeof ASSET_LIBRARY_PREVIEW_KINDS[number]+export type AssetLibrarySourceScope = typeof ASSET_LIBRARY_SOURCE_SCOPES[number]+export type AssetLibraryManifestCapability = typeof ASSET_LIBRARY_MANIFEST_CAPABILITIES[number]++export interface AssetLibraryError {+ code: 'unsafe-path' | 'not-found' | 'not-openable' | 'read-failed' | 'list-failed' | 'invalid-request'+ message: string+}++export interface AssetLibraryEntry {+ id: string+ workspacePath: string+ displayName: string+ sourceScope: AssetLibrarySourceScope+ capability?: AssetCapability+ state: AssetEntryState+ previewKind: AssetLibraryPreviewKind+ source?: AssetLibrarySourceLink+ manifest?: AssetLibraryManifestRef+ artifactId?: string+ versionId?: string+ provenance?: ArtifactProvenance+ warnings: string[]+ openable: boolean+ nonOpenableReason?: string+ createdAt?: string+ updatedAt?: string+}++export interface AssetLibrarySourceLink {+ workspacePath: string+ displayName?: string+ role?: 'source-mesh' | 'source-artifact' | 'related-source'+}++export interface AssetLibraryManifestRef {+ workspacePath: string+ capability: AssetLibraryManifestCapability+}++export type AssetLibraryPreviewPayload =+ | { kind: '3d-model', viewerKind: 'glb' | 'gltf' }+ | { kind: 'text', content: string, byteLength: number, truncated: boolean }+ | { kind: 'binary', binaryKind: string, byteLength: number, message: string }+ | { kind: 'none' }++export interface AssetLibraryReadRequest {+ workspacePath: string+ sourceWorkspacePath?: string+}++export type AssetLibraryOpenRequest = AssetLibraryReadRequest+export type AssetLibraryListRequest = Record<string, never>++export type AssetLibraryListResult =+ | { success: true, entries: AssetLibraryEntry[] }+ | { success: false, error: AssetLibraryError }++export type AssetLibraryReadResult =+ | { success: true, entry: AssetLibraryEntry, preview: AssetLibraryPreviewPayload }+ | { success: false, error: AssetLibraryError }++export type AssetLibraryOpenResult =+ | { success: true, entry: AssetLibraryEntry }+ | { success: false, error: AssetLibraryError }diff --git a/apps/forge-desktop/src/shared/types/collections.ts b/apps/forge-desktop/src/shared/types/collections.tsnew file mode 100644index 000000000..e7b70f292--- /dev/null+++ b/apps/forge-desktop/src/shared/types/collections.ts@@ -0,0 +1,8 @@+import type { GenerationJob } from '@shared/stores/appStore'++export interface Collection {+ id: string+ name: string+ createdAt: number+ jobs: GenerationJob[]+}diff --git a/apps/forge-desktop/src/shared/types/electron.d.ts b/apps/forge-desktop/src/shared/types/electron.d.tsnew file mode 100644index 000000000..c171b6648--- /dev/null+++ b/apps/forge-desktop/src/shared/types/electron.d.ts@@ -0,0 +1,368 @@+// Type declarations for the Electron API exposed via preload+export {}++import type {+ AssetLibraryListResult,+ AssetLibraryOpenRequest,+ AssetLibraryOpenResult,+ AssetLibraryReadRequest,+ AssetLibraryReadResult,+} from './assetLibrary'++// ─── Extension types ──────────────────────────────────────────────────────────++export interface ExtensionNode {+ id: string+ name: string+ input: 'image' | 'text' | 'mesh' | 'audio' | 'scene'+ inputs?: ('image' | 'text' | 'mesh' | 'audio' | 'scene')[] // multi-input nodes; overrides input when set+ inputLabels?: string[] // display labels per input slot (e.g. positive/negative)+ output: 'image' | 'text' | 'mesh' | 'audio' | 'scene'+ paramsSchema: ParamSchema[]+ paramDefaults?: Record<string, number | string>+ hfRepo?: string+ downloadCheck?: string+ hfSkipPrefixes?: string[]+ hfIncludePrefixes?: string[]+ hasModelSources?: boolean+ weightGroups?: string[]+ weightVariants?: WeightVariantsInfo+}++export interface WeightVariantsInfo {+ param: string // params_schema id whose value selects the variant+ default: string+ options: { id: string; label: string; sizeGb?: number; vramGb?: number }[]+}++export interface SharedWeightGroup {+ id: string+ dependentNodeIds: string[]+}++export interface ModelExtension {+ type: 'model'+ id: string+ name: string+ version?: string+ description?: string+ author?: string+ trusted: boolean+ builtin: boolean+ source?: string+ localPath?: string+ nodes: ExtensionNode[]+ weightGroups?: SharedWeightGroup[]+ /** Folder exists but is not a loadable extension — see manifestError */+ corrupted?: boolean+ /** Why the folder is corrupted: manifest gone, manifest unparseable, or install never completed */+ manifestError?: 'missing' | 'invalid' | 'incomplete'+}++export type PickerIntent = 'folder' | 'image' | 'mesh' | 'text'++export interface ParamSchema {+ id: string+ label: string+ type: 'select' | 'int' | 'float' | 'string' | 'file-select'+ default: number | string+ options?: { value: number | string; label: string }[]+ min?: number+ max?: number+ step?: number+ tooltip?: string+ show_if?: Record<string, string | number | (string | number)[]>+ // string: which native dialog the browse button opens (default: 'folder')+ pickerIntent?: PickerIntent+ /** snake_case alias of pickerIntent, for manifests that follow show_if/dir_from. */+ picker_intent?: PickerIntent+ // file-select: dropdown of the files inside the folder held by another param+ dir_from?: string // id of the (string) param holding the folder path+ extensions?: string[] // file extensions to list (e.g. ["json"])+}++export interface ProcessExtension {+ type: 'process'+ id: string+ name: string+ version?: string+ description?: string+ author?: string+ trusted: boolean+ builtin: boolean+ source?: string+ localPath?: string+ entry: string+ nodes: ExtensionNode[]+ /** Folder exists but is not a loadable extension — see manifestError */+ corrupted?: boolean+ /** Why the folder is corrupted: manifest gone, manifest unparseable, or install never completed */+ manifestError?: 'missing' | 'invalid' | 'incomplete'+}++export type AnyExtension = ModelExtension | ProcessExtension++// ─── Process runner types ─────────────────────────────────────────────────────++export interface ProcessInput {+ filePath?: string+ text?: string+ /** Per-slot texts for multi-text-input nodes (index = target handle slot). */+ texts?: (string | undefined)[]+ nodeId?: string+}++export interface ProcessResult {+ filePath?: string+ text?: string+}++export interface WFNodeData {+ extensionId?: string+ inputType?: 'image' | 'text'+ enabled: boolean+ showInGenerate?: boolean+ iterations?: number // While container: auto-loop N times (omit/0 = manual only)+ params: Record<string, unknown>+ // React Flow requires node data to satisfy Record<string, unknown>.+ [key: string]: unknown+}++export interface WFNode {+ id: string+ type: string+ position: { x: number; y: number }+ data: WFNodeData+ // Sub-flow / group support (While container)+ parentId?: string+ extent?: 'parent'+ width?: number+ height?: number+ style?: Record<string, unknown>+}++export interface WFEdge {+ id: string+ source: string+ target: string+ sourceHandle?: string | null+ targetHandle?: string | null+}++export interface Workflow {+ id: string+ name: string+ description: string+ /** Display folder in the workflow browser (no folder = root) */+ folder?: string+ /** Pinned in the workflow browser's Bookmarks section */+ bookmarked?: boolean+ nodes: WFNode[]+ edges: WFEdge[]+ createdAt: string+ updatedAt: string+}++declare global {+ interface Window {+ electron: {+ shell: {+ openExternal: (url: string) => Promise<void>+ }+ slicer: {+ open: (url: string) => Promise<{ success: boolean; error?: string }>+ }+ system: {+ memory: () => Promise<{ total: number; used: number; available: number }>+ }+ window: {+ minimize: () => void+ maximize: () => void+ close: () => void+ isMaximized: () => Promise<boolean>+ onMaximizeChange: (cb: (isMaximized: boolean) => void) => void+ offMaximizeChange: () => void+ }+ notifications: {+ show: (title: string, body: string) => Promise<{ success: boolean; error?: string }>+ }+ ui: {+ setZoomFactor: (factor: number) => void+ }+ python: {+ start: () => Promise<{ success: boolean; port?: number; error?: string }>+ status: () => Promise<{ ready: boolean; apiUrl: string }>+ onCrashed: (cb: (data: { code: number | null }) => void) => void+ offCrashed: () => void+ onLog: (cb: (line: string) => void) => void+ offLog: () => void+ }+ fs: {+ getPathForFile: (file: File) => string+ selectImage: () => Promise<string | null>+ selectMeshFile: () => Promise<string | null>+ saveModel: (defaultName: string) => Promise<string | null>+ readFileBase64: (filePath: string) => Promise<string>+ selectDirectory: (defaultPath?: string) => Promise<string | null>+ savePath: (args: { filters: { name: string; extensions: string[] }[]; defaultPath?: string }) => Promise<string | null>+ listDir: (dirPath: string) => Promise<string[]>+ listFiles: (dirPath: string, extensions?: string[]) => Promise<string[]>+ selectTextFile: () => Promise<string | null>+ moveDirectory: (args: { src: string; dest: string }) => Promise<{ success: boolean; error?: string }>+ deleteDirectory: (dirPath: string) => Promise<{ success: boolean; error?: string }>+ readScreenshotDataUrl: (filename: string) => Promise<string>+ }+ settings: {+ get: () => Promise<{ modelsDir: string; workspaceDir: string; workflowsDir: string; extensionsDir: string; hfToken?: string }>+ set: (patch: { modelsDir?: string; workspaceDir?: string; workflowsDir?: string; extensionsDir?: string; hfToken?: string }) => Promise<{ modelsDir: string; workspaceDir: string; workflowsDir: string; extensionsDir: string; hfToken?: string }>+ }+ /** decrypt returns null when the stored blob can't be decrypted here. */+ secureStore: {+ encrypt: (plainText: string) => Promise<string>+ decrypt: (stored: string) => Promise<string | null>+ }+ agent: {+ /** Opens a file picker and copies the chosen .gguf into the agent's models folder. */+ addModel: () => Promise<{ success: boolean; cancelled?: boolean; fileName?: string; error?: string }>+ }+ cache: {+ clear: () => Promise<{ success: boolean; error?: string }>+ }+ api: {+ updatePaths: (patch: { modelsDir?: string; workspaceDir?: string; extensionsDir?: string }) => Promise<{ success: boolean; error?: string }>+ }+ model: {+ export: (args: { outputUrl: string; format: string }) => Promise<{ success: boolean; error?: string }>+ listDownloaded: () => Promise<{ id: string; name: string; size_gb: number }[]>+ activeDownloads: () => Promise<{ modelId: string; variantId?: string; percent: number; file?: string; fileIndex?: number; totalFiles?: number }[]>+ isDownloaded: (modelId: string) => Promise<boolean>+ hasLocalData: (modelId: string) => Promise<boolean>+ sharedGroups: (extensionId: string) => Promise<SharedWeightGroupState[]>+ download: (modelId: string, variantId?: string) => Promise<{ success: boolean; error?: string; paused?: boolean; cancelled?: boolean }>+ pauseDownload: (modelId: string) => Promise<{ success: boolean; error?: string }>+ cancelDownload: (modelId: string) => Promise<{ success: boolean; error?: string }>+ delete: (modelId: string) => Promise<{ success: boolean; error?: string }>+ deleteSharedGroup: (extensionId: string, groupId: string) => Promise<{ success: boolean; error?: string }>+ deleteExtensionWeights: (extensionId: string) => Promise<{ success: boolean; error?: string }>+ /** Installed variant ids, or null when the node's install state could not be read */+ installedWeightVariants: (modelId: string) => Promise<string[] | null>+ deleteWeightVariant: (modelId: string, variantId: string) => Promise<{ success: boolean; error?: string }>+ unloadAll: () => Promise<{ success: boolean; error?: string }>+ showInFolder: (modelId: string) => Promise<void>+ onProgress: (cb: (data: {+ modelId: string+ variantId?: string+ percent: number+ file?: string+ fileIndex?: number+ totalFiles?: number+ status?: string+ bytesDownloaded?: number+ totalBytes?: number+ stalledSeconds?: number+ paused?: boolean+ cancelled?: boolean+ }) => void) => void+ offProgress: () => void+ onWeightsChanged: (cb: () => void) => void+ offWeightsChanged: () => void+ }+ app: {+ info: () => Promise<{+ version: string+ userData: string+ modelsDir: string+ apiUrl: string+ platform: string+ arch: string+ }>+ onError: (cb: (message: string) => void) => void+ offError: () => void+ }+ log: {+ error: (message: string) => void+ getPath: () => Promise<string>+ readAll: (session?: string) => Promise<Record<string, string>>+ listSessions: () => Promise<string[]>+ }+ workspace: {+ listCollections: () => Promise<string[]>+ createCollection: (name: string) => Promise<void>+ renameCollection: (oldName: string, newName: string) => Promise<void>+ deleteCollection: (name: string) => Promise<void>+ listJobs: (collection: string) => Promise<unknown[]>+ saveJobMeta: (collection: string, filename: string, meta: unknown) => Promise<void>+ deleteJob: (collection: string, filename: string) => Promise<void>+ library: {+ list: () => Promise<AssetLibraryListResult>+ read: (request: AssetLibraryReadRequest) => Promise<AssetLibraryReadResult>+ open: (request: AssetLibraryOpenRequest) => Promise<AssetLibraryOpenResult>+ }+ }+ setup: {+ check: () => Promise<{ needed: boolean; defaultDataDir: string; platform: string; arch: string }>+ run: () => Promise<{ success: boolean; error?: string }>+ saveDataDir: (baseDir: string) => Promise<void>+ onProgress: (cb: (data: { step: string; percent: number; currentPackage?: string }) => void) => void+ offProgress: () => void+ onComplete: (cb: () => void) => void+ offComplete: () => void+ onError: (cb: (data: { message: string }) => void) => void+ offError: () => void+ }+ workflows: {+ list: () => Promise<Workflow[]>+ save: (workflow: Workflow) => Promise<{ success: boolean; error?: string }>+ delete: (id: string) => Promise<{ success: boolean; error?: string }>+ import: () => Promise<{ success: boolean; error?: string; workflow?: Workflow }>+ export: (workflow: Workflow) => Promise<{ success: boolean; error?: string }>+ }+ updater: {+ check: () => Promise<{ success: boolean }>+ quitAndInstall: () => Promise<void>+ onApplying: (cb: (data: { version: string }) => void) => void+ offApplying: () => void+ onMajorMinorAvailable: (cb: (data: { version: string }) => void) => void+ offMajorMinorAvailable: () => void+ }+ extensions: {+ list: () => Promise<AnyExtension[]>+ installFromGitHub: (url: string) => Promise<{+ success: boolean+ error?: string+ cancelled?: boolean+ extensionId?: string+ extension?: AnyExtension+ }>+ installFromLocal: () => Promise<{+ success: boolean+ error?: string+ cancelled?: boolean+ needsRepair?: boolean+ extensionId?: string+ extension?: AnyExtension+ localPath?: string+ }>+ uninstall: (extensionId: string) => Promise<{ success: boolean; error?: string }>+ repair: (extensionId: string) => Promise<{ success: boolean; error?: string }>+ reload: () => Promise<{ success: boolean; error?: string; errors?: Record<string, string> }>+ runProcess: (extensionId: string, input: ProcessInput, params: Record<string, unknown>) => Promise<{ success: boolean; result?: ProcessResult; error?: string }>+ onInstallProgress: (cb: (data: {+ step: 'downloading' | 'extracting' | 'validating' | 'setting_up' | 'done' | 'error'+ percent?: number+ extensionId?: string+ message?: string+ }) => void) => void+ offInstallProgress: () => void+ }+ }+ }+}++export interface SharedWeightGroupState {+ id: string+ targetId: string+ dependentModelIds: string[]+ downloaded: boolean+ hasLocalData: boolean+}diff --git a/apps/forge-desktop/src/shared/types/gaussian-splats-3d.d.ts b/apps/forge-desktop/src/shared/types/gaussian-splats-3d.d.tsnew file mode 100644index 000000000..292e935d8--- /dev/null+++ b/apps/forge-desktop/src/shared/types/gaussian-splats-3d.d.ts@@ -0,0 +1,3 @@+// The package ships a UMD bundle (gaussian-splats-3d.umd.cjs) without type+// declarations. Declare it as an untyped module so the renderer type-checks.+declare module '@mkkellogg/gaussian-splats-3d'diff --git a/apps/forge-desktop/src/shared/ui/index.tsx b/apps/forge-desktop/src/shared/ui/index.tsxnew file mode 100644index 000000000..a2c6c1812--- /dev/null+++ b/apps/forge-desktop/src/shared/ui/index.tsx@@ -0,0 +1,166 @@+import React from 'react'++export function Section({ title, subtitle, children }: { title: string; subtitle: string; children: React.ReactNode }): JSX.Element {+ return (+ <div>+ <div className="mb-7">+ <h2 className="text-2xl font-bold text-zinc-100">{title}</h2>+ <p className="text-sm text-zinc-500 mt-1">{subtitle}</p>+ </div>+ {children}+ </div>+ )+}++export function Card({ title, description, aside, children }: {+ title?: string+ description?: React.ReactNode+ /** Rendered at the right of the header (status badge, …). */+ aside?: React.ReactNode+ children: React.ReactNode+}): JSX.Element {+ return (+ <div className="rounded-xl bg-surface-300 border border-zinc-800 overflow-hidden">+ {(title || description || aside) && (+ <div className="px-4 py-3 border-b border-zinc-800/80 flex items-start justify-between gap-4">+ <div className="min-w-0">+ {title && <p className="text-xs font-semibold text-zinc-200">{title}</p>}+ {description && <p className="text-[11px] text-zinc-500 mt-0.5">{description}</p>}+ </div>+ {aside && <div className="shrink-0">{aside}</div>}+ </div>+ )}+ <div className="divide-y divide-zinc-800/60">+ {children}+ </div>+ </div>+ )+}++export function Row({ label, description, children }: { label: string; description?: string; children: React.ReactNode }): JSX.Element {+ return (+ <div className="flex items-center justify-between gap-4 px-4 py-3">+ <div className="min-w-0">+ <p className="text-xs font-medium text-zinc-300">{label}</p>+ {description && <p className="text-[11px] text-zinc-500 mt-0.5">{description}</p>}+ </div>+ <div className="shrink-0">{children}</div>+ </div>+ )+}++export function PathRow({ label, description, value, onBrowse }: {+ label: string+ description?: string+ value: string+ onBrowse?: () => void+}): JSX.Element {+ return (+ <div className="px-4 py-3">+ <div className="flex items-center justify-between mb-2">+ <div>+ <p className="text-xs font-medium text-zinc-300">{label}</p>+ {description && <p className="text-[11px] text-zinc-500 mt-0.5">{description}</p>}+ </div>+ {onBrowse && (+ <button+ onClick={onBrowse}+ className="px-2.5 py-1 rounded-md text-[11px] font-medium bg-zinc-800 hover:bg-zinc-700 text-zinc-300 transition-colors shrink-0 ml-4"+ >+ Browse…+ </button>+ )}+ </div>+ <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-surface-500 border border-zinc-800">+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="text-zinc-600 shrink-0">+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z" />+ </svg>+ <span className="text-[11px] text-zinc-500 truncate font-mono">{value}</span>+ </div>+ </div>+ )+}++export function InfoRow({ label, value }: { label: string; value: string }): JSX.Element {+ return (+ <div className="flex items-center justify-between px-4 py-3">+ <p className="text-xs font-medium text-zinc-300">{label}</p>+ <span className="text-xs text-zinc-500 font-mono">{value}</span>+ </div>+ )+}++export function Toggle({ value, onChange }: { value: boolean; onChange: (v: boolean) => void }): JSX.Element {+ return (+ <button+ onClick={() => onChange(!value)}+ className={`relative w-9 h-5 rounded-full transition-colors duration-200 shrink-0 ${value ? 'bg-accent' : 'bg-zinc-700'}`}+ >+ <span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white shadow-sm transition-transform duration-200 ${value ? 'translate-x-4' : 'translate-x-0'}`} />+ </button>+ )+}++export function Select({ value, onChange, options }: {+ value: string+ onChange: (v: string) => void+ options: { value: string; label: string }[]+}): JSX.Element {+ return (+ <select+ value={value}+ onChange={(e) => onChange(e.target.value)}+ className="bg-zinc-800 border border-zinc-700 text-zinc-300 text-xs rounded-lg px-2.5 py-1.5 focus:outline-none focus:border-accent/50 cursor-pointer"+ >+ {options.map((o) => (+ <option key={o.value} value={o.value}>{o.label}</option>+ ))}+ </select>+ )+}++export function SegmentedControl<T extends string>({ value, onChange, options, ariaLabel }: {+ value: T+ onChange: (v: T) => void+ options: { value: T; label: string }[]+ ariaLabel?: string+}): JSX.Element {+ return (+ <div role="group" aria-label={ariaLabel} className="inline-flex p-0.5 rounded-lg bg-zinc-800 border border-zinc-700">+ {options.map((o) => {+ const active = o.value === value+ return (+ <button+ key={o.value}+ type="button"+ aria-pressed={active}+ onClick={() => onChange(o.value)}+ className={`px-3 py-1 rounded-md text-xs font-medium transition-colors ${+ active+ ? 'bg-accent/20 text-accent-light'+ : 'text-zinc-400 hover:text-zinc-200'+ }`}+ >+ {o.label}+ </button>+ )+ })}+ </div>+ )+}++export function LinkButton({ label, href }: { label: string; href?: string }): JSX.Element {+ const handleClick = (): void => {+ if (href) window.open(href, '_blank')+ }+ return (+ <button onClick={handleClick} className="flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-medium bg-zinc-800 hover:bg-zinc-700 text-zinc-300 transition-colors">+ {label}+ <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-zinc-500">+ <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />+ <polyline points="15 3 21 3 21 9" />+ <line x1="10" y1="14" x2="21" y2="3" />+ </svg>+ </button>+ )+}diff --git a/apps/forge-desktop/src/shared/utils/format.test.mjs b/apps/forge-desktop/src/shared/utils/format.test.mjsnew file mode 100644index 000000000..7fa3fb8d7--- /dev/null+++ b/apps/forge-desktop/src/shared/utils/format.test.mjs@@ -0,0 +1,62 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++// format.ts has no imports — bundle it straight to CJS and require.+function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-format-test-')), 'format.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('src/shared/utils/format.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++const { formatBytes, formatPoly, formatTime, formatDate } = loadModule()++// ─── formatBytes ───────────────────────────────────────────────────────────────++test('formatBytes picks the GB/MB/KB tier and rounds', () => {+ assert.equal(formatBytes(1.2e9), '1.2 GB')+ assert.equal(formatBytes(1e9), '1.0 GB') // exact GB boundary+ assert.equal(formatBytes(5e8), '500 MB')+ assert.equal(formatBytes(1e6), '1 MB') // exact MB boundary+ assert.equal(formatBytes(128e3), '128 KB')+ assert.equal(formatBytes(0), '0 KB')+})++// ─── formatPoly ────────────────────────────────────────────────────────────────++test('formatPoly abbreviates millions/thousands and leaves small counts raw', () => {+ assert.equal(formatPoly(1_500_000), '1.5M')+ assert.equal(formatPoly(1_000_000), '1.0M') // exact M boundary+ assert.equal(formatPoly(10_500), '10.5k')+ assert.equal(formatPoly(1_000), '1.0k') // exact k boundary+ assert.equal(formatPoly(999), '999') // just below k+ assert.equal(formatPoly(0), '0')+})++// ─── formatTime / formatDate (locale/TZ-robust: assert shape, not exact text) ───++test('formatTime returns an hour:minute-ish string', () => {+ assert.match(formatTime(Date.parse('2025-03-08T14:32:00')), /\d/)+})++test('formatDate labels today and yesterday, and shows the year for old dates', () => {+ const now = Date.now()+ assert.equal(formatDate(now), 'Today')+ assert.equal(formatDate(now - 24 * 60 * 60 * 1000), 'Yesterday')++ const old = new Date()+ old.setFullYear(old.getFullYear() - 2)+ assert.match(formatDate(old.getTime()), new RegExp(String(old.getFullYear())))+})diff --git a/apps/forge-desktop/src/shared/utils/format.ts b/apps/forge-desktop/src/shared/utils/format.tsnew file mode 100644index 000000000..5530966d5--- /dev/null+++ b/apps/forge-desktop/src/shared/utils/format.ts@@ -0,0 +1,31 @@+/** Format a byte count → "1.2 GB", "512 MB", "128 KB" */+export function formatBytes(bytes: number): string {+ if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`+ if (bytes >= 1e6) return `${Math.round(bytes / 1e6)} MB`+ return `${Math.round(bytes / 1e3)} KB`+}++/** Format a polygon/vertex count → "1.5M", "10.5k", "500" */+export function formatPoly(count: number): string {+ if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`+ if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k`+ return String(count)+}++/** Format a timestamp → "14:32" */+export function formatTime(ts: number): string {+ return new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })+}++/** Format a timestamp → "Today", "Yesterday", "Mar 8", "Mar 8, 2025" */+export function formatDate(ts: number): string {+ const d = new Date(ts)+ const today = new Date()+ const yesterday = new Date(today)+ yesterday.setDate(today.getDate() - 1)+ if (d.toDateString() === today.toDateString()) return 'Today'+ if (d.toDateString() === yesterday.toDateString()) return 'Yesterday'+ const opts: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric' }+ if (d.getFullYear() !== today.getFullYear()) opts.year = 'numeric'+ return d.toLocaleDateString([], opts)+}diff --git a/apps/forge-desktop/src/shared/utils/notification.ts b/apps/forge-desktop/src/shared/utils/notification.tsnew file mode 100644index 000000000..e51799740--- /dev/null+++ b/apps/forge-desktop/src/shared/utils/notification.ts@@ -0,0 +1,25 @@+/**+ * Native OS notification (Windows toast / macOS Notification Center / Linux) for+ * events worth surfacing even when the user isn't looking at the app — e.g. a+ * generation or workflow run finishing while they're in another window. Plays+ * each platform's own default notification sound (the toast isn't `silent`).+ *+ * Skipped when the app window already has focus: the user is looking right at+ * it, so a toast on top would just be noise.+ */+async function notifyIfUnfocused(title: string, body: string): Promise<void> {+ if (typeof document !== 'undefined' && document.hasFocus()) return+ try {+ await window.electron.notifications.show(title, body)+ } catch {+ // Notifications not available (e.g. unsupported platform)+ }+}++export function showCompletionNotification(body: string, title = 'Modly'): Promise<void> {+ return notifyIfUnfocused(title, body)+}++export function showErrorNotification(body: string, title = 'Modly'): Promise<void> {+ return notifyIfUnfocused(title, body)+}diff --git a/apps/forge-desktop/src/shared/utils/paramPicker.test.mjs b/apps/forge-desktop/src/shared/utils/paramPicker.test.mjsnew file mode 100644index 000000000..5c975705d--- /dev/null+++ b/apps/forge-desktop/src/shared/utils/paramPicker.test.mjs@@ -0,0 +1,103 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++// paramPicker.ts only type-imports from electron.d, so esbuild erases it.+function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-parampicker-test-')), 'paramPicker.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('src/shared/utils/paramPicker.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++const { resolvePickerIntent, openParamPicker, PICKER_LABELS } = loadModule()++/** Records which dialog was opened; each returns a path unique to that dialog. */+function fakeFs() {+ const calls = []+ return {+ calls,+ selectDirectory: () => { calls.push('selectDirectory'); return Promise.resolve('C:\\picked\\folder') },+ selectImage: () => { calls.push('selectImage'); return Promise.resolve('C:\\picked\\front.png') },+ selectMeshFile: () => { calls.push('selectMeshFile'); return Promise.resolve('C:\\picked\\model.glb') },+ selectTextFile: () => { calls.push('selectTextFile'); return Promise.resolve('C:\\picked\\notes.txt') },+ }+}++const stringParam = (extra) => ({ id: 'front_image_path', label: 'Front image', type: 'string', default: '', ...extra })++// ─── resolvePickerIntent ───────────────────────────────────────────────────────++test('resolvePickerIntent honors pickerIntent and its snake_case alias', () => {+ assert.equal(resolvePickerIntent(stringParam({ pickerIntent: 'image' })), 'image')+ assert.equal(resolvePickerIntent(stringParam({ pickerIntent: 'mesh' })), 'mesh')+ assert.equal(resolvePickerIntent(stringParam({ pickerIntent: 'text' })), 'text')+ assert.equal(resolvePickerIntent(stringParam({ picker_intent: 'image' })), 'image')+})++test('resolvePickerIntent falls back to the folder picker when unset or unknown', () => {+ assert.equal(resolvePickerIntent(stringParam()), 'folder') // pre-existing manifests+ assert.equal(resolvePickerIntent(stringParam({ pickerIntent: 'folder' })), 'folder')+ assert.equal(resolvePickerIntent(stringParam({ pickerIntent: 'hologram' })), 'folder') // newer manifest, older app+ assert.equal(resolvePickerIntent(undefined), 'folder')+})++// ─── openParamPicker ───────────────────────────────────────────────────────────++test('openParamPicker opens the image dialog for pickerIntent: image — issue #155', async () => {+ const fs = fakeFs()+ const picked = await openParamPicker(stringParam({ pickerIntent: 'image' }), fs)++ assert.deepEqual(fs.calls, ['selectImage']) // and *not* selectDirectory+ assert.equal(picked, 'C:\\picked\\front.png')+})++test('openParamPicker routes mesh/text intents to their existing dialogs', async () => {+ const mesh = fakeFs()+ assert.equal(await openParamPicker(stringParam({ pickerIntent: 'mesh' }), mesh), 'C:\\picked\\model.glb')+ assert.deepEqual(mesh.calls, ['selectMeshFile'])++ const text = fakeFs()+ assert.equal(await openParamPicker(stringParam({ picker_intent: 'text' }), text), 'C:\\picked\\notes.txt')+ assert.deepEqual(text.calls, ['selectTextFile'])+})++test('openParamPicker keeps the folder dialog when no intent is declared', async () => {+ const fs = fakeFs()+ assert.equal(await openParamPicker(stringParam(), fs), 'C:\\picked\\folder')+ assert.deepEqual(fs.calls, ['selectDirectory'])+})++test('PICKER_LABELS names every intent, so the browse button always has an accessible name', () => {+ for (const intent of ['folder', 'image', 'mesh', 'text']) {+ assert.equal(typeof PICKER_LABELS[intent], 'string')+ assert.ok(PICKER_LABELS[intent].length > 0)+ }+})++// ─── Call sites ────────────────────────────────────────────────────────────────+// The bug in #155 was not in a resolver (there wasn't one) — it was the string+// param's browse button calling selectDirectory() unconditionally. There is no+// DOM harness in this repo, so guard the wiring at the source level instead.++for (const file of [+ 'src/areas/workflows/nodes/ExtensionNode.tsx',+ 'src/areas/generate/components/WorkflowPanel.tsx',+]) {+ test(`${file} routes its string param browse button through openParamPicker`, () => {+ const src = readFileSync(resolve(file), 'utf8')+ assert.match(src, /openParamPicker\(param, window\.electron\.fs\)/)+ assert.doesNotMatch(src, /const p = await window\.electron\.fs\.selectDirectory\(\)/)+ })+}diff --git a/apps/forge-desktop/src/shared/utils/paramPicker.ts b/apps/forge-desktop/src/shared/utils/paramPicker.tsnew file mode 100644index 000000000..7e3a19741--- /dev/null+++ b/apps/forge-desktop/src/shared/utils/paramPicker.ts@@ -0,0 +1,45 @@+import type { ParamSchema, PickerIntent } from '@shared/types/electron.d'++// Which native dialog the browse button next to a `string` param opens.+// Extension manifests request one with `pickerIntent` (or `picker_intent`) on+// the param; params that don't set it keep the historical folder picker.++export const PICKER_INTENTS = ['folder', 'image', 'mesh', 'text'] as const++/** Accessible name / tooltip for the browse button, per intent. */+export const PICKER_LABELS: Record<PickerIntent, string> = {+ folder: 'Browse for a folder…',+ image: 'Browse for an image file…',+ mesh: 'Browse for a 3D mesh file…',+ text: 'Browse for a text file…',+}++/** Just the members of `window.electron.fs` a param picker can reach for. */+export interface ParamPickerApi {+ selectDirectory: (defaultPath?: string) => Promise<string | null>+ selectImage: () => Promise<string | null>+ selectMeshFile: () => Promise<string | null>+ selectTextFile: () => Promise<string | null>+}++type PickerParam = Pick<ParamSchema, 'pickerIntent' | 'picker_intent'>++/**+ * Intent a param asks for, falling back to 'folder' — the behavior every+ * `string` param had before `pickerIntent` existed — when it is unset or is a+ * value this build doesn't know about.+ */+export function resolvePickerIntent(param: PickerParam | undefined): PickerIntent {+ const requested = param?.pickerIntent ?? param?.picker_intent+ return PICKER_INTENTS.includes(requested as PickerIntent) ? (requested as PickerIntent) : 'folder'+}++/** Opens the dialog the param asked for. Resolves to null when cancelled. */+export function openParamPicker(param: PickerParam | undefined, fs: ParamPickerApi): Promise<string | null> {+ switch (resolvePickerIntent(param)) {+ case 'image': return fs.selectImage()+ case 'mesh': return fs.selectMeshFile()+ case 'text': return fs.selectTextFile()+ default: return fs.selectDirectory()+ }+}diff --git a/apps/forge-desktop/src/shared/utils/weightVariants.test.mjs b/apps/forge-desktop/src/shared/utils/weightVariants.test.mjsnew file mode 100644index 000000000..1659391b4--- /dev/null+++ b/apps/forge-desktop/src/shared/utils/weightVariants.test.mjs@@ -0,0 +1,63 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { buildSync } from 'esbuild'+import { createRequire } from 'node:module'+import { mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++function loadModule() {+ const outfile = join(mkdtempSync(join(tmpdir(), 'modly-weight-variants-test-')), 'weightVariants.cjs')+ const require = createRequire(import.meta.url)+ const result = buildSync({+ entryPoints: [resolve('src/shared/utils/weightVariants.ts')],+ bundle: true,+ platform: 'node',+ format: 'cjs',+ write: false,+ })+ writeFileSync(outfile, result.outputFiles[0].text, 'utf8')+ return require(outfile)+}++const { withWeightVariantAvailability, isMissingWeightVariant } = loadModule()++const variants = {+ param: 'gguf_quant',+ default: 'Q5_K_M',+ options: [{ id: 'Q4_K_M', label: 'Q4_K_M' }, { id: 'Q5_K_M', label: 'Q5_K_M' }],+}++const quantParam = {+ id: 'gguf_quant',+ label: 'Quantization',+ type: 'select',+ default: 'Q5_K_M',+ options: [+ { value: 'Q4_K_M', label: 'Q4_K_M' },+ { value: 'Q5_K_M', label: 'Q5_K_M' },+ { value: 'auto', label: 'Auto' },+ ],+}++test('labels declared variants that are not installed and keeps their values', () => {+ const marked = withWeightVariantAvailability(quantParam, variants, ['Q5_K_M'])+ assert.deepEqual(marked.options.map((option) => option.label), ['Q4_K_M (not installed)', 'Q5_K_M', 'Auto'])+ assert.deepEqual(marked.options.map((option) => option.value), ['Q4_K_M', 'Q5_K_M', 'auto'])+})++test('returns the param untouched when availability is unknown or the param selects nothing', () => {+ assert.equal(withWeightVariantAvailability(quantParam, variants, undefined), quantParam)+ assert.equal(withWeightVariantAvailability(quantParam, undefined, []), quantParam)+ const steps = { id: 'steps', label: 'Steps', type: 'int', default: 25 }+ assert.equal(withWeightVariantAvailability(steps, variants, []), steps)+})++test('flags a selected variant only when availability is known and it is not installed', () => {+ assert.equal(isMissingWeightVariant('gguf_quant', 'Q4_K_M', variants, ['Q5_K_M']), true)+ assert.equal(isMissingWeightVariant('gguf_quant', 'Q5_K_M', variants, ['Q5_K_M']), false)+ assert.equal(isMissingWeightVariant('gguf_quant', 'auto', variants, []), false)+ assert.equal(isMissingWeightVariant('steps', 'Q4_K_M', variants, []), false)+ assert.equal(isMissingWeightVariant('gguf_quant', 'Q4_K_M', variants, undefined), false)+ assert.equal(isMissingWeightVariant('gguf_quant', 'Q4_K_M', undefined, []), false)+})diff --git a/apps/forge-desktop/src/shared/utils/weightVariants.ts b/apps/forge-desktop/src/shared/utils/weightVariants.tsnew file mode 100644index 000000000..252fd6d57--- /dev/null+++ b/apps/forge-desktop/src/shared/utils/weightVariants.ts@@ -0,0 +1,35 @@+import type { ParamSchema, WeightVariantsInfo } from '@shared/types/electron.d'++/**+ * Suffix the options of a node's variant-selecting param that are declared+ * weight variants but not installed. Other params, and values that are not+ * variant ids, are returned untouched. `installed` undefined means not known yet.+ */+export function withWeightVariantAvailability(+ param: ParamSchema,+ variants: WeightVariantsInfo | undefined,+ installed: string[] | undefined,+): ParamSchema {+ if (!variants || !installed || param.id !== variants.param || !param.options) return param+ const variantIds = new Set(variants.options.map((option) => option.id))+ return {+ ...param,+ options: param.options.map((option) => {+ const value = String(option.value)+ if (!variantIds.has(value) || installed.includes(value)) return option+ return { ...option, label: `${option.label ?? value} (not installed)` }+ }),+ }+}++/** True when `value` selects a declared weight variant that is known not to be installed. */+export function isMissingWeightVariant(+ paramId: string,+ value: unknown,+ variants: WeightVariantsInfo | undefined,+ installed: string[] | undefined,+): boolean {+ if (!variants || !installed || paramId !== variants.param) return false+ const id = String(value)+ return variants.options.some((option) => option.id === id) && !installed.includes(id)+}diff --git a/apps/forge-desktop/src/styles/globals.css b/apps/forge-desktop/src/styles/globals.cssnew file mode 100644index 000000000..9bc7baa25--- /dev/null+++ b/apps/forge-desktop/src/styles/globals.css@@ -0,0 +1,114 @@+@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');++@font-face {+ font-family: 'Atkinson Hyperlegible';+ font-style: normal;+ font-weight: 400;+ font-display: swap;+ src: url('../assets/fonts/atkinson-hyperlegible/AtkinsonHyperlegible-Regular.woff2') format('woff2');+}++@font-face {+ font-family: 'Atkinson Hyperlegible';+ font-style: normal;+ font-weight: 700;+ font-display: swap;+ src: url('../assets/fonts/atkinson-hyperlegible/AtkinsonHyperlegible-Bold.woff2') format('woff2');+}++@tailwind base;+@tailwind components;+@tailwind utilities;++@layer base {+ :root {+ --app-font: 'Inter', system-ui, sans-serif;+ }++ * {+ box-sizing: border-box;+ margin: 0;+ padding: 0;+ }++ html,+ body,+ #root {+ height: 100%;+ width: 100%;+ overflow: hidden;+ background-color: #111113;+ color: #f4f4f5;+ font-family: var(--app-font);+ -webkit-font-smoothing: antialiased;+ user-select: none;+ }++ /* Custom scrollbar */+ ::-webkit-scrollbar {+ width: 6px;+ }+ ::-webkit-scrollbar-track {+ background: #18181b;+ }+ ::-webkit-scrollbar-thumb {+ background: #3f3f46;+ border-radius: 3px;+ }+ ::-webkit-scrollbar-thumb:hover {+ background: #52525b;+ }+}++@layer utilities {+ .drag-region {+ -webkit-app-region: drag;+ }+ .no-drag {+ -webkit-app-region: no-drag;+ }+ .animate-slide-up {+ animation: slideUp 0.25s cubic-bezier(0.16, 1, 0.3, 1) forwards;+ }+ .animate-fade-in {+ animation: fadeIn 0.2s ease-out forwards;+ }+ .animate-slide-up-center {+ animation: slideUpCenter 0.25s cubic-bezier(0.16, 1, 0.3, 1) forwards;+ }+ .animate-drawer-in {+ animation: drawerIn 0.22s cubic-bezier(0.2, 0.8, 0.2, 1) forwards;+ }+}++@keyframes slideUp {+ from {+ opacity: 0;+ transform: translateX(-50%) translateY(20px);+ }+ to {+ opacity: 1;+ transform: translateX(-50%) translateY(0);+ }+}++@keyframes fadeIn {+ from { opacity: 0; }+ to { opacity: 1; }+}++@keyframes drawerIn {+ from { transform: translateX(100%); }+ to { transform: translateX(0); }+}++@keyframes slideUpCenter {+ from {+ opacity: 0;+ transform: translateY(12px) scale(0.97);+ }+ to {+ opacity: 1;+ transform: translateY(0) scale(1);+ }+}diff --git a/apps/forge-desktop/src/vite-env.d.ts b/apps/forge-desktop/src/vite-env.d.tsnew file mode 100644index 000000000..11f02fe2a--- /dev/null+++ b/apps/forge-desktop/src/vite-env.d.ts@@ -0,0 +1 @@+/// <reference types="vite/client" />diff --git a/apps/forge-desktop/tailwind.config.js b/apps/forge-desktop/tailwind.config.jsnew file mode 100644index 000000000..c061cadce--- /dev/null+++ b/apps/forge-desktop/tailwind.config.js@@ -0,0 +1,37 @@+/** @type {import('tailwindcss').Config} */+module.exports = {+ content: ['./src/**/*.{ts,tsx,html}'],+ theme: {+ extend: {+ colors: {+ surface: {+ 50: '#f4f4f5',+ 100: '#e4e4e7',+ 200: '#27272a',+ 300: '#1e1e21',+ 400: '#18181b',+ 500: '#111113',+ },+ accent: {+ DEFAULT: '#7c3aed',+ light: '#a78bfa',+ dark: '#5b21b6',+ }+ },+ fontFamily: {+ sans: ['Inter', 'system-ui', 'sans-serif'],+ mono: ['JetBrains Mono', 'monospace'],+ },+ keyframes: {+ slide: {+ '0%': { transform: 'translateX(-100%)' },+ '100%': { transform: 'translateX(400%)' },+ },+ },+ animation: {+ slide: 'slide 1.5s ease-in-out infinite',+ },+ }+ },+ plugins: []+}diff --git a/apps/forge-desktop/tools/modly-cli/SKILL.md b/apps/forge-desktop/tools/modly-cli/SKILL.mdnew file mode 100644index 000000000..8b492a6ee--- /dev/null+++ b/apps/forge-desktop/tools/modly-cli/SKILL.md@@ -0,0 +1,191 @@+---+name: modly-cli+description: Use when an agent needs to call a running Modly desktop instance from the terminal to generate/export image-to-3D assets through canonical JSON-first automation commands.+version: 1.2.0+author: Modly+license: MIT+metadata:+ hermes:+ tags: [modly, image-to-3d, cli, automation, agents]+ related_skills: []+---++# Modly CLI++## Overview++Modly exposes a local API at `http://127.0.0.1:8765` while the official desktop app is running. The stdlib-only CLI at `tools/modly-cli/agent.py` is an agent helper over the canonical automation contract:++- `health`+- `model`+- `workflow-run`+- `capability`+- `process-run`++Final machine-readable JSON is printed to stdout. Progress JSON lines, when requested, are printed to stderr.++## Prerequisites++Launch the official Modly desktop app first, then check readiness:++```bash+python tools/modly-cli/agent.py health+```++Use `--compact` when another agent needs single-line JSON:++```bash+python tools/modly-cli/agent.py --compact health+```++`GET /health` is checked before business operations. If the app is unavailable, failures are structured:++```json+{+ "ok": false,+ "code": "API_UNAVAILABLE",+ "message": "Cannot reach Modly API at ..."+}+```++## Canonical Commands++Inspect models through `/model/*`:++```bash+python tools/modly-cli/agent.py model list+python tools/modly-cli/agent.py model status+python tools/modly-cli/agent.py model params --model active+```++Start or resume workflow runs:++```bash+python tools/modly-cli/agent.py workflow-run start --image ./input.png --wait+python tools/modly-cli/agent.py workflow-run status <run_id>+python tools/modly-cli/agent.py workflow-run cancel <run_id>+```++Generate from an image and export the finished mesh:++```bash+python tools/modly-cli/agent.py generate \+ --image ./input.png \+ --output ./export.glb \+ --progress+```++`generate` is a friendly wrapper around `POST /workflow-runs/from-image` and `GET /workflow-runs/{run_id}`. It does not silently fall back to `/generate/*`. The JSON includes recovery metadata:++```json+{+ "ok": true,+ "run": {"kind": "workflowRun", "id": "..."},+ "workspace_path": "Default/model.glb",+ "export_path": "/absolute/path/to/export.glb",+ "meta": {+ "status_command": "python tools/modly-cli/agent.py workflow-run status ...",+ "cancel_command": "python tools/modly-cli/agent.py workflow-run cancel ...",+ "legacy": false+ }+}+```++Use `--no-export` when the caller only needs the workspace path. The hidden `export` helper remains available to download an existing workspace mesh, but it is not part of the canonical root command set:++```bash+python tools/modly-cli/agent.py export --path Default/model.glb --output ./model.glb+```++Discover capabilities or process runs only when the running server exposes the canonical contract:++```bash+python tools/modly-cli/agent.py capability list+python tools/modly-cli/agent.py process-run status <run_id>+```++If the contract is absent, the CLI fails closed:++```json+{+ "ok": false,+ "code": "UNSUPPORTED_PROCESS",+ "message": "This process is not available through the canonical process-run contract."+}+```++## Model Selection++`--model auto` uses the active model reported by `/model/status`, then validates that id against `/model/all`. Explicit `--model` values are also validated against `/model/all`. The CLI does not infer hidden capabilities from model names, labels, or string fragments.++## Legacy Compatibility++The old `/generate/*` endpoints are explicit compatibility commands:++```bash+python tools/modly-cli/agent.py legacy job <job_id>+python tools/modly-cli/agent.py legacy cancel <job_id>+python tools/modly-cli/agent.py legacy generate --image ./input.png --output ./legacy.glb+```++Legacy responses include `meta.legacy: true`. Top-level `job`, `cancel`, `models`, and `params` aliases may still parse for older scripts, but they are not the documented canonical surface.++## Developer-Only API Helpers++Headless startup helpers live under `dev`:++```bash+python tools/modly-cli/agent.py dev serve-api --print-command+python tools/modly-cli/agent.py dev ensure-server+python tools/modly-cli/agent.py dev ensure-server --start --detach+```++These commands start or inspect only the FastAPI backend. They do not imply Electron/Desktop bridge readiness, scene operation readiness, extension process execution readiness, or full workflow support. Prefer launching the official desktop app for real agent workflows.++## Experimental ComfyUI Helpers++ComfyUI orchestration is outside the canonical Modly contract and lives under `experimental`:++```bash+python tools/modly-cli/agent.py experimental comfy-image \+ --workflow Trellis2Workflow \+ --prompt "clean object render, isolated on white" \+ --comfy-output ./source.png++python tools/modly-cli/agent.py experimental generate-from-workflow \+ --workflow Trellis2-Full \+ --prompt "clean orthographic product render of a stylized robot toy" \+ --output ./export.glb+```++`experimental generate-from-workflow --workflow <name> --output <path>` treats `--output` as the final artifact location. If the ComfyUI history contains a downloadable `.glb`, `.gltf`, `.obj`, `.stl`, or `.ply`, the CLI downloads that asset directly and does not call Modly health or generation. If the workflow only produces an image, the CLI downloads that image and falls back through the canonical Modly workflow-run generation path. If no supported asset or image is found, it fails with `code: "NO_WORKFLOW_OUTPUT"`.++## Hidden Helper Aliases++The top-level `status`, `export`, and `batch` helpers remain parseable for older scripts and agent ergonomics, but root help does not present them as canonical automation primitives. Prefer `health`, `model`, `workflow-run`, `capability`, and `process-run` when documenting the supported contract.++## Batch Workflow++The hidden `batch` helper generates meshes sequentially from a directory or manifest JSON through the canonical `generate` path:++```bash+python tools/modly-cli/agent.py batch \+ --input-dir ./images \+ --output-dir ./meshes \+ --continue-on-error++python tools/modly-cli/agent.py batch \+ --manifest ./jobs.json \+ --output-dir ./meshes+```++Manifest files may be a JSON list, or an object with `jobs` or `images`. Each entry can be a string image path or an object with `image`, optional `output`, and optional `format`.++## Verification Checklist++- [ ] `python tools/modly-cli/agent.py health` returns `ok: true`.+- [ ] `python tools/modly-cli/agent.py model list` returns model entries.+- [ ] `python tools/modly-cli/agent.py generate --image <image> --output <mesh>` returns `ok: true`, `run.kind: workflowRun`, and recovery metadata.+- [ ] The reported `export_path` exists and has non-zero size when export is enabled.+- [ ] `python tools/modly-cli/agent.py workflow-run status <run_id>` can resume polling from metadata.+- [ ] `python tools/modly-cli/test_agent.py` passes.diff --git a/apps/forge-desktop/tools/modly-cli/agent.py b/apps/forge-desktop/tools/modly-cli/agent.pynew file mode 100644index 000000000..e424aa25b--- /dev/null+++ b/apps/forge-desktop/tools/modly-cli/agent.py@@ -0,0 +1,1360 @@+#!/usr/bin/env python3+"""Minimal agent-friendly CLI for the local Modly API.++The Electron app normally owns the FastAPI server. This tool is intentionally+small and stdlib-only so automation agents can call a running Modly instance,+optionally start only the FastAPI backend, and always receive parseable JSON.+"""+from __future__ import annotations++import argparse+import json+import mimetypes+import os+import subprocess+import sys+import tempfile+import time+import urllib.error+import urllib.parse+import urllib.request+from pathlib import Path+from typing import Any++def _int_env(primary: str, fallback: str, default: int) -> int:+ value = os.environ.get(primary, os.environ.get(fallback, str(default)))+ try:+ return int(value)+ except (TypeError, ValueError):+ return default+++def _float_env(primary: str, fallback: str, default: float) -> float:+ value = os.environ.get(primary, os.environ.get(fallback, str(default)))+ try:+ return float(value)+ except (TypeError, ValueError):+ return default+++DEFAULT_BASE_URL = os.environ.get("MODLY_API_URL", "http://127.0.0.1:8765")+DEFAULT_TIMEOUT_SECONDS = _int_env("MODLY_CLI_TIMEOUT", "MODLY_AGENT_TIMEOUT", 1800)+DEFAULT_POLL_SECONDS = _float_env("MODLY_CLI_POLL_SECONDS", "MODLY_AGENT_POLL_SECONDS", 2.0)+EXPORT_FORMATS = ("glb", "stl", "obj", "ply")+IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".webp"}+WORKFLOW_ASSET_SUFFIXES = {".glb", ".gltf", ".obj", ".stl", ".ply"}+++class ModlyCliError(RuntimeError):+ """Expected user/API failure that should be reported as JSON."""++ def __init__(self, message: str, *, code: str = "MODLY_CLI_ERROR", http_status: int | None = None) -> None:+ super().__init__(message)+ self.message = message+ self.code = code+ self.http_status = http_status+++def _json_print(data: dict[str, Any], *, compact: bool = False) -> None:+ if compact:+ print(json.dumps(data, separators=(",", ":"), sort_keys=True))+ else:+ print(json.dumps(data, indent=2, sort_keys=True))+++def _request_json(+ method: str,+ url: str,+ *,+ timeout: float,+ data: bytes | None = None,+ headers: dict[str, str] | None = None,+) -> Any:+ req = urllib.request.Request(url, data=data, method=method, headers=headers or {})+ try:+ with urllib.request.urlopen(req, timeout=timeout) as resp:+ raw = resp.read().decode("utf-8")+ except urllib.error.HTTPError as exc:+ detail = exc.read().decode("utf-8", errors="replace")+ raise ModlyCliError(f"HTTP {exc.code} from {url}: {detail}", code=f"HTTP_{exc.code}", http_status=exc.code) from exc+ except urllib.error.URLError as exc:+ raise ModlyCliError(f"Cannot reach Modly API at {url}: {exc.reason}", code="API_UNAVAILABLE") from exc+ try:+ return json.loads(raw) if raw else {}+ except json.JSONDecodeError as exc:+ raise ModlyCliError(f"Expected JSON from {url}, got: {raw[:500]}", code="INVALID_JSON_RESPONSE") from exc+++def _download(url: str, dest: Path, *, timeout: float) -> int:+ dest.parent.mkdir(parents=True, exist_ok=True)+ try:+ with urllib.request.urlopen(url, timeout=timeout) as resp, dest.open("wb") as fh:+ total = 0+ while True:+ chunk = resp.read(1024 * 1024)+ if not chunk:+ return total+ fh.write(chunk)+ total += len(chunk)+ except urllib.error.HTTPError as exc:+ detail = exc.read().decode("utf-8", errors="replace")+ raise ModlyCliError(f"HTTP {exc.code} while downloading {url}: {detail}", code=f"HTTP_{exc.code}", http_status=exc.code) from exc+ except urllib.error.URLError as exc:+ raise ModlyCliError(f"Cannot download {url}: {exc.reason}", code="DOWNLOAD_FAILED") from exc+ except OSError as exc:+ raise ModlyCliError(f"Cannot write to {dest}: {exc}", code="WRITE_FAILED") from exc+++def _multipart_form(fields: dict[str, str], file_field: str, file_path: Path) -> tuple[bytes, str]:+ boundary = f"----modly-cli-{time.time_ns()}"+ parts: list[bytes] = []++ for name, value in fields.items():+ parts.extend([+ f"--{boundary}\r\n".encode(),+ f'Content-Disposition: form-data; name="{name}"\r\n\r\n'.encode(),+ str(value).encode("utf-8"),+ b"\r\n",+ ])++ content_type = mimetypes.guess_type(file_path.name)[0] or "application/octet-stream"+ parts.extend([+ f"--{boundary}\r\n".encode(),+ f'Content-Disposition: form-data; name="{file_field}"; filename="{file_path.name}"\r\n'.encode(),+ f"Content-Type: {content_type}\r\n\r\n".encode(),+ file_path.read_bytes(),+ b"\r\n",+ f"--{boundary}--\r\n".encode(),+ ])+ return b"".join(parts), f"multipart/form-data; boundary={boundary}"+++def _workspace_relative_path(output_url: str) -> str:+ parsed = urllib.parse.urlparse(output_url)+ path = parsed.path if parsed.scheme else output_url+ prefix = "/workspace/"+ if path.startswith(prefix):+ return _validate_workspace_path(urllib.parse.unquote(path[len(prefix):]))+ return _validate_workspace_path(urllib.parse.unquote(path))+++def _is_windows_drive_component(component: str) -> bool:+ return len(component) >= 2 and component[0].isalpha() and component[1] == ":"+++def _validate_workspace_path(workspace_path: str) -> str:+ value = str(workspace_path)+ normalized = value.replace("\\", "/")+ parts = normalized.split("/")+ if (+ not value+ or value.startswith(("/", "\\"))+ or urllib.parse.urlparse(value).scheme+ or any(part == ".." for part in parts)+ or any(_is_windows_drive_component(part) for part in parts)+ ):+ raise ModlyCliError(f"Invalid workspace path: {workspace_path}", code="INVALID_WORKSPACE_PATH")+ return value+++def _export_workspace_path(base_url: str, workspace_path: str, fmt: str, dest: Path, *, timeout: float) -> int:+ workspace_path = _validate_workspace_path(workspace_path)+ export_url = f"{base_url.rstrip('/')}/export/{urllib.parse.quote(fmt)}?{urllib.parse.urlencode({'path': workspace_path})}"+ return _download(export_url, dest, timeout=timeout)+++def _try_health(base_url: str, timeout: float) -> dict[str, Any] | None:+ try:+ health = _request_json("GET", f"{base_url.rstrip('/')}/health", timeout=timeout)+ except ModlyCliError:+ return None+ return health if isinstance(health, dict) else {"raw": health}+++def _require_health(base_url: str, timeout: float) -> dict[str, Any]:+ health = _request_json("GET", f"{base_url.rstrip('/')}/health", timeout=timeout)+ return health if isinstance(health, dict) else {"raw": health}+++def _model_catalog(base_url: str, timeout: float) -> list[dict[str, Any]]:+ data = _request_json("GET", f"{base_url.rstrip('/')}/model/all", timeout=timeout)+ if not isinstance(data, list):+ raise ModlyCliError(f"Expected /model/all to return a list, got: {data}", code="INVALID_MODEL_CATALOG")+ return [model for model in data if isinstance(model, dict)]+++def _model_ids(models: list[dict[str, Any]]) -> set[str]:+ return {str(model["id"]) for model in models if model.get("id")}+++def _validate_model_id(base_url: str, request_timeout: float, model_id: str, models: list[dict[str, Any]] | None = None) -> str:+ models = models if models is not None else _model_catalog(base_url, request_timeout)+ ids = _model_ids(models)+ if model_id not in ids:+ available = ", ".join(sorted(ids)) or "(none)"+ raise ModlyCliError(+ f"Unknown model id '{model_id}'. Use one of: {available}",+ code="INVALID_MODEL_ID",+ )+ return model_id+++def _recovery_meta(base_url: str, run_id: str, *, legacy: bool = False, kind: str = "workflow-run", extra: dict[str, Any] | None = None) -> dict[str, Any]:+ prefix = "python tools/modly-cli/agent.py"+ if base_url.rstrip("/") != DEFAULT_BASE_URL.rstrip("/"):+ prefix = f"{prefix} --base-url {base_url.rstrip('/')}"+ if legacy:+ group = "legacy job"+ cancel = "legacy cancel"+ elif kind == "process-run":+ group = "process-run status"+ cancel = "process-run cancel"+ else:+ group = "workflow-run status"+ cancel = "workflow-run cancel"+ meta = {+ "status_command": f"{prefix} {group} {run_id}",+ "cancel_command": f"{prefix} {cancel} {run_id}",+ "legacy": legacy,+ }+ if extra:+ meta.update(extra)+ return meta+++def _unsupported_process(message: str = "This process is not available through the canonical process-run contract.") -> ModlyCliError:+ return ModlyCliError(message, code="UNSUPPORTED_PROCESS")+++def _request_supported_contract(method: str, url: str, *, timeout: float, data: bytes | None = None, headers: dict[str, str] | None = None) -> Any:+ try:+ return _request_json(method, url, timeout=timeout, data=data, headers=headers)+ except ModlyCliError as exc:+ if exc.http_status == 404:+ raise _unsupported_process() from exc+ raise+++def _repo_root() -> Path:+ return Path(__file__).resolve().parents[2]+++def _windows_env_paths(name: str) -> list[Path]:+ value = os.environ.get(name)+ if value:+ return [Path(value)]+ paths: list[Path] = []+ if os.name == "posix":+ users_dir = Path("/mnt/c/Users")+ roots: list[Path] = []+ if users_dir.exists():+ try:+ roots = sorted(p for p in users_dir.glob("*") if p.is_dir())+ except PermissionError:+ roots = []+ for root in roots:+ try:+ if name == "LOCALAPPDATA":+ candidate = root / "AppData" / "Local"+ elif name == "APPDATA":+ candidate = root / "AppData" / "Roaming"+ else:+ continue+ if candidate.exists():+ paths.append(candidate)+ except PermissionError:+ continue+ return paths+++def _windows_env_path(name: str) -> Path | None:+ paths = _windows_env_paths(name)+ return paths[0] if paths else None+++def _default_api_dir() -> Path | None:+ repo_api = _repo_root() / "api"+ if (repo_api / "main.py").exists():+ return repo_api+ for local in _windows_env_paths("LOCALAPPDATA"):+ installed = local / "Programs" / "Modly" / "resources" / "api"+ if (installed / "main.py").exists():+ return installed+ return None+++def _default_python(api_dir: Path) -> Path | None:+ candidates = [+ api_dir / ".venv" / "Scripts" / "python.exe",+ api_dir / ".venv" / "bin" / "python",+ ]+ for appdata in _windows_env_paths("APPDATA"):+ candidates.append(appdata / "Modly" / "dependencies" / "venv" / "Scripts" / "python.exe")+ candidates.append(Path(sys.executable))+ for candidate in candidates:+ if candidate.exists():+ return candidate+ return None+++def _load_modly_settings() -> dict[str, Any]:+ candidates: list[Path] = []+ for appdata in _windows_env_paths("APPDATA"):+ candidates.append(appdata / "Modly" / "settings.json")+ candidates.append(Path.home() / ".config" / "Modly" / "settings.json")+ for path in candidates:+ if path.exists():+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ return data if isinstance(data, dict) else {}+ except (OSError, json.JSONDecodeError):+ return {}+ return {}+++def _resolve_serve_config(args: argparse.Namespace) -> tuple[Path, Path, dict[str, str], list[str], str]:+ api_dir = Path(args.api_dir).expanduser().resolve() if getattr(args, "api_dir", None) else _default_api_dir()+ if not api_dir or not (api_dir / "main.py").exists():+ raise ModlyCliError("Could not find Modly api directory; pass --api-dir")++ python = Path(args.python).expanduser().resolve() if getattr(args, "python", None) else _default_python(api_dir)+ if not python or not python.exists():+ raise ModlyCliError("Could not find Modly Python environment; pass --python")++ settings = _load_modly_settings()+ env = os.environ.copy()+ hf_token = getattr(args, "hf_token", None) or settings.get("hfToken") or os.environ.get("HF_TOKEN", "")+ env.update({+ "PYTHONUNBUFFERED": "1",+ "MODELS_DIR": getattr(args, "models_dir", None) or settings.get("modelsDir") or str(Path.home() / ".modly" / "models"),+ "WORKSPACE_DIR": getattr(args, "workspace_dir", None) or settings.get("workspaceDir") or str(Path.home() / ".modly" / "workspace"),+ "EXTENSIONS_DIR": getattr(args, "extensions_dir", None) or settings.get("extensionsDir") or "",+ "SELECTED_MODEL_ID": getattr(args, "model", None) or os.environ.get("SELECTED_MODEL_ID", ""),+ "HUGGING_FACE_HUB_TOKEN": hf_token,+ "HF_TOKEN": hf_token,+ })+ cmd = [str(python), "-m", "uvicorn", "main:app", "--host", args.host, "--port", str(args.port)]+ base_url = f"http://{args.host}:{args.port}"+ return api_dir, python, env, cmd, base_url+++def _start_backend(cmd: list[str], *, api_dir: Path, env: dict[str, str], detach: bool) -> subprocess.Popen[Any]:+ kwargs: dict[str, Any] = {"cwd": str(api_dir), "env": env}+ if detach:+ kwargs.update({+ "stdin": subprocess.DEVNULL,+ "stdout": subprocess.DEVNULL,+ "stderr": subprocess.DEVNULL,+ })+ if os.name != "nt":+ kwargs["start_new_session"] = True+ else:+ kwargs["creationflags"] = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)+ return subprocess.Popen(cmd, **kwargs)+++def cmd_health(args: argparse.Namespace) -> int:+ base_url = args.base_url.rstrip("/")+ data = _request_json("GET", f"{base_url}/health", timeout=args.request_timeout)+ _json_print({"ok": True, "base_url": base_url, "health": data}, compact=args.compact)+ return 0+++def cmd_status(args: argparse.Namespace) -> int:+ base_url = args.base_url.rstrip("/")+ health = _request_json("GET", f"{base_url}/health", timeout=args.request_timeout)+ model = _request_json("GET", f"{base_url}/model/status", timeout=args.request_timeout)+ _json_print({"ok": True, "base_url": base_url, "health": health, "model": model}, compact=args.compact)+ return 0+++def cmd_models(args: argparse.Namespace) -> int:+ base_url = args.base_url.rstrip("/")+ _require_health(base_url, args.request_timeout)+ data = _request_json("GET", f"{base_url}/model/all", timeout=args.request_timeout)+ _json_print({"ok": True, "base_url": base_url, "models": data, "meta": {"canonical": "model list"}}, compact=args.compact)+ return 0+++def cmd_model_status(args: argparse.Namespace) -> int:+ base_url = args.base_url.rstrip("/")+ _require_health(base_url, args.request_timeout)+ data = _request_json("GET", f"{base_url}/model/status", timeout=args.request_timeout)+ _json_print({"ok": True, "base_url": base_url, "model": data}, compact=args.compact)+ return 0+++def cmd_model_list(args: argparse.Namespace) -> int:+ return cmd_models(args)+++def _parse_params(params_json: str | None, params_file: str | None) -> dict[str, Any]:+ if params_file:+ text = Path(params_file).expanduser().read_text(encoding="utf-8")+ else:+ text = params_json or "{}"+ try:+ parsed = json.loads(text)+ except json.JSONDecodeError as exc:+ raise ModlyCliError(f"params must be valid JSON: {exc}") from exc+ if not isinstance(parsed, dict):+ raise ModlyCliError("params must be a JSON object")+ return parsed+++def _choose_auto_model(base_url: str, request_timeout: float) -> str:+ active = _request_json("GET", f"{base_url.rstrip('/')}/model/status", timeout=request_timeout)+ if not isinstance(active, dict) or not active.get("id"):+ raise ModlyCliError(f"Could not resolve active model id: {active}", code="MODEL_NOT_READY")+ return _validate_model_id(base_url, request_timeout, str(active["id"]))+++def _resolve_model_id(args: argparse.Namespace, base_url: str) -> str:+ model_id = args.model+ if not model_id or model_id == "auto":+ return _choose_auto_model(base_url, args.request_timeout)+ if model_id == "active":+ active = _request_json("GET", f"{base_url}/model/status", timeout=args.request_timeout)+ if not isinstance(active, dict) or not active.get("id"):+ raise ModlyCliError(f"Could not resolve active model id: {active}", code="MODEL_NOT_READY")+ return _validate_model_id(base_url, args.request_timeout, str(active["id"]))+ return _validate_model_id(base_url, args.request_timeout, str(model_id))+++def cmd_params(args: argparse.Namespace) -> int:+ base_url = args.base_url.rstrip("/")+ _require_health(base_url, args.request_timeout)+ model_id = _resolve_model_id(args, base_url)+ query = ""+ if model_id:+ query = "?" + urllib.parse.urlencode({"model_id": model_id})+ params = _request_json("GET", f"{base_url}/model/params{query}", timeout=args.request_timeout)+ _json_print({"ok": True, "base_url": base_url, "model_id": model_id, "params": params, "meta": {"canonical": "model params"}}, compact=args.compact)+ return 0+++def cmd_job(args: argparse.Namespace) -> int:+ base_url = args.base_url.rstrip("/")+ _require_health(base_url, args.request_timeout)+ status = _request_json("GET", f"{base_url}/generate/status/{urllib.parse.quote(args.job_id)}", timeout=args.request_timeout)+ _json_print({"ok": True, "base_url": base_url, "job_id": args.job_id, "status": status, "meta": _recovery_meta(base_url, args.job_id, legacy=True)}, compact=args.compact)+ return 0+++def cmd_cancel(args: argparse.Namespace) -> int:+ base_url = args.base_url.rstrip("/")+ _require_health(base_url, args.request_timeout)+ result = _request_json("POST", f"{base_url}/generate/cancel/{urllib.parse.quote(args.job_id)}", timeout=args.request_timeout)+ _json_print({"ok": True, "base_url": base_url, "job_id": args.job_id, "cancel": result, "meta": _recovery_meta(base_url, args.job_id, legacy=True)}, compact=args.compact)+ return 0++++def _load_comfy_workflow(workflow: str, *, host: str, timeout: float) -> dict[str, Any]:+ path = Path(workflow).expanduser()+ if path.exists():+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except json.JSONDecodeError as exc:+ raise ModlyCliError(f"workflow must be valid JSON: {path}: {exc}") from exc+ if not isinstance(data, dict):+ raise ModlyCliError(f"workflow JSON must be an object: {path}")+ return data++ candidates = [workflow, f"{workflow}.json"] if not workflow.endswith(".json") else [workflow]+ for name in candidates:+ quoted = urllib.parse.quote(name.lstrip("/"), safe="/")+ for prefix in ("/userdata/workflows/", "/api/userdata/workflows/", "/userdata/", "/api/userdata/"):+ try:+ data = _request_json("GET", f"{host.rstrip('/')}{prefix}{quoted}", timeout=timeout)+ except ModlyCliError:+ continue+ if isinstance(data, dict):+ return data++ search_roots: list[Path] = []+ for value in [os.environ.get("COMFYUI_WORKFLOW_DIR"), os.environ.get("COMFYUI_USER_DIR")]:+ if value:+ search_roots.append(Path(value).expanduser())+ search_roots.extend([+ Path.home() / "ComfyUI" / "user" / "default" / "workflows",+ Path.home() / "Documents" / "ComfyUI" / "user" / "default" / "workflows",+ ])+ for appdata in _windows_env_paths("APPDATA"):+ search_roots.extend([+ appdata / "ComfyUI" / "user" / "default" / "workflows",+ appdata / "comfyui" / "user" / "default" / "workflows",+ ])+ for root in search_roots:+ for name in candidates:+ candidate = root / name+ if candidate.exists():+ try:+ data = json.loads(candidate.read_text(encoding="utf-8"))+ except json.JSONDecodeError as exc:+ raise ModlyCliError(f"workflow must be valid JSON: {candidate}: {exc}") from exc+ if isinstance(data, dict):+ return data+ raise ModlyCliError(f"Could not find ComfyUI workflow '{workflow}'. Pass a JSON path or set COMFYUI_WORKFLOW_DIR.")+++def _patch_comfy_workflow(workflow: dict[str, Any], *, prompt: str | None, seed: int | None) -> dict[str, Any]:+ workflow = json.loads(json.dumps(workflow))+ nodes = workflow.get("prompt", workflow)+ if not isinstance(nodes, dict):+ raise ModlyCliError("ComfyUI workflow must be API format (top-level node-id object, or {'prompt': {...}})")+ if "nodes" in workflow and "links" in workflow:+ raise ModlyCliError("ComfyUI workflow is editor format; export it as API format first")++ if prompt is not None:+ patched = False+ for node in nodes.values():+ if not isinstance(node, dict):+ continue+ class_type = str(node.get("class_type", "")).lower()+ inputs = node.get("inputs") if isinstance(node.get("inputs"), dict) else {}+ text = str(inputs.get("text", "")).lower()+ if "cliptextencode" in class_type and "negative" not in text:+ inputs["text"] = prompt+ patched = True+ break+ if not patched:+ for node in nodes.values():+ if isinstance(node, dict) and isinstance(node.get("inputs"), dict):+ inputs = node["inputs"]+ for key in ("prompt", "positive", "text"):+ if key in inputs and isinstance(inputs[key], str):+ inputs[key] = prompt+ patched = True+ break+ if patched:+ break+ if not patched:+ raise ModlyCliError("Could not find a text/prompt input to patch in ComfyUI workflow")++ if seed is not None:+ for node in nodes.values():+ if not isinstance(node, dict) or not isinstance(node.get("inputs"), dict):+ continue+ inputs = node["inputs"]+ for key in ("seed", "noise_seed"):+ if key in inputs and isinstance(inputs[key], int):+ inputs[key] = seed+ return nodes+++def _run_comfy_workflow(args: argparse.Namespace) -> dict[str, Any]:+ host = args.comfy_url.rstrip("/")+ workflow = _load_comfy_workflow(args.workflow, host=host, timeout=args.request_timeout)+ prompt = getattr(args, "prompt", None)+ seed = getattr(args, "seed", None)+ graph = _patch_comfy_workflow(workflow, prompt=prompt, seed=seed)+ payload = json.dumps({"prompt": graph, "client_id": "modly-cli"}).encode("utf-8")+ queued = _request_json("POST", f"{host}/prompt", timeout=args.request_timeout, data=payload, headers={"Content-Type": "application/json"})+ prompt_id = queued.get("prompt_id") if isinstance(queued, dict) else None+ if not prompt_id:+ raise ModlyCliError(f"ComfyUI did not return prompt_id: {queued}")++ deadline = time.monotonic() + args.timeout+ history: dict[str, Any] = {}+ while time.monotonic() < deadline:+ data = _request_json("GET", f"{host}/history/{urllib.parse.quote(str(prompt_id))}", timeout=args.request_timeout)+ if isinstance(data, dict) and str(prompt_id) in data:+ history = data[str(prompt_id)] if isinstance(data[str(prompt_id)], dict) else {"raw": data[str(prompt_id)]}+ break+ if getattr(args, "progress", False) and not getattr(args, "quiet", False):+ print(json.dumps({"phase": "comfy", "prompt_id": prompt_id, "status": "running"}), file=sys.stderr)+ time.sleep(args.poll)+ if not history:+ raise ModlyCliError(f"Timed out waiting for ComfyUI prompt {prompt_id}", code="TIMEOUT")++ return {"ok": True, "comfy_url": host, "workflow": args.workflow, "prompt_id": str(prompt_id), "history": history}+++def _iter_comfy_file_refs(value: Any) -> list[dict[str, Any]]:+ refs: list[dict[str, Any]] = []+ if isinstance(value, dict):+ filename = value.get("filename")+ if isinstance(filename, str) and filename:+ refs.append(value)+ for child in value.values():+ refs.extend(_iter_comfy_file_refs(child))+ elif isinstance(value, list):+ for child in value:+ refs.extend(_iter_comfy_file_refs(child))+ return refs+++def _comfy_ref_suffix(ref: dict[str, Any]) -> str:+ filename = str(ref.get("filename") or "")+ return Path(urllib.parse.urlparse(filename).path).suffix.lower()+++def _find_comfy_file_ref(history: dict[str, Any], suffixes: set[str]) -> dict[str, Any] | None:+ outputs = history.get("outputs") if isinstance(history.get("outputs"), dict) else history+ for ref in _iter_comfy_file_refs(outputs):+ if _comfy_ref_suffix(ref) in suffixes:+ return ref+ return None+++def _comfy_view_url(host: str, ref: dict[str, Any]) -> str:+ query = urllib.parse.urlencode({+ "filename": ref.get("filename", ""),+ "subfolder": ref.get("subfolder", ""),+ "type": ref.get("type", "output"),+ })+ return f"{host.rstrip('/')}/view?{query}"+++def _download_comfy_ref(host: str, ref: dict[str, Any], dest: Path, *, timeout: float) -> int:+ return _download(_comfy_view_url(host, ref), dest, timeout=timeout)+++def _temp_path_for_comfy_ref(ref: dict[str, Any], *, default_suffix: str) -> Path:+ suffix = _comfy_ref_suffix(ref) or default_suffix+ tmp = tempfile.NamedTemporaryFile(delete=False, prefix="modly-comfy-", suffix=suffix)+ tmp.close()+ return Path(tmp.name)+++def _download_comfy_image_output(args: argparse.Namespace, comfy: dict[str, Any]) -> dict[str, Any]:+ host = str(comfy["comfy_url"])+ prompt_id = str(comfy["prompt_id"])+ history = comfy["history"] if isinstance(comfy.get("history"), dict) else {}++ image_ref = _find_comfy_file_ref(history, IMAGE_SUFFIXES)+ if not image_ref:+ raise ModlyCliError(f"ComfyUI prompt {prompt_id} completed without a supported image output", code="NO_WORKFLOW_OUTPUT")++ out_path: Path | None = getattr(args, "comfy_output", None)+ if out_path:+ out = Path(out_path).expanduser().resolve()+ else:+ out = _temp_path_for_comfy_ref(image_ref, default_suffix=".png")+ bytes_written = _download_comfy_ref(host, image_ref, out, timeout=args.request_timeout)+ return {+ "ok": True,+ "comfy_url": host,+ "workflow": comfy["workflow"],+ "prompt_id": prompt_id,+ "image_path": str(out),+ "bytes_written": bytes_written,+ "image": image_ref,+ }+++def _run_comfy_image(args: argparse.Namespace) -> dict[str, Any]:+ comfy = _run_comfy_workflow(args)+ return _download_comfy_image_output(args, comfy)+++def cmd_comfy_image(args: argparse.Namespace) -> int:+ result = _run_comfy_image(args)+ result["meta"] = {"experimental": True, "canonical": False}+ _json_print(result, compact=args.compact)+ return 0+++def cmd_generate_from_workflow(args: argparse.Namespace) -> int:+ comfy = _run_comfy_workflow(args)+ host = str(comfy["comfy_url"])+ prompt_id = str(comfy["prompt_id"])+ history = comfy["history"] if isinstance(comfy.get("history"), dict) else {}+ asset_ref = _find_comfy_file_ref(history, WORKFLOW_ASSET_SUFFIXES)+ if asset_ref:+ if not args.output:+ raise ModlyCliError("--output is required when a workflow produces a direct 3D asset", code="OUTPUT_REQUIRED")+ export_dest = Path(args.output).expanduser().resolve()+ bytes_written = _download_comfy_ref(host, asset_ref, export_dest, timeout=args.request_timeout)+ _json_print({+ "ok": True,+ "source": "comfy-workflow",+ "output_type": "asset",+ "export_path": str(export_dest),+ "bytes_written": bytes_written,+ "workflow": comfy["workflow"],+ "prompt_id": prompt_id,+ "comfy_url": host,+ "asset": asset_ref,+ "meta": {"experimental": True, "canonical": False},+ }, compact=args.compact)+ return 0++ comfy_image = _download_comfy_image_output(args, comfy)+ _require_health(args.base_url.rstrip("/"), args.request_timeout)+ output = Path(args.output).expanduser().resolve() if args.output else None+ result = _generate_one(args, Path(str(comfy_image["image_path"])), output)+ result["source"] = "comfy-workflow"+ result["output_type"] = "image"+ result["comfy"] = comfy_image+ result.setdefault("meta", {})["experimental"] = True+ _json_print(result, compact=args.compact)+ return 0+++def _canonical_generation_params(args: argparse.Namespace) -> dict[str, Any]:+ params = _parse_params(getattr(args, "params_json", None), getattr(args, "params_file", None))+ params.setdefault("remesh", getattr(args, "remesh", "quad"))+ params.setdefault("enable_texture", bool(getattr(args, "enable_texture", True)))+ params.setdefault("texture_resolution", getattr(args, "texture_resolution", 1024))+ return params+++def _workflow_workspace_path(status: dict[str, Any]) -> str:+ scene_candidate = status.get("scene_candidate")+ if isinstance(scene_candidate, dict) and scene_candidate.get("workspace_path"):+ return _validate_workspace_path(str(scene_candidate["workspace_path"]))+ output_url = str(status.get("output_url") or "")+ if output_url:+ return _workspace_relative_path(output_url)+ raise ModlyCliError(f"Workflow run completed without an output path: {status}", code="MISSING_OUTPUT")+++def _start_workflow_run(args: argparse.Namespace, image_path: Path, *, base_url: str, model_id: str, params: dict[str, Any]) -> tuple[str, dict[str, Any]]:+ fields = {+ "model_id": model_id,+ "params": json.dumps(params, separators=(",", ":")),+ }+ if getattr(args, "collection", None):+ fields["collection"] = str(args.collection)+ body, content_type = _multipart_form(fields, "image", image_path)+ started = _request_json(+ "POST",+ f"{base_url}/workflow-runs/from-image",+ timeout=args.request_timeout,+ data=body,+ headers={"Content-Type": content_type},+ )+ run_id = started.get("run_id") if isinstance(started, dict) else None+ if not run_id:+ raise ModlyCliError(f"Modly did not return a run_id: {started}", code="MISSING_RUN_ID")+ return str(run_id), started if isinstance(started, dict) else {"raw": started}+++def _poll_workflow_run(args: argparse.Namespace, *, base_url: str, run_id: str, progress_label: str = "workflow-run") -> tuple[dict[str, Any], str]:+ deadline = time.monotonic() + args.timeout+ last_status: dict[str, Any] = {}+ while time.monotonic() < deadline:+ status = _request_json("GET", f"{base_url}/workflow-runs/{urllib.parse.quote(str(run_id))}", timeout=args.request_timeout)+ last_status = status if isinstance(status, dict) else {"raw": status}+ state = last_status.get("status")+ if state == "done":+ return last_status, _workflow_workspace_path(last_status)+ if state in {"error", "cancelled"}:+ raise ModlyCliError(f"Workflow run {run_id} ended with status {state}: {last_status}", code="WORKFLOW_RUN_FAILED")+ if getattr(args, "progress", False) and not getattr(args, "quiet", False):+ progress = last_status.get("progress", 0)+ step = last_status.get("step", "")+ print(json.dumps({"phase": progress_label, "run_id": run_id, "status": state, "progress": progress, "step": step}), file=sys.stderr)+ time.sleep(args.poll)++ raise ModlyCliError(f"Timed out waiting for workflow run {run_id}. Last status: {last_status}", code="TIMEOUT")+++def _run_workflow_run(+ args: argparse.Namespace,+ image_path: Path,+ *,+ base_url: str,+ model_id: str,+ params: dict[str, Any],+ wait: bool,+) -> tuple[str, dict[str, Any], str | None]:+ run_id, started = _start_workflow_run(args, image_path, base_url=base_url, model_id=model_id, params=params)+ if not wait:+ return run_id, started, None+ status, rel_path = _poll_workflow_run(args, base_url=base_url, run_id=run_id)+ return run_id, status, rel_path+++def cmd_workflow_run_start(args: argparse.Namespace) -> int:+ base_url = args.base_url.rstrip("/")+ _require_health(base_url, args.request_timeout)+ image_path = Path(args.image).expanduser().resolve()+ if not image_path.exists() or not image_path.is_file():+ raise ModlyCliError(f"image file not found: {image_path}", code="IMAGE_NOT_FOUND")+ model_id = _resolve_model_id(args, base_url)+ params = _canonical_generation_params(args)+ run_id, status, rel_path = _run_workflow_run(args, image_path, base_url=base_url, model_id=model_id, params=params, wait=getattr(args, "wait", False))+ payload: dict[str, Any] = {+ "ok": True,+ "base_url": base_url,+ "image": str(image_path),+ "model_id": model_id,+ "run": {"kind": "workflowRun", "id": run_id},+ "status": status,+ "meta": _recovery_meta(base_url, run_id),+ }+ if rel_path:+ payload["workspace_path"] = rel_path+ _json_print(payload, compact=args.compact)+ return 0+++def cmd_workflow_run_status(args: argparse.Namespace) -> int:+ base_url = args.base_url.rstrip("/")+ _require_health(base_url, args.request_timeout)+ status = _request_json("GET", f"{base_url}/workflow-runs/{urllib.parse.quote(args.run_id)}", timeout=args.request_timeout)+ _json_print({"ok": True, "base_url": base_url, "run": {"kind": "workflowRun", "id": args.run_id}, "status": status, "meta": _recovery_meta(base_url, args.run_id)}, compact=args.compact)+ return 0+++def cmd_workflow_run_cancel(args: argparse.Namespace) -> int:+ base_url = args.base_url.rstrip("/")+ _require_health(base_url, args.request_timeout)+ result = _request_json("POST", f"{base_url}/workflow-runs/{urllib.parse.quote(args.run_id)}/cancel", timeout=args.request_timeout)+ _json_print({"ok": True, "base_url": base_url, "run": {"kind": "workflowRun", "id": args.run_id}, "cancel": result, "meta": _recovery_meta(base_url, args.run_id)}, compact=args.compact)+ return 0+++def _ensure_no_external_texture_process(args: argparse.Namespace) -> None:+ if getattr(args, "texture_model", "auto") not in (None, "", "auto"):+ raise _unsupported_process()+ if getattr(args, "texture_params_json", None) or getattr(args, "texture_params_file", None):+ raise _unsupported_process()+++def _run_generation_job(+ args: argparse.Namespace,+ image_path: Path,+ *,+ base_url: str,+ model_id: str,+ params: dict[str, Any],+ progress_label: str,+) -> tuple[str, dict[str, Any], str]:+ fields = {+ "model_id": model_id,+ "collection": args.collection,+ "remesh": args.remesh,+ "enable_texture": "true" if getattr(args, "enable_texture", True) else "false",+ "texture_resolution": str(getattr(args, "texture_resolution", 1024)),+ "params": json.dumps(params, separators=(",", ":")),+ }+ body, content_type = _multipart_form(fields, "image", image_path)+ started = _request_json(+ "POST",+ f"{base_url}/generate/from-image",+ timeout=args.request_timeout,+ data=body,+ headers={"Content-Type": content_type},+ )+ job_id = started.get("job_id") if isinstance(started, dict) else None+ if not job_id:+ raise ModlyCliError(f"Modly did not return a job_id: {started}")++ deadline = time.monotonic() + args.timeout+ last_status: dict[str, Any] = {}+ while time.monotonic() < deadline:+ status = _request_json("GET", f"{base_url}/generate/status/{urllib.parse.quote(str(job_id))}", timeout=args.request_timeout)+ last_status = status if isinstance(status, dict) else {"raw": status}+ state = last_status.get("status")+ if state == "done":+ output_url = str(last_status.get("output_url") or "")+ if not output_url:+ raise ModlyCliError(f"Job completed without output_url: {last_status}")+ return str(job_id), last_status, _workspace_relative_path(output_url)+ if state in {"error", "cancelled"}:+ raise ModlyCliError(f"Job {job_id} ended with status {state}: {last_status}")+ if getattr(args, "progress", False) and not getattr(args, "quiet", False):+ progress = last_status.get("progress", 0)+ step = last_status.get("step", "")+ print(json.dumps({"phase": progress_label, "job_id": job_id, "status": state, "progress": progress, "step": step}), file=sys.stderr)+ time.sleep(args.poll)++ raise ModlyCliError(f"Timed out waiting for job {job_id}. Last status: {last_status}")+++def _generate_one(args: argparse.Namespace, image_path: Path, output_path: Path | None = None) -> dict[str, Any]:+ base_url = args.base_url.rstrip("/")+ _require_health(base_url, args.request_timeout)+ image_path = image_path.expanduser().resolve()+ if not image_path.exists() or not image_path.is_file():+ raise ModlyCliError(f"image file not found: {image_path}", code="IMAGE_NOT_FOUND")++ _ensure_no_external_texture_process(args)+ params = _canonical_generation_params(args)+ model_id = _resolve_model_id(args, base_url)+ run_id, status, rel_path = _run_workflow_run(+ args,+ image_path,+ base_url=base_url,+ model_id=model_id,+ params=params,+ wait=True,+ )+ assert rel_path is not None++ export_dest = None+ bytes_written = None+ if not getattr(args, "no_export", False):+ export_dest = output_path or image_path.resolve().parent / f"{Path(rel_path).stem}.{args.format}"+ export_dest = export_dest.expanduser().resolve()+ bytes_written = _export_workspace_path(base_url, rel_path, args.format, export_dest, timeout=args.request_timeout)+ result: dict[str, Any] = {+ "ok": True,+ "base_url": base_url,+ "image": str(image_path),+ "model_id": model_id,+ "run": {"kind": "workflowRun", "id": run_id},+ "status": status,+ "workspace_path": rel_path,+ "texture_enabled": bool(params.get("enable_texture")),+ "export_format": args.format,+ "meta": _recovery_meta(base_url, run_id),+ }+ if export_dest is not None:+ result["export_path"] = str(export_dest)+ result["bytes_written"] = bytes_written+ return result+++def cmd_generate(args: argparse.Namespace) -> int:+ output = Path(args.output).expanduser().resolve() if args.output else None+ result = _generate_one(args, Path(args.image), output)+ _json_print(result, compact=args.compact)+ return 0+++def cmd_legacy_generate(args: argparse.Namespace) -> int:+ base_url = args.base_url.rstrip("/")+ _require_health(base_url, args.request_timeout)+ image_path = Path(args.image).expanduser().resolve()+ if not image_path.exists() or not image_path.is_file():+ raise ModlyCliError(f"image file not found: {image_path}", code="IMAGE_NOT_FOUND")+ params = _parse_params(getattr(args, "params_json", None), getattr(args, "params_file", None))+ model_id = _resolve_model_id(args, base_url)+ job_id, status, rel_path = _run_generation_job(+ args,+ image_path,+ base_url=base_url,+ model_id=model_id,+ params=params,+ progress_label="legacy-generate",+ )+ export_dest = None+ bytes_written = None+ if not getattr(args, "no_export", False):+ export_dest = Path(args.output).expanduser().resolve() if args.output else image_path.resolve().parent / f"{Path(rel_path).stem}.{args.format}"+ bytes_written = _export_workspace_path(base_url, rel_path, args.format, export_dest, timeout=args.request_timeout)+ payload: dict[str, Any] = {+ "ok": True,+ "base_url": base_url,+ "image": str(image_path),+ "model_id": model_id,+ "job_id": job_id,+ "status": status,+ "workspace_path": rel_path,+ "export_format": args.format,+ "meta": _recovery_meta(base_url, job_id, legacy=True),+ }+ if export_dest is not None:+ payload["export_path"] = str(export_dest)+ payload["bytes_written"] = bytes_written+ _json_print(payload, compact=args.compact)+ return 0+++def cmd_export(args: argparse.Namespace) -> int:+ base_url = args.base_url.rstrip("/")+ _require_health(base_url, args.request_timeout)+ dest = Path(args.output).expanduser().resolve()+ bytes_written = _export_workspace_path(base_url, args.path, args.format, dest, timeout=args.request_timeout)+ _json_print({+ "ok": True,+ "base_url": base_url,+ "workspace_path": args.path,+ "export_format": args.format,+ "export_path": str(dest),+ "bytes_written": bytes_written,+ }, compact=args.compact)+ return 0+++def _iter_images(input_dir: Path) -> list[Path]:+ if not input_dir.exists() or not input_dir.is_dir():+ raise ModlyCliError(f"input directory not found: {input_dir}")+ return sorted(p for p in input_dir.iterdir() if p.is_file() and p.suffix.lower() in IMAGE_SUFFIXES)+++def _manifest_jobs(path: Path, fallback_output_dir: Path | None, default_format: str) -> list[tuple[Path, Path | None, str]]:+ try:+ raw = json.loads(path.read_text(encoding="utf-8"))+ except json.JSONDecodeError as exc:+ raise ModlyCliError(f"manifest must be valid JSON: {exc}") from exc+ entries = raw.get("jobs", raw.get("images")) if isinstance(raw, dict) else raw+ if not isinstance(entries, list):+ raise ModlyCliError("manifest must be a JSON list or object with a jobs/images list")++ jobs: list[tuple[Path, Path | None, str]] = []+ for index, entry in enumerate(entries):+ if isinstance(entry, str):+ image = Path(entry)+ fmt = default_format+ output = None+ elif isinstance(entry, dict):+ image_value = entry.get("image") or entry.get("image_path") or entry.get("path")+ if not image_value:+ raise ModlyCliError(f"manifest entry {index} is missing image")+ image = Path(str(image_value))+ fmt = str(entry.get("format") or default_format)+ if fmt not in EXPORT_FORMATS:+ raise ModlyCliError(f"manifest entry {index} has unsupported format: {fmt}")+ output = Path(str(entry["output"])) if entry.get("output") else None+ else:+ raise ModlyCliError(f"manifest entry {index} must be a string or object")++ if not image.is_absolute():+ image = path.parent / image+ if output is None and fallback_output_dir is not None:+ output = fallback_output_dir / f"{image.stem}.{fmt}"+ elif output is not None and not output.is_absolute():+ output = path.parent / output+ jobs.append((image, output, fmt))+ return jobs+++def cmd_batch(args: argparse.Namespace) -> int:+ output_dir = Path(args.output_dir).expanduser().resolve() if args.output_dir else None+ if output_dir:+ output_dir.mkdir(parents=True, exist_ok=True)+ if args.manifest:+ jobs = _manifest_jobs(Path(args.manifest).expanduser().resolve(), output_dir, args.format)+ else:+ if not args.input_dir or output_dir is None:+ raise ModlyCliError("batch requires --input-dir and --output-dir, or --manifest with per-entry outputs")+ input_dir = Path(args.input_dir).expanduser().resolve()+ jobs = [(image, output_dir / f"{image.stem}.{args.format}", args.format) for image in _iter_images(input_dir)]++ results: list[dict[str, Any]] = []+ failures = 0+ original_format = args.format+ try:+ for image, output, fmt in jobs:+ args.format = fmt+ try:+ results.append(_generate_one(args, image, output))+ except ModlyCliError as exc:+ failures += 1+ results.append({"ok": False, "image": str(image), "error": str(exc)})+ if not args.continue_on_error:+ break+ finally:+ args.format = original_format+ _json_print({"ok": failures == 0, "count": len(results), "failures": failures, "results": results}, compact=args.compact)+ return 0 if failures == 0 else 1+++def cmd_serve(args: argparse.Namespace) -> int:+ api_dir, _python, env, cmd, base_url = _resolve_serve_config(args)+ public_env = {k: env.get(k, "") for k in ["MODELS_DIR", "WORKSPACE_DIR", "EXTENSIONS_DIR", "SELECTED_MODEL_ID"]}+ meta = {"dev_only": True, "canonical": False}+ if args.print_command:+ _json_print({"ok": True, "cmd": cmd, "cwd": str(api_dir), "base_url": base_url, "env": public_env, "meta": meta}, compact=args.compact)+ return 0+ proc = _start_backend(cmd, api_dir=api_dir, env=env, detach=args.detach)+ if args.detach:+ _json_print({"ok": True, "started": True, "pid": proc.pid, "base_url": base_url, "cmd": cmd, "cwd": str(api_dir), "env": public_env, "meta": meta}, compact=args.compact)+ return 0+ return int(proc.wait())+++def cmd_ensure_server(args: argparse.Namespace) -> int:+ base_url = args.base_url.rstrip("/")+ health = _try_health(base_url, args.request_timeout)+ meta = {"dev_only": True, "canonical": False}+ if health:+ _json_print({"ok": True, "started": False, "base_url": base_url, "health": health, "meta": meta}, compact=args.compact)+ return 0+ if not args.start:+ message = "Modly API is not running; launch Modly or run ensure-server --start"+ if args.fail_on_unavailable:+ raise ModlyCliError(message, code="API_UNAVAILABLE")+ _json_print({"ok": False, "started": False, "base_url": base_url, "error": message, "code": "API_UNAVAILABLE", "message": message, "meta": meta}, compact=args.compact)+ return 0+ api_dir, _python, env, cmd, resolved_url = _resolve_serve_config(args)+ public_env = {k: env.get(k, "") for k in ["MODELS_DIR", "WORKSPACE_DIR", "EXTENSIONS_DIR", "SELECTED_MODEL_ID"]}+ if args.print_command:+ _json_print({"ok": True, "started": False, "would_start": True, "base_url": resolved_url, "cmd": cmd, "cwd": str(api_dir), "env": public_env, "meta": meta}, compact=args.compact)+ return 0+ proc = _start_backend(cmd, api_dir=api_dir, env=env, detach=args.detach)+ _json_print({"ok": True, "started": True, "pid": proc.pid, "base_url": resolved_url, "cmd": cmd, "cwd": str(api_dir), "env": public_env, "meta": meta}, compact=args.compact)+ if not args.detach:+ return int(proc.wait())+ return 0+++def cmd_capability_list(args: argparse.Namespace) -> int:+ base_url = args.base_url.rstrip("/")+ _require_health(base_url, args.request_timeout)+ data = _request_supported_contract("GET", f"{base_url}/automation/capabilities", timeout=args.request_timeout)+ _json_print({"ok": True, "base_url": base_url, "capabilities": data}, compact=args.compact)+ return 0+++def _json_arg(value: str | None, file_value: str | None) -> dict[str, Any]:+ return _parse_params(value, file_value)+++def cmd_process_run_start(args: argparse.Namespace) -> int:+ base_url = args.base_url.rstrip("/")+ _require_health(base_url, args.request_timeout)+ payload = _json_arg(getattr(args, "input_json", None), getattr(args, "input_file", None))+ body = json.dumps({"process": args.process, "input": payload}, separators=(",", ":")).encode("utf-8")+ data = _request_supported_contract("POST", f"{base_url}/process-runs", timeout=args.request_timeout, data=body, headers={"Content-Type": "application/json"})+ run_id = data.get("run_id") if isinstance(data, dict) else None+ output = {"ok": True, "base_url": base_url, "run": {"kind": "processRun", "id": str(run_id) if run_id else ""}, "status": data}+ if run_id:+ output["meta"] = _recovery_meta(base_url, str(run_id), kind="process-run")+ _json_print(output, compact=args.compact)+ return 0+++def cmd_process_run_status(args: argparse.Namespace) -> int:+ base_url = args.base_url.rstrip("/")+ _require_health(base_url, args.request_timeout)+ data = _request_supported_contract("GET", f"{base_url}/process-runs/{urllib.parse.quote(args.run_id)}", timeout=args.request_timeout)+ _json_print({"ok": True, "base_url": base_url, "run": {"kind": "processRun", "id": args.run_id}, "status": data}, compact=args.compact)+ return 0+++def cmd_process_run_cancel(args: argparse.Namespace) -> int:+ base_url = args.base_url.rstrip("/")+ _require_health(base_url, args.request_timeout)+ data = _request_supported_contract("POST", f"{base_url}/process-runs/{urllib.parse.quote(args.run_id)}/cancel", timeout=args.request_timeout)+ _json_print({"ok": True, "base_url": base_url, "run": {"kind": "processRun", "id": args.run_id}, "cancel": data}, compact=args.compact)+ return 0+++def _add_comfy_options(parser: argparse.ArgumentParser) -> None:+ parser.add_argument("--workflow", default="Trellis2Workflow", help="ComfyUI API-format workflow path or saved workflow name (default: Trellis2Workflow)")+ parser.add_argument("--prompt", help="Prompt text to inject into the first positive text/prompt input")+ parser.add_argument("--seed", type=int, help="Seed to inject into seed/noise_seed inputs")+ parser.add_argument("--comfy-url", default=os.environ.get("COMFYUI_URL", "http://127.0.0.1:8188"), help="ComfyUI API URL (default: http://127.0.0.1:8188)")+ parser.add_argument("--comfy-output", help="Where to save the ComfyUI image output before passing it to Modly")+++def _add_generation_options(parser: argparse.ArgumentParser, *, image: bool, output: bool, batch: bool = False) -> None:+ if image:+ parser.add_argument("--image", required=True, help="Input image path")+ if output:+ parser.add_argument("--output", help="Export destination path. Defaults beside the input image")+ parser.add_argument("--no-export", action="store_true", help="Do not download/export the completed workspace mesh")+ parser.add_argument("--format", choices=EXPORT_FORMATS, default="glb", help="Export format (default: glb)")+ parser.add_argument("--model", default="auto", help="Model id to use, 'active', or 'auto' (default: auto)")+ parser.add_argument("--collection", default="Agent", help="Modly workspace collection (default: Agent)")+ parser.add_argument("--remesh", choices=["quad", "triangle", "none"], default="quad", help="Remesh mode (default: quad)")+ parser.add_argument("--texture", dest="enable_texture", action="store_true", default=True, help="Enable texture generation (default)")+ parser.add_argument("--no-texture", dest="enable_texture", action="store_false", help="Disable texture generation for faster geometry-only smoke tests")+ parser.add_argument("--enable-texture", dest="enable_texture", action="store_true", help=argparse.SUPPRESS)+ parser.add_argument("--texture-resolution", type=int, default=1024, help="Texture diffusion resolution when texturing is enabled")+ parser.add_argument("--texture-model", default="auto", help="External texture process id. Unsupported unless the server exposes canonical process-run support.")+ parser.add_argument("--texture-size", type=int, default=2048, help="Texture atlas size when texturing is enabled (default: 2048)")+ parser.add_argument("--texture-steps", type=int, default=30, help="Texture diffusion steps when texturing is enabled (default: 30)")+ parser.add_argument("--texture-guidance", type=float, default=3.0, help="Texture guidance strength when texturing is enabled (default: 3.0)")+ parser.add_argument("--texture-params-json", help="External texture process params as a JSON object")+ parser.add_argument("--texture-params-file", help="Path to external texture process params JSON file")+ parser.add_argument("--params-json", help="Model-specific params as a JSON object")+ parser.add_argument("--params-file", help="Path to model-specific params JSON file")+ parser.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT_SECONDS, help=f"Generation timeout in seconds (default: {DEFAULT_TIMEOUT_SECONDS})")+ parser.add_argument("--poll", type=float, default=DEFAULT_POLL_SECONDS, help=f"Polling interval in seconds (default: {DEFAULT_POLL_SECONDS})")+ parser.add_argument("--progress", action="store_true", help="Emit progress JSON lines to stderr while waiting")+ if batch:+ parser.add_argument("--continue-on-error", action="store_true", help="Continue batch after an image fails")+++def _add_serve_options(parser: argparse.ArgumentParser, *, include_start: bool = False) -> None:+ if include_start:+ parser.add_argument("--start", action="store_true", help="Start the backend if health check fails")+ parser.add_argument("--api-dir", help="Directory containing Modly API main.py")+ parser.add_argument("--python", help="Python executable with Modly API dependencies installed")+ parser.add_argument("--host", default="127.0.0.1", help="Backend host (default: 127.0.0.1)")+ parser.add_argument("--port", type=int, default=8765, help="Backend port (default: 8765)")+ parser.add_argument("--models-dir", help="Models directory for the backend")+ parser.add_argument("--workspace-dir", help="Workspace directory for generated meshes")+ parser.add_argument("--extensions-dir", help="Extensions directory for the backend")+ parser.add_argument("--model", help="Initial SELECTED_MODEL_ID")+ parser.add_argument("--hf-token", help="Hugging Face token for gated models")+ parser.add_argument("--detach", action="store_true", help="Start in background and print pid")+ parser.add_argument("--print-command", action="store_true", help="Print resolved command/env without starting")+++class JsonArgumentParser(argparse.ArgumentParser):+ def error(self, message: str) -> None:+ raise ModlyCliError(message, code="INVALID_ARGUMENTS")+++def build_parser() -> argparse.ArgumentParser:+ parser = JsonArgumentParser(+ prog="modly-cli",+ description="Tiny stdlib-only CLI for agents calling a running Modly desktop API.",+ )+ parser.add_argument("--base-url", default=DEFAULT_BASE_URL, help=f"Modly API URL (default: {DEFAULT_BASE_URL})")+ parser.add_argument("--request-timeout", type=float, default=30, help="Per-request timeout in seconds (default: 30)")+ parser.add_argument("--compact", action="store_true", help="Print compact one-line JSON")+ parser.add_argument("--quiet", action="store_true", help="Suppress progress output; final JSON is still printed")+ canonical_commands = "{health,model,workflow-run,capability,process-run,generate,dev,experimental,legacy}"+ sub = parser.add_subparsers(dest="command", required=True, metavar=canonical_commands)++ health = sub.add_parser("health", help="Check that Modly's local API is reachable")+ health.set_defaults(func=cmd_health)++ status = sub.add_parser("status", help=argparse.SUPPRESS)+ status.set_defaults(func=cmd_status)++ model = sub.add_parser("model", help="Inspect canonical model state")+ model_sub = model.add_subparsers(dest="model_command", required=True)+ model_list = model_sub.add_parser("list", help="List model adapters known to the running app")+ model_list.set_defaults(func=cmd_model_list)+ model_status = model_sub.add_parser("status", help="Show active model status")+ model_status.set_defaults(func=cmd_model_status)+ model_params = model_sub.add_parser("params", help="Show parameter schema for a validated model id")+ model_params.add_argument("--model", default="auto", help="Model id, 'active', or 'auto' for the validated active model (default: auto)")+ model_params.set_defaults(func=cmd_params)++ workflow = sub.add_parser("workflow-run", help="Start, inspect, and cancel canonical workflow runs")+ workflow_sub = workflow.add_subparsers(dest="workflow_command", required=True)+ workflow_start = workflow_sub.add_parser("start", help="Start a workflow run from an image")+ _add_generation_options(workflow_start, image=True, output=False)+ workflow_start.add_argument("--wait", action="store_true", help="Wait for completion and include workspace_path")+ workflow_start.set_defaults(func=cmd_workflow_run_start)+ workflow_status = workflow_sub.add_parser("status", help="Show workflow run status")+ workflow_status.add_argument("run_id")+ workflow_status.set_defaults(func=cmd_workflow_run_status)+ workflow_cancel = workflow_sub.add_parser("cancel", help="Cancel a workflow run")+ workflow_cancel.add_argument("run_id")+ workflow_cancel.set_defaults(func=cmd_workflow_run_cancel)++ capability = sub.add_parser("capability", help="Discover canonical automation capabilities")+ capability_sub = capability.add_subparsers(dest="capability_command", required=True)+ capability_list = capability_sub.add_parser("list", help="List automation capabilities when the server exposes them")+ capability_list.set_defaults(func=cmd_capability_list)++ process = sub.add_parser("process-run", help="Start, inspect, and cancel canonical process runs")+ process_sub = process.add_subparsers(dest="process_command", required=True)+ process_start = process_sub.add_parser("start", help="Start a process run when the server exposes the canonical contract")+ process_start.add_argument("--process", required=True, help="Canonical process id")+ process_start.add_argument("--input-json", help="Process input as a JSON object")+ process_start.add_argument("--input-file", help="Path to process input JSON object")+ process_start.set_defaults(func=cmd_process_run_start)+ process_status = process_sub.add_parser("status", help="Show process run status")+ process_status.add_argument("run_id")+ process_status.set_defaults(func=cmd_process_run_status)+ process_cancel = process_sub.add_parser("cancel", help="Cancel a process run")+ process_cancel.add_argument("run_id")+ process_cancel.set_defaults(func=cmd_process_run_cancel)++ gen = sub.add_parser("generate", help="Generate a 3D mesh from an image, wait, export it, and print JSON")+ _add_generation_options(gen, image=True, output=True)+ gen.set_defaults(func=cmd_generate)++ exp = sub.add_parser("export", help=argparse.SUPPRESS)+ exp.add_argument("--path", required=True, help="Workspace-relative mesh path, e.g. Agent/foo.glb")+ exp.add_argument("--output", required=True, help="Destination file path")+ exp.add_argument("--format", choices=EXPORT_FORMATS, default="glb", help="Export format (default: glb)")+ exp.set_defaults(func=cmd_export)++ batch = sub.add_parser("batch", help=argparse.SUPPRESS)+ group = batch.add_mutually_exclusive_group(required=True)+ group.add_argument("--input-dir", help="Directory of .png/.jpg/.jpeg/.webp images")+ group.add_argument("--manifest", help="JSON list or object with jobs/images entries")+ batch.add_argument("--output-dir", help="Directory for exported meshes; required for --input-dir")+ _add_generation_options(batch, image=False, output=False, batch=True)+ batch.set_defaults(func=cmd_batch)++ dev = sub.add_parser("dev", help="Developer-only local API helpers")+ dev_sub = dev.add_subparsers(dest="dev_command", required=True)+ serve = dev_sub.add_parser("serve-api", help="Start only the FastAPI backend without Electron/Desktop bridge readiness")+ _add_serve_options(serve)+ serve.set_defaults(func=cmd_serve)+ ensure = dev_sub.add_parser("ensure-server", help="Check API health and optionally start only the FastAPI backend")+ _add_serve_options(ensure, include_start=True)+ ensure.add_argument("--fail-on-unavailable", action="store_true", help="Exit nonzero when API is unavailable")+ ensure.set_defaults(func=cmd_ensure_server)++ experimental = sub.add_parser("experimental", help="Experimental external orchestration helpers")+ experimental_sub = experimental.add_subparsers(dest="experimental_command", required=True)+ comfy = experimental_sub.add_parser("comfy-image", help="Run a preconfigured ComfyUI workflow and save its first image output")+ _add_comfy_options(comfy)+ comfy.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT_SECONDS, help=f"ComfyUI timeout in seconds (default: {DEFAULT_TIMEOUT_SECONDS})")+ comfy.add_argument("--poll", type=float, default=DEFAULT_POLL_SECONDS, help=f"Polling interval in seconds (default: {DEFAULT_POLL_SECONDS})")+ comfy.add_argument("--progress", action="store_true", help="Emit progress JSON lines to stderr while waiting")+ comfy.set_defaults(func=cmd_comfy_image)+ wf = experimental_sub.add_parser("generate-from-workflow", help="Run a ComfyUI workflow and save or convert its output")+ _add_comfy_options(wf)+ _add_generation_options(wf, image=False, output=True)+ wf.set_defaults(func=cmd_generate_from_workflow)++ legacy = sub.add_parser("legacy", help="Explicit compatibility commands for /generate/* endpoints")+ legacy_sub = legacy.add_subparsers(dest="legacy_command", required=True)+ legacy_job = legacy_sub.add_parser("job", help="Show one legacy generation job status")+ legacy_job.add_argument("job_id")+ legacy_job.set_defaults(func=cmd_job)+ legacy_cancel = legacy_sub.add_parser("cancel", help="Cancel one legacy generation job")+ legacy_cancel.add_argument("job_id")+ legacy_cancel.set_defaults(func=cmd_cancel)+ legacy_gen = legacy_sub.add_parser("generate", help="Use the legacy /generate/from-image endpoint explicitly")+ _add_generation_options(legacy_gen, image=True, output=True)+ legacy_gen.set_defaults(func=cmd_legacy_generate)++ models_alias = sub.add_parser("models", help=argparse.SUPPRESS)+ models_alias.set_defaults(func=cmd_models)+ params_alias = sub.add_parser("params", help=argparse.SUPPRESS)+ params_alias.add_argument("--model", default="auto")+ params_alias.set_defaults(func=cmd_params)+ job_alias = sub.add_parser("job", help=argparse.SUPPRESS)+ job_alias.add_argument("job_id")+ job_alias.set_defaults(func=cmd_job)+ cancel_alias = sub.add_parser("cancel", help=argparse.SUPPRESS)+ cancel_alias.add_argument("job_id")+ cancel_alias.set_defaults(func=cmd_cancel)+ serve_alias = sub.add_parser("serve", help=argparse.SUPPRESS)+ _add_serve_options(serve_alias)+ serve_alias.set_defaults(func=cmd_serve)+ ensure_alias = sub.add_parser("ensure-server", help=argparse.SUPPRESS)+ _add_serve_options(ensure_alias, include_start=True)+ ensure_alias.add_argument("--fail-on-unavailable", action="store_true")+ ensure_alias.set_defaults(func=cmd_ensure_server)+ comfy_alias = sub.add_parser("comfy-image", help=argparse.SUPPRESS)+ _add_comfy_options(comfy_alias)+ comfy_alias.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT_SECONDS)+ comfy_alias.add_argument("--poll", type=float, default=DEFAULT_POLL_SECONDS)+ comfy_alias.add_argument("--progress", action="store_true")+ comfy_alias.set_defaults(func=cmd_comfy_image)+ wf_alias = sub.add_parser("generate-from-workflow", help=argparse.SUPPRESS)+ _add_comfy_options(wf_alias)+ _add_generation_options(wf_alias, image=False, output=True)+ wf_alias.set_defaults(func=cmd_generate_from_workflow)+ hidden = {"status", "export", "batch", "models", "params", "job", "cancel", "serve", "ensure-server", "comfy-image", "generate-from-workflow"}+ # Hide compatibility aliases from help; argparse only exposes this via a private list.+ sub._choices_actions = [choice for choice in sub._choices_actions if getattr(choice, "dest", None) not in hidden]+ return parser+++def main(argv: list[str] | None = None) -> int:+ parser = build_parser()+ args = None+ try:+ args = parser.parse_args(argv)+ return int(args.func(args))+ except ModlyCliError as exc:+ _json_print({"ok": False, "code": exc.code, "message": exc.message, "error": exc.message}, compact=getattr(args, "compact", False) if args else False)+ return 1+ except SystemExit as exc:+ code = exc.code+ if code in (None, 0):+ return 0+ message = str(code)+ _json_print({"ok": False, "code": "INVALID_ARGUMENTS", "message": message, "error": message}, compact=getattr(args, "compact", False) if args else False)+ return 1+ except KeyboardInterrupt:+ _json_print({"ok": False, "code": "INTERRUPTED", "message": "interrupted", "error": "interrupted"}, compact=getattr(args, "compact", False) if args else False)+ return 130+ except Exception as exc:+ _json_print({"ok": False, "code": "UNEXPECTED_ERROR", "message": str(exc), "error": str(exc)}, compact=getattr(args, "compact", False) if args else False)+ return 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/apps/forge-desktop/tools/modly-cli/test_agent.py b/apps/forge-desktop/tools/modly-cli/test_agent.pynew file mode 100644index 000000000..9537ec1af--- /dev/null+++ b/apps/forge-desktop/tools/modly-cli/test_agent.py@@ -0,0 +1,548 @@+#!/usr/bin/env python3+"""Unit tests for the stdlib-only Modly agent CLI."""+from __future__ import annotations++import importlib.util+import io+import json+import os+import tempfile+import unittest+from contextlib import redirect_stdout+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++MODULE_PATH = Path(__file__).with_name("agent.py")+SPEC = importlib.util.spec_from_file_location("modly_agent", MODULE_PATH)+agent = importlib.util.module_from_spec(SPEC)+assert SPEC and SPEC.loader+SPEC.loader.exec_module(agent)+++class OutputTests(unittest.TestCase):+ def test_compact_json_is_one_line(self) -> None:+ buf = io.StringIO()+ with redirect_stdout(buf):+ agent._json_print({"ok": True, "nested": {"x": 1}}, compact=True)+ self.assertEqual(buf.getvalue(), '{"nested":{"x":1},"ok":true}\n')+++class CommandTests(unittest.TestCase):+ def test_status_combines_health_and_model(self) -> None:+ calls: list[tuple[str, str]] = []++ def fake_request(method: str, url: str, *, timeout: float, **_: object) -> object:+ calls.append((method, url))+ if url.endswith("/health"):+ return {"status": "ok"}+ if url.endswith("/model/status"):+ return {"id": "sf3d", "loaded": True}+ raise AssertionError(url)++ args = SimpleNamespace(base_url="http://example.test/", request_timeout=1, compact=True)+ buf = io.StringIO()+ with patch.object(agent, "_request_json", fake_request), redirect_stdout(buf):+ self.assertEqual(agent.cmd_status(args), 0)+ payload = json.loads(buf.getvalue())+ self.assertEqual(payload["health"], {"status": "ok"})+ self.assertEqual(payload["model"]["id"], "sf3d")+ self.assertEqual(calls, [("GET", "http://example.test/health"), ("GET", "http://example.test/model/status")])++ def test_params_auto_uses_validated_active_model_id(self) -> None:+ calls: list[str] = []++ def fake_request(method: str, url: str, *, timeout: float, **_: object) -> object:+ calls.append(url)+ if url.endswith("/health"):+ return {"status": "ok"}+ if url.endswith("/model/status"):+ return {"id": "active-photo", "loaded": True}+ if url.endswith("/model/all"):+ return [+ {"id": "texture-only/generate", "name": "Misleading Generate Label"},+ {"id": "active-photo", "name": "Active Photo Model"},+ ]+ if url.endswith("/model/params?model_id=active-photo"):+ return [{"name": "foreground_ratio"}]+ raise AssertionError(url)++ args = SimpleNamespace(base_url="http://example.test", request_timeout=1, model="auto", compact=False)+ buf = io.StringIO()+ with patch.object(agent, "_request_json", fake_request), redirect_stdout(buf):+ self.assertEqual(agent.cmd_params(args), 0)+ payload = json.loads(buf.getvalue())+ self.assertEqual(payload["model_id"], "active-photo")+ self.assertEqual(payload["params"][0]["name"], "foreground_ratio")+ self.assertEqual(calls[:3], ["http://example.test/health", "http://example.test/model/status", "http://example.test/model/all"])++ def test_explicit_model_id_must_exist_in_model_all(self) -> None:+ def fake_request(method: str, url: str, *, timeout: float, **_: object) -> object:+ if url.endswith("/model/all"):+ return [{"id": "sf3d"}]+ raise AssertionError(url)++ args = SimpleNamespace(request_timeout=1, model="missing")+ with patch.object(agent, "_request_json", fake_request):+ with self.assertRaises(agent.ModlyCliError) as ctx:+ agent._resolve_model_id(args, "http://example.test")+ self.assertEqual(ctx.exception.code, "INVALID_MODEL_ID")++ def test_export_downloads_workspace_path(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ out = Path(td) / "mesh.glb"+ args = SimpleNamespace(base_url="http://example.test", request_timeout=1, path="Agent/foo.glb", output=str(out), format="glb", compact=True)+ with patch.object(agent, "_require_health", return_value={"status": "ok"}), patch.object(agent, "_download", return_value=123) as download, redirect_stdout(io.StringIO()) as buf:+ self.assertEqual(agent.cmd_export(args), 0)+ download.assert_called_once()+ self.assertIn("/export/glb?path=Agent%2Ffoo.glb", download.call_args.args[0])+ self.assertEqual(json.loads(buf.getvalue())["bytes_written"], 123)++ def test_export_rejects_unsafe_workspace_paths(self) -> None:+ bad_paths = [+ "../secret.glb",+ "Agent/../secret.glb",+ "/Agent/foo.glb",+ "C:/Agent/foo.glb",+ "C:\\Agent\\foo.glb",+ "\\\\server\\share\\foo.glb",+ ]+ with patch.object(agent, "_download", side_effect=AssertionError("unsafe path should not be downloaded")):+ for bad_path in bad_paths:+ with self.subTest(path=bad_path):+ with self.assertRaises(agent.ModlyCliError) as ctx:+ agent._export_workspace_path("http://example.test", bad_path, "glb", Path("out.glb"), timeout=1)+ self.assertEqual(ctx.exception.code, "INVALID_WORKSPACE_PATH")++ def test_workspace_relative_path_rejects_unsafe_server_output(self) -> None:+ bad_urls = [+ "/workspace/../secret.glb",+ "/workspace/C:/secret.glb",+ "/workspace/Agent/%2E%2E/secret.glb",+ "http://example.test/workspace//absolute.glb",+ ]+ for bad_url in bad_urls:+ with self.subTest(url=bad_url):+ with self.assertRaises(agent.ModlyCliError) as ctx:+ agent._workspace_relative_path(bad_url)+ self.assertEqual(ctx.exception.code, "INVALID_WORKSPACE_PATH")++ def test_workflow_workspace_path_rejects_unsafe_scene_candidate_path(self) -> None:+ status = {"scene_candidate": {"workspace_path": "Agent/../secret.glb"}}+ with self.assertRaises(agent.ModlyCliError) as ctx:+ agent._workflow_workspace_path(status)+ self.assertEqual(ctx.exception.code, "INVALID_WORKSPACE_PATH")++ def test_generate_uses_workflow_run_and_recovery_metadata(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ image = Path(td) / "robot.png"+ output = Path(td) / "robot.glb"+ image.write_bytes(b"png")+ args = SimpleNamespace(+ base_url="http://example.test",+ request_timeout=1,+ image=str(image),+ output=str(output),+ format="glb",+ model="sf3d",+ collection="Agent",+ remesh="quad",+ enable_texture=True,+ texture_resolution=1024,+ texture_model="auto",+ texture_params_json=None,+ texture_params_file=None,+ texture_size=2048,+ texture_steps=30,+ texture_guidance=3.0,+ params_json=None,+ params_file=None,+ timeout=10,+ poll=0,+ progress=False,+ quiet=True,+ no_export=False,+ )+ bodies: list[bytes] = []++ def fake_request(method: str, url: str, *, timeout: float, data: bytes | None = None, **_: object) -> object:+ if url.endswith("/health"):+ return {"status": "ok"}+ if url.endswith("/model/status"):+ return {"id": "sf3d", "loaded": True}+ if url.endswith("/model/all"):+ return [{"id": "sf3d"}]+ if url.endswith("/workflow-runs/from-image"):+ self.assertEqual(method, "POST")+ assert data is not None+ bodies.append(data)+ return {"run_id": "run-1", "status": "pending"}+ if url.endswith("/workflow-runs/run-1"):+ return {"run_id": "run-1", "status": "done", "progress": 100, "output_url": "/workspace/Default/robot.glb"}+ raise AssertionError(url)++ with patch.object(agent, "_request_json", fake_request), patch.object(agent, "_export_workspace_path", return_value=456):+ result = agent._generate_one(args, image, output)+ self.assertEqual(result["run"], {"kind": "workflowRun", "id": "run-1"})+ self.assertFalse(result["meta"]["legacy"])+ self.assertIn("workflow-run status run-1", result["meta"]["status_command"])+ self.assertEqual(result["workspace_path"], "Default/robot.glb")+ self.assertIn(b'name="model_id"\r\n\r\nsf3d', bodies[0])+ self.assertIn(b'"enable_texture":true', bodies[0])++ def test_workflow_run_status_and_cancel_use_canonical_endpoints(self) -> None:+ calls: list[tuple[str, str]] = []++ def fake_request(method: str, url: str, *, timeout: float, **_: object) -> object:+ calls.append((method, url))+ if url.endswith("/health"):+ return {"status": "ok"}+ if url.endswith("/workflow-runs/run-1"):+ return {"run_id": "run-1", "status": "running"}+ if url.endswith("/workflow-runs/run-1/cancel"):+ return {"cancelled": True}+ raise AssertionError(url)++ status_args = SimpleNamespace(base_url="http://example.test", request_timeout=1, run_id="run-1", compact=True)+ cancel_args = SimpleNamespace(base_url="http://example.test", request_timeout=1, run_id="run-1", compact=True)+ with patch.object(agent, "_request_json", fake_request), redirect_stdout(io.StringIO()) as buf:+ self.assertEqual(agent.cmd_workflow_run_status(status_args), 0)+ self.assertEqual(agent.cmd_workflow_run_cancel(cancel_args), 0)+ outputs = [json.loads(line) for line in buf.getvalue().splitlines()]+ self.assertEqual(outputs[0]["run"], {"kind": "workflowRun", "id": "run-1"})+ self.assertEqual(outputs[1]["cancel"]["cancelled"], True)+ self.assertIn(("GET", "http://example.test/workflow-runs/run-1"), calls)+ self.assertIn(("POST", "http://example.test/workflow-runs/run-1/cancel"), calls)++ def test_capability_and_process_fail_closed_when_contract_is_absent(self) -> None:+ def fake_request(method: str, url: str, *, timeout: float, **_: object) -> object:+ if url.endswith("/health"):+ return {"status": "ok"}+ raise agent.ModlyCliError("missing", code="HTTP_404", http_status=404)++ cap_args = SimpleNamespace(base_url="http://example.test", request_timeout=1, compact=True)+ proc_args = SimpleNamespace(base_url="http://example.test", request_timeout=1, run_id="run-1", compact=True)+ with patch.object(agent, "_request_json", fake_request):+ with self.assertRaises(agent.ModlyCliError) as cap_ctx:+ agent.cmd_capability_list(cap_args)+ with self.assertRaises(agent.ModlyCliError) as proc_ctx:+ agent.cmd_process_run_status(proc_args)+ self.assertEqual(cap_ctx.exception.code, "UNSUPPORTED_PROCESS")+ self.assertEqual(proc_ctx.exception.code, "UNSUPPORTED_PROCESS")++ def test_process_run_start_uses_recovery_meta_with_custom_base_url(self) -> None:+ def fake_request(method: str, url: str, *, timeout: float, **_: object) -> object:+ if url.endswith("/health"):+ return {"status": "ok"}+ if url.endswith("/process-runs"):+ return {"run_id": "proc-1", "status": "queued"}+ raise AssertionError(url)++ args = SimpleNamespace(+ base_url="http://custom.test",+ request_timeout=1,+ input_json="{}",+ input_file=None,+ process="texture",+ compact=True,+ )+ with patch.object(agent, "_request_json", fake_request), redirect_stdout(io.StringIO()) as buf:+ self.assertEqual(agent.cmd_process_run_start(args), 0)+ payload = json.loads(buf.getvalue())+ self.assertIn("--base-url http://custom.test", payload["meta"]["status_command"])+ self.assertIn("--base-url http://custom.test", payload["meta"]["cancel_command"])++ def test_main_converts_unexpected_exceptions_to_json(self) -> None:+ def boom(_args: object) -> int:+ raise RuntimeError("boom")++ with patch.object(agent, "cmd_health", boom), redirect_stdout(io.StringIO()) as buf:+ self.assertEqual(agent.main(["health"]), 1)+ payload = json.loads(buf.getvalue())+ self.assertEqual(payload["code"], "UNEXPECTED_ERROR")+ self.assertEqual(payload["message"], "boom")++ def test_main_converts_argparse_errors_to_json(self) -> None:+ with redirect_stdout(io.StringIO()) as buf:+ self.assertEqual(agent.main(["health", "--bogus"]), 1)+ payload = json.loads(buf.getvalue())+ self.assertEqual(payload["code"], "INVALID_ARGUMENTS")+ self.assertIn("--bogus", payload["message"])++ def test_generate_from_workflow_downloads_direct_asset_without_modly_health(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ output = Path(td) / "robot.glb"+ history = {+ "outputs": {+ "9": {+ "meshes": [+ {"filename": "robot.glb", "subfolder": "trellis", "type": "output"},+ ]+ }+ }+ }+ args = SimpleNamespace(+ base_url="http://modly.test",+ request_timeout=1,+ compact=True,+ output=str(output),+ workflow="Trellis2-Full",+ )++ with (+ patch.object(agent, "_run_comfy_workflow", return_value={"ok": True, "comfy_url": "http://comfy.test", "workflow": "Trellis2-Full", "prompt_id": "prompt-1", "history": history}),+ patch.object(agent, "_download", return_value=789) as download,+ patch.object(agent, "_require_health", side_effect=AssertionError("Modly health should not run for direct asset output")),+ patch.object(agent, "_generate_one", side_effect=AssertionError("Modly generation should not run for direct asset output")),+ redirect_stdout(io.StringIO()) as buf,+ ):+ self.assertEqual(agent.cmd_generate_from_workflow(args), 0)++ payload = json.loads(buf.getvalue())+ self.assertEqual(payload["source"], "comfy-workflow")+ self.assertEqual(payload["output_type"], "asset")+ self.assertEqual(payload["export_path"], str(output.resolve()))+ self.assertEqual(payload["bytes_written"], 789)+ self.assertEqual(payload["workflow"], "Trellis2-Full")+ self.assertEqual(payload["prompt_id"], "prompt-1")+ self.assertTrue(payload["meta"]["experimental"])+ download.assert_called_once()+ self.assertIn("/view?", download.call_args.args[0])+ self.assertIn("filename=robot.glb", download.call_args.args[0])++ def test_generate_from_workflow_falls_back_to_modly_for_image_only_outputs(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ output = Path(td) / "robot.glb"+ history = {+ "outputs": {+ "3": {+ "images": [+ {"filename": "source.png", "subfolder": "", "type": "output"},+ ]+ }+ }+ }+ args = SimpleNamespace(+ base_url="http://modly.test",+ request_timeout=1,+ compact=True,+ output=str(output),+ workflow="Trellis2-Full",+ )++ def fake_generate(_args: object, image_path: Path, output_path: Path | None) -> dict[str, object]:+ self.assertTrue(str(image_path).endswith(".png"))+ self.assertEqual(output_path, output.resolve())+ return {"ok": True, "run": {"kind": "workflowRun", "id": "run-1"}, "meta": {"legacy": False}}++ with (+ patch.object(agent, "_run_comfy_workflow", return_value={"ok": True, "comfy_url": "http://comfy.test", "workflow": "Trellis2-Full", "prompt_id": "prompt-1", "history": history}),+ patch.object(agent, "_download", return_value=123),+ patch.object(agent, "_require_health", return_value={"status": "ok"}) as health,+ patch.object(agent, "_generate_one", fake_generate),+ redirect_stdout(io.StringIO()) as buf,+ ):+ self.assertEqual(agent.cmd_generate_from_workflow(args), 0)++ payload = json.loads(buf.getvalue())+ self.assertEqual(payload["source"], "comfy-workflow")+ self.assertEqual(payload["output_type"], "image")+ self.assertEqual(payload["comfy"]["prompt_id"], "prompt-1")+ self.assertTrue(payload["meta"]["experimental"])+ health.assert_called_once_with("http://modly.test", 1)++ def test_generate_from_workflow_fails_when_history_has_no_supported_output(self) -> None:+ args = SimpleNamespace(base_url="http://modly.test", request_timeout=1, compact=True, output="robot.glb", workflow="Trellis2-Full")+ history = {"outputs": {"4": {"text": ["done"]}}}+ with patch.object(agent, "_run_comfy_workflow", return_value={"ok": True, "comfy_url": "http://comfy.test", "workflow": "Trellis2-Full", "prompt_id": "prompt-1", "history": history}):+ with self.assertRaises(agent.ModlyCliError) as ctx:+ agent.cmd_generate_from_workflow(args)+ self.assertEqual(ctx.exception.code, "NO_WORKFLOW_OUTPUT")++ def test_batch_processes_images_sequentially(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ inputs = root / "inputs"+ outputs = root / "outputs"+ inputs.mkdir()+ (inputs / "b.jpg").write_bytes(b"jpg")+ (inputs / "a.png").write_bytes(b"png")+ (inputs / "ignore.txt").write_text("no")+ args = SimpleNamespace(input_dir=str(inputs), manifest=None, output_dir=str(outputs), format="glb", compact=False, continue_on_error=False)++ def fake_generate(_args: object, image: Path, output: Path | None = None) -> dict[str, object]:+ return {"ok": True, "image": str(image), "export_path": str(output)}++ with patch.object(agent, "_generate_one", fake_generate), redirect_stdout(io.StringIO()) as buf:+ self.assertEqual(agent.cmd_batch(args), 0)+ payload = json.loads(buf.getvalue())+ self.assertEqual(payload["count"], 2)+ self.assertEqual([Path(r["image"]).name for r in payload["results"]], ["a.png", "b.jpg"])++ def test_batch_accepts_manifest_json(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ image = root / "robot.png"+ output = root / "robot.stl"+ manifest = root / "jobs.json"+ image.write_bytes(b"png")+ manifest.write_text(json.dumps({"jobs": [{"image": "robot.png", "output": "robot.stl", "format": "stl"}]}), encoding="utf-8")+ args = SimpleNamespace(input_dir=None, manifest=str(manifest), output_dir=None, format="glb", compact=True, continue_on_error=False)++ def fake_generate(_args: object, image_path: Path, output_path: Path | None = None) -> dict[str, object]:+ self.assertEqual(_args.format, "stl")+ return {"ok": True, "image": str(image_path), "export_path": str(output_path)}++ with patch.object(agent, "_generate_one", fake_generate), redirect_stdout(io.StringIO()) as buf:+ self.assertEqual(agent.cmd_batch(args), 0)+ payload = json.loads(buf.getvalue())+ self.assertEqual(payload["results"][0]["image"], str(image))+ self.assertEqual(payload["results"][0]["export_path"], str(output))+++class ComfyWorkflowTests(unittest.TestCase):+ def test_patch_positive_cliptextencode(self) -> None:+ workflow = {+ "1": {"class_type": "CLIPTextEncode", "inputs": {"text": "old prompt", "clip": ["4", 1]}},+ "2": {"class_type": "CLIPTextEncode", "inputs": {"text": "negative", "clip": ["4", 1]}},+ }+ result = agent._patch_comfy_workflow(workflow, prompt="new prompt", seed=42)+ self.assertEqual(result["1"]["inputs"]["text"], "new prompt")+ self.assertEqual(result["2"]["inputs"]["text"], "negative")++ def test_patch_raises_when_no_text_input(self) -> None:+ workflow = {+ "1": {"class_type": "LoadImage", "inputs": {"image": "photo.png"}},+ }+ with self.assertRaises(agent.ModlyCliError):+ agent._patch_comfy_workflow(workflow, prompt="good", seed=None)++ def test_patch_fallback_to_prompt_key(self) -> None:+ workflow = {+ "1": {"class_type": "KSampler", "inputs": {"prompt": "old", "seed": 0}},+ }+ result = agent._patch_comfy_workflow(workflow, prompt="new", seed=99)+ self.assertEqual(result["1"]["inputs"]["prompt"], "new")+ self.assertEqual(result["1"]["inputs"]["seed"], 99)++ def test_patch_seed_noise_seed(self) -> None:+ workflow = {+ "1": {"class_type": "KSampler", "inputs": {"noise_seed": 0, "prompt": "test"}},+ }+ result = agent._patch_comfy_workflow(workflow, prompt=None, seed=7)+ self.assertEqual(result["1"]["inputs"]["noise_seed"], 7)++ def test_rejects_editor_format(self) -> None:+ workflow = {"nodes": [], "links": []}+ with self.assertRaises(agent.ModlyCliError):+ agent._patch_comfy_workflow(workflow, prompt="x", seed=None)++ def test_prompt_wrapper(self) -> None:+ workflow = {"prompt": {"1": {"class_type": "CLIPTextEncode", "inputs": {"text": "old"}}}}+ result = agent._patch_comfy_workflow(workflow, prompt="new", seed=None)+ self.assertEqual(result["1"]["inputs"]["text"], "new")++ def test_deep_copy_no_mutation(self) -> None:+ original = {"1": {"class_type": "CLIPTextEncode", "inputs": {"text": "old"}}}+ agent._patch_comfy_workflow(original, prompt="new", seed=None)+ self.assertEqual(original["1"]["inputs"]["text"], "old")+++class ServeConfigTests(unittest.TestCase):+ def test_default_api_dir_checks_all_windows_localappdata_candidates(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ repo = root / "repo"+ repo.mkdir()+ bad_local = root / "Default" / "AppData" / "Local"+ good_api = root / "joshu" / "AppData" / "Local" / "Programs" / "Modly" / "resources" / "api"+ good_api.mkdir(parents=True)+ (good_api / "main.py").write_text("# api", encoding="utf-8")++ with patch.object(agent, "_repo_root", return_value=repo), patch.object(agent, "_windows_env_paths", return_value=[bad_local, good_api.parents[3]]):+ self.assertEqual(agent._default_api_dir(), good_api)++ def test_load_modly_settings_checks_all_windows_appdata_candidates(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ bad_roaming = root / "Default" / "AppData" / "Roaming"+ good_roaming = root / "joshu" / "AppData" / "Roaming"+ settings = good_roaming / "Modly" / "settings.json"+ settings.parent.mkdir(parents=True)+ settings.write_text(json.dumps({"workspaceDir": "C:/workspace"}), encoding="utf-8")++ with patch.object(agent, "_windows_env_paths", return_value=[bad_roaming, good_roaming]):+ self.assertEqual(agent._load_modly_settings()["workspaceDir"], "C:/workspace")++ def test_malformed_timeout_environment_does_not_break_module_import(self) -> None:+ spec = importlib.util.spec_from_file_location("modly_agent_bad_env", MODULE_PATH)+ module = importlib.util.module_from_spec(spec)+ assert spec and spec.loader+ with patch.dict(os.environ, {"MODLY_CLI_TIMEOUT": "not-int", "MODLY_CLI_POLL_SECONDS": "not-float"}):+ spec.loader.exec_module(module)+ self.assertEqual(module.DEFAULT_TIMEOUT_SECONDS, 1800)+ self.assertEqual(module.DEFAULT_POLL_SECONDS, 2.0)++ def test_resolve_serve_config_explicit_paths(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ api_dir = Path(td) / "api"+ api_dir.mkdir()+ (api_dir / "main.py").write_text("# api")+ python = Path(td) / "python.exe"+ python.write_text("# python")+ args = SimpleNamespace(+ api_dir=str(api_dir),+ python=str(python),+ host="0.0.0.0",+ port=9999,+ models_dir=None,+ workspace_dir=None,+ extensions_dir=None,+ model=None,+ hf_token=None,+ )+ _api_dir, _python, env, cmd, base_url = agent._resolve_serve_config(args)+ self.assertEqual(str(_api_dir), str(api_dir.resolve()))+ self.assertEqual(base_url, "http://0.0.0.0:9999")+ self.assertTrue(cmd[0].endswith("python.exe"))+ self.assertIn("PYTHONUNBUFFERED", env)+++class ParserTests(unittest.TestCase):+ def test_canonical_dev_experimental_and_legacy_subcommands_parse(self) -> None:+ parser = agent.build_parser()+ cases = [+ ["status"],+ ["model", "list"],+ ["model", "params"],+ ["workflow-run", "status", "abc"],+ ["workflow-run", "cancel", "abc"],+ ["capability", "list"],+ ["process-run", "status", "abc"],+ ["experimental", "comfy-image"],+ ["experimental", "generate-from-workflow", "--workflow", "Trellis2-Full", "--prompt", "asset", "--output", "asset.glb"],+ ["export", "--path", "Agent/foo.glb", "--output", "foo.glb"],+ ["batch", "--input-dir", "imgs", "--output-dir", "meshes"],+ ["dev", "serve-api", "--print-command"],+ ["dev", "ensure-server"],+ ["legacy", "job", "abc"],+ ["legacy", "cancel", "abc"],+ ]+ for argv in cases:+ with self.subTest(argv=argv):+ args = parser.parse_args(argv)+ self.assertTrue(callable(args.func))++ def test_hidden_aliases_are_not_documented_as_canonical(self) -> None:+ parser = agent.build_parser()+ help_text = parser.format_help()+ self.assertNotIn("comfy-image", help_text)+ self.assertNotIn("ensure-server", help_text)+ self.assertNotIn("job", help_text)+ self.assertNotIn("\n status", help_text)+ self.assertNotIn("\n export", help_text)+ self.assertNotIn("\n batch", help_text)+++if __name__ == "__main__":+ unittest.main()diff --git a/apps/forge-desktop/tsconfig.builtins.json b/apps/forge-desktop/tsconfig.builtins.jsonnew file mode 100644index 000000000..15c7e29d4--- /dev/null+++ b/apps/forge-desktop/tsconfig.builtins.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "CommonJS",+ "moduleResolution": "node",+ "strict": true,+ "skipLibCheck": true,+ "outDir": "out/builtin-extensions",+ "rootDir": "src/areas/workflows/nodes",+ "declaration": false,+ "sourceMap": false,+ "esModuleInterop": true+ },+ "include": [+ "src/areas/workflows/nodes/mesh-exporter/**/*.ts"+ ]+}diff --git a/apps/forge-desktop/tsconfig.json b/apps/forge-desktop/tsconfig.jsonnew file mode 100644index 000000000..155ebaa67--- /dev/null+++ b/apps/forge-desktop/tsconfig.json@@ -0,0 +1,7 @@+{+ "files": [],+ "references": [+ { "path": "./tsconfig.node.json" },+ { "path": "./tsconfig.web.json" }+ ]+}diff --git a/apps/forge-desktop/tsconfig.node.json b/apps/forge-desktop/tsconfig.node.jsonnew file mode 100644index 000000000..d90232c6b--- /dev/null+++ b/apps/forge-desktop/tsconfig.node.json@@ -0,0 +1,16 @@+{+ "compilerOptions": {+ "composite": true,+ "module": "ESNext",+ "moduleResolution": "bundler",+ "target": "ES2022",+ "lib": ["ES2022"],+ "strict": true,+ "skipLibCheck": true,+ "types": ["electron-vite/node"],+ "paths": {+ "@main/*": ["./electron/main/*"]+ }+ },+ "include": ["electron.vite.config.*", "electron/**/*"]+}diff --git a/apps/forge-desktop/tsconfig.web.json b/apps/forge-desktop/tsconfig.web.jsonnew file mode 100644index 000000000..2b2dbc6e6--- /dev/null+++ b/apps/forge-desktop/tsconfig.web.json@@ -0,0 +1,23 @@+{+ "compilerOptions": {+ "composite": true,+ "module": "ESNext",+ "moduleResolution": "bundler",+ "target": "ES2022",+ "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "jsx": "react-jsx",+ "strict": true,+ "skipLibCheck": true,+ "paths": {+ "@/*": ["./src/*"],+ "@areas/*": ["./src/areas/*"],+ "@shared/*": ["./src/shared/*"],+ "@styles/*": ["./src/styles/*"]+ }+ },+ "include": ["src/**/*"],+ "exclude": [+ "src/areas/workflows/nodes/mesh-exporter",+ "src/areas/workflows/nodes/mesh-optimizer"+ ]+}