Skip to content

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.

feat(modly): connect the open-source Modly app to three.ws with account sign-in, publish and library, a /modly page, a Modly extension and a GPU worker

nirholas26489e5b93e2
diff --git a/apps/desktop/scripts/release-manifest.mjs b/apps/desktop/scripts/release-manifest.mjs
index d829cf398..a261687e6 100644
--- a/apps/desktop/scripts/release-manifest.mjs
+++ b/apps/desktop/scripts/release-manifest.mjs
@@ -35,8 +35,8 @@ export const MINIMUM_OS = {
// Filename patterns electron-builder.config.cjs produces, most specific first.
const KINDS = [
- { re: /-mac-universal\.dmg$/, platform: 'mac', arch: 'universal', kind: 'dmg', label: 'Disk image (.dmg)', primary: true },
- { re: /-mac-universal\.zip$/, platform: 'mac', arch: 'universal', kind: 'zip', label: 'Zip archive (.zip)' },
+ { re: /-mac-(universal|arm64|x64)\.dmg$/, platform: 'mac', kind: 'dmg', label: 'Disk image (.dmg)', primary: true },
+ { re: /-mac-(universal|arm64|x64)\.zip$/, platform: 'mac', kind: 'zip', label: 'Zip archive (.zip)' },
{ re: /-win-(x64|arm64)-setup\.exe$/, platform: 'win', kind: 'nsis', label: 'Installer (.exe)', primary: true },
{ re: /-win-(x64|arm64)-portable\.exe$/, platform: 'win', kind: 'portable', label: 'Portable (.exe, no install)' },
{ re: /-linux-(x86_64|x64|arm64|aarch64)\.AppImage$/, platform: 'linux', kind: 'appimage', label: 'AppImage', primary: true },
@@ -85,19 +85,21 @@ export async function describeArtifacts(dist, { baseUrl = DEFAULT_BASE_URL, sign
}
// Keep the other platforms' files from the published manifest when it is the
-// same version; this run's platforms always replace what was there.
-export function mergeManifest({ version, date, notes, files }, previous) {
+// same version; this run's platforms always replace what was there. Other
+// apps that publish through the same bucket (three.ws Forge) pass their own
+// product name and OS floors.
+export function mergeManifest({ version, date, notes, files }, previous, { product = 'three.ws Desktop', minimumOS = MINIMUM_OS } = {}) {
const built = new Set(files.map((f) => f.platform));
const carried = previous && previous.version === version ? (previous.files || []).filter((f) => !built.has(f.platform)) : [];
const order = { mac: 0, win: 1, linux: 2 };
const all = [...files, ...carried].sort((a, b) => order[a.platform] - order[b.platform] || Number(b.primary) - Number(a.primary) || a.name.localeCompare(b.name));
return {
schema: 1,
- product: 'three.ws Desktop',
+ product,
version,
date: previous && previous.version === version && previous.date ? previous.date : date,
notes,
- minimumOS: MINIMUM_OS,
+ minimumOS,
platforms: [...new Set(all.map((f) => f.platform))],
files: all,
};
diff --git a/apps/forge-desktop/.gcloudignore b/apps/forge-desktop/.gcloudignore
new file mode 100644
index 000000000..9d9ddcbc6
--- /dev/null
+++ b/apps/forge-desktop/.gcloudignore
@@ -0,0 +1,22 @@
+# Upload context for apps/forge-desktop/cloudbuild.yaml, submitted from the
+# repo root with --ignore-file apps/forge-desktop/.gcloudignore. The Forge build
+# needs the app, the three.ws cloud extensions it bundles as built-ins
+# (integrations/modly), and the release manifest it shares with three.ws
+# Desktop; everything else in the monorepo stays on this machine.
+/*
+!/apps/
+/apps/*
+!/apps/forge-desktop/
+/apps/forge-desktop/node_modules/
+/apps/forge-desktop/out/
+/apps/forge-desktop/dist/
+/apps/forge-desktop/resources/python-embed/
+/apps/forge-desktop/api/.venv/
+/apps/forge-desktop/api/venv/
+**/__pycache__/
+!/apps/desktop/
+/apps/desktop/*
+!/apps/desktop/scripts/
+!/integrations/
+/integrations/*
+!/integrations/modly/
diff --git a/apps/forge-desktop/NOTICE b/apps/forge-desktop/NOTICE
new file mode 100644
index 000000000..61f5cc753
--- /dev/null
+++ b/apps/forge-desktop/NOTICE
@@ -0,0 +1,21 @@
+three.ws Forge
+Copyright three.ws
+
+Based on Modly (https://github.com/lightningpixel/modly)
+by Lightning Pixel (https://github.com/lightningpixel)
+
+three.ws Forge is a fork of Modly, a desktop application for local image-to-3D
+generation. Modly is released under the MIT License; its full text, including
+the attribution request quoted above, is in the LICENSE file in this
+directory and applies to the code that originates from Modly. The three.ws
+changes (the rebrand, the three.ws account and publishing integration, the
+three.ws Forge cloud generators bundled from integrations/modly, the CC0
+library browser, and the release pipeline) are released under the same MIT
+License.
+
+Model extensions that Forge installs from GitHub (for example the Hunyuan3D,
+TRELLIS and TripoSG extensions published by Lightning Pixel) download model
+weights from their original publishers. Those weights carry their own
+licenses, which Forge shows on each model's card before download. Tencent's
+Hunyuan3D weights in particular are licensed for use outside the European
+Union, the United Kingdom and South Korea only.
diff --git a/apps/forge-desktop/api/routers/settings.py b/apps/forge-desktop/api/routers/settings.py
index 9106ad2d6..059c5cb81 100644
--- a/apps/forge-desktop/api/routers/settings.py
+++ b/apps/forge-desktop/api/routers/settings.py
@@ -54,3 +54,24 @@ async def update_hf_token(body: TokenUpdate):
os.environ.pop("HUGGING_FACE_HUB_TOKEN", None)
os.environ.pop("HF_TOKEN", None)
return {"ok": True}
+
+
+class ThreeWsAccountUpdate(BaseModel):
+ api_key: str
+ base_url: Optional[str] = None
+
+
[email protected]("/three-ws")
+async def update_three_ws_account(body: ThreeWsAccountUpdate):
+ """
+ Point the bundled three.ws extensions at the account signed in through
+ Settings → three.ws. The cloud generator runs inside this process and the
+ publish node in a subprocess spawned after this call; both read the env.
+ """
+ if body.api_key:
+ os.environ["THREE_WS_API_KEY"] = body.api_key
+ else:
+ os.environ.pop("THREE_WS_API_KEY", None)
+ if body.base_url:
+ os.environ["THREE_WS_BASE_URL"] = body.base_url
+ return {"ok": True}
diff --git a/apps/forge-desktop/api/services/generator_registry.py b/apps/forge-desktop/api/services/generator_registry.py
index 734c3ffd4..ec5625e99 100644
--- a/apps/forge-desktop/api/services/generator_registry.py
+++ b/apps/forge-desktop/api/services/generator_registry.py
@@ -53,6 +53,10 @@ 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
+# Model extensions that ship inside the app (synced to userData/builtin-extensions
+# by Electron on every start). A user-installed extension with the same id wins.
+_builtin_extensions_dir_raw = os.environ.get("BUILTIN_EXTENSIONS_DIR", "")
+BUILTIN_EXTENSIONS_DIR = Path(_builtin_extensions_dir_raw) if _builtin_extensions_dir_raw else None
_REGISTRATION_PENDING_PREFIX = ".forge-registration-pending-"
_EXTENSION_ID = re.compile(r"^[a-z0-9][a-z0-9._-]*$")
_REGISTRATION_PENDING_NAME = re.compile(
@@ -64,6 +68,21 @@ _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)'}")
+print(f"[Registry] BUILTIN_EXTENSIONS_DIR = {BUILTIN_EXTENSIONS_DIR or '(not set)'}")
+
+
+def _extension_dirs() -> List[Tuple[Path, bool]]:
+ """Every candidate extension folder as (path, is_builtin).
+
+ Built-ins come first so a user-installed extension with the same id,
+ discovered later, replaces the bundled one.
+ """
+ found: List[Tuple[Path, bool]] = []
+ for root, builtin in ((BUILTIN_EXTENSIONS_DIR, True), (EXTENSIONS_DIR, False)):
+ if root is None or not root.exists():
+ continue
+ found.extend((child, builtin) for child in sorted(root.iterdir()))
+ return found
def is_within_workspace(resolved_path: Path) -> bool:
@@ -400,7 +419,7 @@ def _discover_extensions(
Dict[str, str],
]:
"""
- Scans EXTENSIONS_DIR to find valid extensions.
+ Scans BUILTIN_EXTENSIONS_DIR, then 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".
@@ -410,9 +429,8 @@ def _discover_extensions(
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()):
+ for ext_dir, builtin in _extension_dirs():
if not ext_dir.is_dir():
continue
# Dot-dirs are install machinery (staging/backup), never extensions
@@ -529,7 +547,8 @@ def _discover_extensions(
(ext_dir / ".forge-incomplete").exists()
or (ext_dir / ".forge-registration-pending").exists()
or (
- _registration_pending(ext_id)
+ not builtin
+ and _registration_pending(ext_id)
and not (
registration_authorization is not None
and registration_authorization[0] == ext_id
diff --git a/apps/forge-desktop/api/tests/test_generator_registry.py b/apps/forge-desktop/api/tests/test_generator_registry.py
index 1d4bc7a94..54b4637c2 100644
--- a/apps/forge-desktop/api/tests/test_generator_registry.py
+++ b/apps/forge-desktop/api/tests/test_generator_registry.py
@@ -156,6 +156,47 @@ class GeneratorRegistryDiscoveryTests(unittest.TestCase):
self.registry.reload()
self.assertNotIn(str(extension.resolve()), sys.path)
+ def _write_named_generator(self, directory: Path, extension_id: str, name: str) -> None:
+ directory.mkdir(parents=True)
+ manifest = {
+ "id": extension_id, "name": name, "type": "model",
+ "generator_class": "TestGenerator",
+ "nodes": [{"id": "generate", "name": name}],
+ }
+ (directory / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")
+ (directory / "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",
+ )
+
+ def test_builtin_extensions_load_without_a_user_install(self) -> None:
+ builtin_dir = self.root / "builtin-extensions"
+ self._write_named_generator(builtin_dir / "three-ws", "three-ws", "Bundled")
+ old_builtin = registry_module.BUILTIN_EXTENSIONS_DIR
+ registry_module.BUILTIN_EXTENSIONS_DIR = builtin_dir
+ try:
+ self.registry.initialize()
+ self.assertEqual(self.registry.get_manifest("three-ws/generate")["name"], "Bundled")
+ finally:
+ registry_module.BUILTIN_EXTENSIONS_DIR = old_builtin
+ sys.modules.pop("extensions.three-ws.generator", None)
+
+ def test_user_installed_extension_overrides_the_builtin_with_the_same_id(self) -> None:
+ builtin_dir = self.root / "builtin-extensions"
+ self._write_named_generator(builtin_dir / "three-ws", "three-ws", "Bundled")
+ self._write_named_generator(self.extensions_dir / "three-ws", "three-ws", "Installed")
+ old_builtin = registry_module.BUILTIN_EXTENSIONS_DIR
+ registry_module.BUILTIN_EXTENSIONS_DIR = builtin_dir
+ try:
+ self.registry.initialize()
+ self.assertEqual(self.registry.get_manifest("three-ws/generate")["name"], "Installed")
+ finally:
+ registry_module.BUILTIN_EXTENSIONS_DIR = old_builtin
+ sys.modules.pop("extensions.three-ws.generator", None)
+
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)
diff --git a/apps/forge-desktop/api/tests/test_settings_three_ws.py b/apps/forge-desktop/api/tests/test_settings_three_ws.py
new file mode 100644
index 000000000..81a2b9e80
--- /dev/null
+++ b/apps/forge-desktop/api/tests/test_settings_three_ws.py
@@ -0,0 +1,39 @@
+import asyncio
+import os
+import unittest
+from unittest import mock
+
+from routers.settings import ThreeWsAccountUpdate, update_three_ws_account
+
+
+class ThreeWsAccountSettingsTests(unittest.TestCase):
+ """POST /settings/three-ws keeps the bundled three.ws extensions on the signed-in account."""
+
+ def setUp(self) -> None:
+ patcher = mock.patch.dict(os.environ, {}, clear=False)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ os.environ.pop("THREE_WS_API_KEY", None)
+ os.environ.pop("THREE_WS_BASE_URL", None)
+
+ def _post(self, **body) -> dict:
+ return asyncio.run(update_three_ws_account(ThreeWsAccountUpdate(**body)))
+
+ def test_sign_in_sets_the_key_and_origin(self) -> None:
+ self.assertEqual(self._post(api_key="sk_live_example", base_url="https://three.ws"), {"ok": True})
+ self.assertEqual(os.environ["THREE_WS_API_KEY"], "sk_live_example")
+ self.assertEqual(os.environ["THREE_WS_BASE_URL"], "https://three.ws")
+
+ def test_sign_out_removes_the_key(self) -> None:
+ os.environ["THREE_WS_API_KEY"] = "sk_live_example"
+ self._post(api_key="")
+ self.assertNotIn("THREE_WS_API_KEY", os.environ)
+
+ def test_missing_origin_leaves_the_current_one(self) -> None:
+ os.environ["THREE_WS_BASE_URL"] = "https://staging.three.ws"
+ self._post(api_key="sk_live_example")
+ self.assertEqual(os.environ["THREE_WS_BASE_URL"], "https://staging.three.ws")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/apps/forge-desktop/cloudbuild.yaml b/apps/forge-desktop/cloudbuild.yaml
new file mode 100644
index 000000000..2a2d55696
--- /dev/null
+++ b/apps/forge-desktop/cloudbuild.yaml
@@ -0,0 +1,133 @@
+# three.ws Forge release build: Linux (.AppImage, .deb) and Windows (NSIS
+# installer) on Cloud Build, published to the release bucket that the three.ws
+# load balancer serves at https://three.ws/releases/forge/. macOS builds on a
+# Mac (apps/forge-desktop/scripts/release-mac.sh) and merges into the same
+# release.json. Runbook: docs/ops/forge-desktop-release.md.
+#
+# Submit from the repo root. Publishing is owner-gated: the default
+# (_PUBLISH=0) builds, writes release.json and stages everything under
+# staging/forge/<version>/<build id>/ without touching the live feed.
+#
+# gcloud builds submit --config apps/forge-desktop/cloudbuild.yaml \
+# --ignore-file apps/forge-desktop/.gcloudignore \
+# --region us-central1 --project aerial-vehicle-466722-p5 \
+# --substitutions _PUBLISH=1
+#
+# Windows signing reuses three.ws Desktop's secrets (desktop-windows-csc-link,
+# desktop-windows-csc-password): both apps ship under the three.ws publisher.
+
+steps:
+ - id: prepare
+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
+ entrypoint: bash
+ args:
+ - -c
+ - |
+ set -euo pipefail
+ mkdir -p /workspace/.release
+ if gcloud secrets versions access latest --secret=desktop-windows-csc-link --project=$PROJECT_ID > /workspace/.release/win.pfx.b64 2>/dev/null \
+ && gcloud secrets versions access latest --secret=desktop-windows-csc-password --project=$PROJECT_ID > /workspace/.release/win.pass 2>/dev/null; then
+ echo 1 > /workspace/.release/win.signed
+ echo "Windows certificate found: the installer will be signed."
+ else
+ rm -f /workspace/.release/win.pfx.b64 /workspace/.release/win.pass
+ echo 0 > /workspace/.release/win.signed
+ echo "No Windows certificate in Secret Manager: building unsigned."
+ fi
+ if ! gcloud storage cp gs://${_BUCKET}/releases/forge/release.json /workspace/.release/published.json 2>/dev/null; then
+ echo '{}' > /workspace/.release/published.json
+ echo "No published release.json yet: this is the first Forge release."
+ fi
+
+ - id: install
+ name: electronuserland/builder:20-wine
+ dir: apps/forge-desktop
+ entrypoint: bash
+ args: ['-c', 'npm ci --no-audit --no-fund && node node_modules/electron/install.js']
+
+ - id: build
+ name: electronuserland/builder:20-wine
+ dir: apps/forge-desktop
+ entrypoint: bash
+ args: ['-c', 'npm run build']
+
+ - id: linux
+ name: electronuserland/builder:20-wine
+ dir: apps/forge-desktop
+ entrypoint: bash
+ args:
+ - -c
+ - |
+ set -euo pipefail
+ node scripts/download-python-embed.js --platform linux --arch x64
+ npx electron-builder --config electron-builder.config.cjs --linux --publish never
+
+ - id: windows
+ name: electronuserland/builder:20-wine
+ dir: apps/forge-desktop
+ entrypoint: bash
+ args:
+ - -c
+ - |
+ set -euo pipefail
+ node scripts/download-python-embed.js --platform win32 --arch x64
+ if [ "$$(cat /workspace/.release/win.signed)" = "1" ]; then
+ export CSC_LINK="$$(cat /workspace/.release/win.pfx.b64)"
+ export CSC_KEY_PASSWORD="$$(cat /workspace/.release/win.pass)"
+ else
+ export CSC_IDENTITY_AUTO_DISCOVERY=false
+ fi
+ npx electron-builder --config electron-builder.config.cjs --win --publish never
+
+ - id: manifest
+ name: electronuserland/builder:20-wine
+ dir: apps/forge-desktop
+ entrypoint: bash
+ args:
+ - -c
+ - |
+ set -euo pipefail
+ rm -f /workspace/.release/win.pfx.b64 /workspace/.release/win.pass
+ THREE_WS_SIGNED_WIN="$$(cat /workspace/.release/win.signed)" \
+ node scripts/release-manifest.mjs --merge /workspace/.release/published.json
+ node -e "process.stdout.write(require('./package.json').version)" > /workspace/.release/version
+
+ - id: publish
+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
+ dir: apps/forge-desktop/dist
+ entrypoint: bash
+ args:
+ - -c
+ - |
+ set -euo pipefail
+ shopt -s nullglob
+ VERSION="$$(cat /workspace/.release/version)"
+ BINARIES=(*.AppImage *.deb *.exe *.blockmap)
+ FEED_FILES=(latest*.yml release.json)
+ STAGE="gs://${_BUCKET}/staging/forge/$${VERSION}/$BUILD_ID"
+ gcloud storage cp "$${BINARIES[@]}" "$${FEED_FILES[@]}" "$$STAGE/"
+ echo "Staged $${#BINARIES[@]} binaries for Forge $$VERSION at $$STAGE/"
+ if [ "${_PUBLISH}" != "1" ]; then
+ echo "Dry run (_PUBLISH=${_PUBLISH}): the live feed is unchanged. Publish with --substitutions _PUBLISH=1."
+ exit 0
+ fi
+ LIVE="gs://${_BUCKET}/releases/forge"
+ # Binaries first, versioned names, cached forever; the feed files that
+ # point at them last, never cached, so no client sees a feed entry
+ # before its file exists.
+ gcloud storage cp "$${BINARIES[@]}" "$$LIVE/" --cache-control="public, max-age=31536000, immutable"
+ gcloud storage cp release.json "$$LIVE/versions/$${VERSION}.json" --cache-control="public, max-age=300"
+ gcloud storage cp "$${FEED_FILES[@]}" "$$LIVE/" --cache-control="no-cache, max-age=0"
+ echo "Published three.ws Forge $$VERSION to https://three.ws/releases/forge/"
+
+substitutions:
+ _BUCKET: three-ws-desktop-releases
+ _PUBLISH: '0'
+
+serviceAccount: projects/aerial-vehicle-466722-p5/serviceAccounts/[email protected]
+timeout: 5400s
+options:
+ machineType: E2_HIGHCPU_8
+ logging: CLOUD_LOGGING_ONLY
+ diskSizeGb: 150
+tags: ['three-ws-forge-release']
diff --git a/apps/forge-desktop/electron-builder.config.cjs b/apps/forge-desktop/electron-builder.config.cjs
new file mode 100644
index 000000000..bb1bf2db1
--- /dev/null
+++ b/apps/forge-desktop/electron-builder.config.cjs
@@ -0,0 +1,104 @@
+// electron-builder configuration for three.ws Forge.
+//
+// Targets: macOS arm64 .dmg and .zip, Windows NSIS installer, Linux .AppImage
+// and .deb. Each build bundles a standalone CPython (resources/python-embed,
+// fetched by scripts/download-python-embed.js for the target platform) that
+// creates the local generation backend's virtualenv on first launch.
+//
+// Artifacts land in dist/ with the names apps/desktop/scripts/release-manifest.mjs
+// classifies, and are published to the release bucket behind the three.ws CDN
+// (https://three.ws/releases/forge/) by apps/forge-desktop/cloudbuild.yaml
+// (Linux and Windows) and scripts/release-mac.sh (macOS). The runbook is
+// docs/ops/forge-desktop-release.md.
+//
+// Signing follows three.ws Desktop: the Windows certificate and the Apple
+// Developer ID come from Secret Manager when present. Without them the build is
+// complete and installable, ad-hoc signed on macOS (scripts/after-pack.js) and
+// unsigned on Windows.
+
+const FEED_URL = process.env.THREE_WS_RELEASE_FEED || 'https://three.ws/releases/forge';
+
+const macSigned = Boolean(process.env.CSC_LINK || process.env.CSC_NAME);
+const macNotarize = macSigned && Boolean(process.env.APPLE_API_KEY && process.env.APPLE_API_KEY_ID && process.env.APPLE_API_ISSUER);
+
+const pythonEmbed = [{ from: 'resources/python-embed', to: 'python-embed' }];
+
+/** @type {import('electron-builder').Configuration} */
+module.exports = {
+ appId: 'ws.three.forge',
+ productName: 'three.ws Forge',
+ copyright: 'Copyright three.ws. Based on Modly by Lightning Pixel (MIT).',
+ artifactName: 'three.ws-Forge-${version}-${os}-${arch}.${ext}',
+ directories: { output: 'dist', buildResources: 'resources' },
+ files: ['out/**/*', 'resources/icons/**/*'],
+ extraResources: [
+ {
+ from: 'api',
+ to: 'api',
+ filter: ['**/*', '!.venv/**/*', '!venv/**/*', '!__pycache__/**/*', '!**/build/**/*', '!**/*.pyd', '!**/*.egg-info/**/*', '!**/test_*.py'],
+ },
+ { from: 'out/builtin-extensions', to: 'builtin-extensions' },
+ { from: 'LICENSE', to: 'LICENSE' },
+ { from: 'NOTICE', to: 'NOTICE' },
+ ],
+ // ad-hoc signs the macOS bundle when no Developer ID is configured
+ afterPack: macSigned ? undefined : 'scripts/after-pack.js',
+ // The generic provider is a static directory. electron-builder writes
+ // latest.yml / latest-mac.yml / latest-linux.yml beside the artifacts and
+ // bakes this URL into app-update.yml, which electron/main/updater.ts reads.
+ publish: [{ provider: 'generic', url: FEED_URL, channel: 'latest' }],
+ mac: {
+ category: 'public.app-category.graphics-design',
+ icon: 'resources/icons/icon.png',
+ target: [
+ { target: 'dmg', arch: ['arm64'] },
+ { target: 'zip', arch: ['arm64'] },
+ ],
+ minimumSystemVersion: '12.0',
+ identity: macSigned ? undefined : null,
+ hardenedRuntime: macSigned,
+ notarize: macNotarize,
+ extraResources: pythonEmbed,
+ extendInfo: { NSHumanReadableCopyright: 'three.ws. Based on Modly by Lightning Pixel (MIT).' },
+ },
+ dmg: {
+ sign: false,
+ writeUpdateInfo: false,
+ title: 'three.ws Forge ${version}',
+ },
+ win: {
+ icon: 'resources/icons/icon.png',
+ target: [{ target: 'nsis', arch: ['x64'] }],
+ publisherName: 'three.ws',
+ extraResources: pythonEmbed,
+ },
+ nsis: {
+ oneClick: false,
+ perMachine: false,
+ allowToChangeInstallationDirectory: true,
+ createDesktopShortcut: true,
+ createStartMenuShortcut: true,
+ shortcutName: 'three.ws Forge',
+ artifactName: 'three.ws-Forge-${version}-win-${arch}-setup.${ext}',
+ differentialPackage: true,
+ },
+ linux: {
+ icon: 'resources/icons/icon.png',
+ category: 'Graphics',
+ target: [
+ { target: 'AppImage', arch: ['x64'] },
+ { target: 'deb', arch: ['x64'] },
+ ],
+ extraResources: pythonEmbed,
+ executableName: 'three-ws-forge',
+ maintainer: 'three.ws <[email protected]>',
+ vendor: 'three.ws',
+ synopsis: 'Image-to-3D generation and mesh workflows on your machine or the three.ws cloud',
+ description: 'Turn images and prompts into 3D models with local open-source generators or the three.ws Forge cloud, chain mesh processing in a node workflow editor, and publish the result to your three.ws account.',
+ desktop: { StartupWMClass: 'three.ws Forge' },
+ },
+ deb: {
+ packageName: 'three-ws-forge',
+ depends: ['libnotify4', 'libxtst6', 'libnss3', 'libsecret-1-0'],
+ },
+};
diff --git a/apps/forge-desktop/electron/main/copy-runtime.ts b/apps/forge-desktop/electron/main/copy-runtime.ts
index cbb2a58dc..d5434c1c8 100644
--- a/apps/forge-desktop/electron/main/copy-runtime.ts
+++ b/apps/forge-desktop/electron/main/copy-runtime.ts
@@ -14,7 +14,7 @@ import { cp } from 'fs/promises'
* `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_three.ws Forge-XXXXXX/, which is a different path on every launch, the
+ * /tmp/.mount_<app>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
diff --git a/apps/forge-desktop/electron/main/ipc-handlers.ts b/apps/forge-desktop/electron/main/ipc-handlers.ts
index 5a271ee54..f5aee83ed 100644
--- a/apps/forge-desktop/electron/main/ipc-handlers.ts
+++ b/apps/forge-desktop/electron/main/ipc-handlers.ts
@@ -90,6 +90,7 @@ 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'
+import { registerThreeWsIpcHandlers } from './three-ws-ipc'
type WindowGetter = () => BrowserWindow | null
const pExecFile = promisify(execFile)
@@ -910,6 +911,9 @@ export function setupIpcHandlers(pythonBridge: PythonBridge, getWindow: WindowGe
}
}
+ // three.ws account, publishing and the CC0 library (three-ws-ipc.ts).
+ registerThreeWsIpcHandlers(getWindow)
+
ipcMain.handle('settings:get', () => {
// hfToken is stored encrypted, hand the renderer the usable value.
return { ...getSettings(app.getPath('userData')), hfToken: getHfToken() }
@@ -1122,8 +1126,14 @@ export function setupIpcHandlers(pythonBridge: PythonBridge, getWindow: WindowGe
}
})
- // Remote registry: list of trusted GitHub repo URLs
- const REGISTRY_URL = 'https://raw.githubusercontent.com/lightningpixel/modly-official-extension/main/registry.json'
+ // Remote registries: lists of trusted GitHub repo URLs. three.ws publishes
+ // its own list, and the upstream Modly list keeps the official model
+ // extensions (Hunyuan3D mini, TripoSG, TRELLIS.2) marked trusted. A repo is
+ // trusted when either list names it.
+ const REGISTRY_URLS = [
+ 'https://three.ws/forge-desktop/registry.json',
+ '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
@@ -1133,20 +1143,24 @@ export function setupIpcHandlers(pythonBridge: PythonBridge, getWindow: WindowGe
if (registryCache && now - registryCache.fetchedAt < REGISTRY_TTL) {
return registryCache.repos
}
- try {
- const { net } = require('electron')
- const res = await net.fetch(REGISTRY_URL)
+ const { net } = require('electron')
+ const lists = await Promise.allSettled(REGISTRY_URLS.map(async (url) => {
+ const res = await net.fetch(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
+ const data = await res.json() as { trusted_repos?: unknown }
+ if (!Array.isArray(data.trusted_repos)) throw new Error('trusted_repos missing')
+ return data.trusted_repos.filter((r): r is string => typeof r === 'string')
+ }))
+ const fetched = lists.filter((l): l is PromiseFulfilledResult<string[]> => l.status === 'fulfilled')
+ if (fetched.length === 0) {
+ // Offline or every fetch failed: keep previous cache, or empty
return registryCache?.repos ?? new Set()
}
+ const repos = new Set(
+ fetched.flatMap((l) => l.value).map((r) => r.toLowerCase().replace(/\/$/, ''))
+ )
+ registryCache = { repos, fetchedAt: now }
+ return repos
}
function isTrustedSource(source: string | undefined, trustedRepos: Set<string>): boolean {
@@ -1485,8 +1499,10 @@ export function setupIpcHandlers(pythonBridge: PythonBridge, getWindow: WindowGe
readExtensionsFromDir(builtinDir, true),
])
- // Built-ins come first, then user extensions
- return [...builtinExts, ...userExts]
+ // Built-ins come first, then user extensions. A user-installed extension
+ // with a built-in's id replaces it, matching the backend registry.
+ const userIds = new Set(userExts.map((ext) => ext.id))
+ return [...builtinExts.filter((ext) => !userIds.has(ext.id)), ...userExts]
})
// Install an extension from a GitHub repo URL
diff --git a/apps/forge-desktop/electron/main/process-runner.ts b/apps/forge-desktop/electron/main/process-runner.ts
index 9072bbc2a..fad6ba47c 100644
--- a/apps/forge-desktop/electron/main/process-runner.ts
+++ b/apps/forge-desktop/electron/main/process-runner.ts
@@ -3,6 +3,7 @@ import { spawn } from 'child_process'
import { existsSync } from 'fs'
import { join } from 'path'
import { app } from 'electron'
+import { getThreeWsApiKey, THREE_WS_ORIGIN } from './three-ws-account'
// ─── Worker code for JS process extensions ────────────────────────────────────
@@ -232,6 +233,9 @@ export class PythonProcessRunner implements IProcessRunner {
// template read these names, so both spellings are exported.
MODLY_API_DIR: apiDir,
MODLY_NODE_EXECUTABLE: process.execPath,
+ // The signed-in three.ws account, so the bundled three.ws nodes
+ // (publish, cloud generation) work without pasting a key per node.
+ ...threeWsEnv(),
EXTENSION_DIR: this.extDir,
WORKSPACE_DIR: this.workspaceDir,
TEMP_DIR: this.tempDir,
@@ -307,6 +311,11 @@ export class PythonProcessRunner implements IProcessRunner {
terminate(): void {}
}
+function threeWsEnv(): Record<string, string> {
+ const key = getThreeWsApiKey()
+ return key ? { THREE_WS_API_KEY: key, THREE_WS_BASE_URL: THREE_WS_ORIGIN } : { THREE_WS_BASE_URL: THREE_WS_ORIGIN }
+}
+
// ─── Helper: find Python executable for an extension ─────────────────────────
export function getExtPythonExe(extDir: string): string | null {
diff --git a/apps/forge-desktop/electron/main/python-bridge.ts b/apps/forge-desktop/electron/main/python-bridge.ts
index e78e39ce6..80370fbc5 100644
--- a/apps/forge-desktop/electron/main/python-bridge.ts
+++ b/apps/forge-desktop/electron/main/python-bridge.ts
@@ -5,8 +5,10 @@ import { existsSync, mkdirSync } from 'fs'
import axios from 'axios'
import { ensureAgentDir, getSettings } from './settings-store'
import { getHfToken } from './hf-token'
+import { getThreeWsApiKey, THREE_WS_ORIGIN } from './three-ws-account'
import { logger } from './logger'
import { cleanPythonEnv, getVenvPythonExe } from './python-setup'
+import { getBuiltinExtensionsDir } from './builtin-sync'
const API_PORT = 8765
const API_HOST = '127.0.0.1'
@@ -66,11 +68,18 @@ export class PythonBridge {
MODELS_DIR: this.resolveModelsDir(),
WORKSPACE_DIR: this.resolveWorkspaceDir(),
EXTENSIONS_DIR: this.resolveExtensionsDir(),
+ // Model extensions bundled with the app (the three.ws cloud generator).
+ BUILTIN_EXTENSIONS_DIR: getBuiltinExtensionsDir(),
// llm_server.py keeps everything of the local LLM here: engine, GGUF models, logs, config.
THREEWS_LLM_DIR: this.resolveAgentDir(),
SELECTED_MODEL_ID: process.env['SELECTED_MODEL_ID'] ?? '',
HUGGING_FACE_HUB_TOKEN: this.resolveHfToken(),
HF_TOKEN: this.resolveHfToken(),
+ // The three.ws account from Settings → three.ws, for the bundled
+ // cloud generator and publish node. Sign-in later updates it through
+ // POST /settings/three-ws without a restart.
+ THREE_WS_BASE_URL: THREE_WS_ORIGIN,
+ ...(getThreeWsApiKey() ? { THREE_WS_API_KEY: getThreeWsApiKey() } : {}),
},
// On Unix, put the bridge in its own process group so every subprocess
// it spawns (extension runners, etc.) inherits that group. On shutdown
diff --git a/apps/forge-desktop/electron/main/python-setup.ts b/apps/forge-desktop/electron/main/python-setup.ts
index c5922a09b..be787aea9 100644
--- a/apps/forge-desktop/electron/main/python-setup.ts
+++ b/apps/forge-desktop/electron/main/python-setup.ts
@@ -156,7 +156,7 @@ export function markSetupDone(userData: string): void {
/**
* On Linux AppImage, process.resourcesPath resolves to an ephemeral mount point
- * (/tmp/.mount_three.ws Forge-XXXXXX/) that changes every launch, which breaks venv symlinks.
+ * (/tmp/.mount_<app>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> {
diff --git a/apps/forge-desktop/electron/main/settings-store.ts b/apps/forge-desktop/electron/main/settings-store.ts
index a02797970..73d80870b 100644
--- a/apps/forge-desktop/electron/main/settings-store.ts
+++ b/apps/forge-desktop/electron/main/settings-store.ts
@@ -10,6 +10,8 @@ export interface AppSettings {
/** Local LLM engine, GGUF models, logs and config used by the agent. */
agentDir: string
hfToken?: string
+ /** three.ws API key from Settings → three.ws, encrypted (secure-store.ts). */
+ threeWsApiKey?: string
}
function settingsPath(userData: string): string {
diff --git a/apps/forge-desktop/electron/main/three-ws-account.ts b/apps/forge-desktop/electron/main/three-ws-account.ts
new file mode 100644
index 000000000..75984261d
--- /dev/null
+++ b/apps/forge-desktop/electron/main/three-ws-account.ts
@@ -0,0 +1,387 @@
+import { net, shell } from 'electron'
+import { createHash } from 'crypto'
+import { hostname } from 'os'
+import { join } from 'path'
+import { mkdir, writeFile } from 'fs/promises'
+import { getSettings, setSettings } from './settings-store'
+import { encryptSecretSync, decryptSecretSync } from './secure-store'
+import { logger } from './logger'
+import { AVATAR_VISIBILITIES } from '../../src/shared/types/threeWs'
+import type {
+ AvatarVisibility,
+ DeviceLink,
+ LibraryObject,
+ LibraryPage,
+ PublishResult,
+ ThreeWsAccount,
+} from '../../src/shared/types/threeWs'
+
+export { AVATAR_VISIBILITIES }
+export type { AvatarVisibility, DeviceLink, LibraryObject, LibraryPage, PublishResult, ThreeWsAccount }
+
+/**
+ * The three.ws account behind Forge: sign-in through the same device flow the
+ * `three-ws` CLI uses (/api/cli/link, /api/cli/token), the resulting API key
+ * stored encrypted at rest like the Hugging Face token, publishing a GLB to the
+ * account (/api/avatars/upload then /api/avatars), and the CC0 object library
+ * (/api/objects/library, /api/catalog).
+ *
+ * Every call runs in the main process through Electron's net stack, so the
+ * renderer never sees the key and system proxies are honoured.
+ */
+
+export const THREE_WS_ORIGIN = (process.env.THREE_WS_BASE_URL || 'https://three.ws').replace(/\/+$/, '')
+
+// Publishing needs avatars:write; profile lets whoami return the email and
+// display name shown in Settings; generate unlocks the account's Forge tiers.
+export const THREE_WS_SCOPE = 'profile avatars:read avatars:write generate'
+
+const CLIENT_NAME = 'three.ws Forge'
+const USER_AGENT = 'three-ws-forge-desktop'
+// /api/avatars/upload proxies bodies up to 50 MB; larger files take the
+// presigned path straight to storage. 500 MB is the per-avatar account limit.
+const MAX_PROXY_UPLOAD_BYTES = 50 * 1024 * 1024
+const MAX_AVATAR_BYTES = 500 * 1024 * 1024
+
+export class ThreeWsError extends Error {
+ constructor(message: string, readonly code = '', readonly status = 0) {
+ super(message)
+ this.name = 'ThreeWsError'
+ }
+}
+
+const SIGNED_OUT: ThreeWsAccount = { signedIn: false, email: null, displayName: null, username: null, scope: '', keyPrefix: null, plan: null }
+
+// ─── Key storage ─────────────────────────────────────────────────────────────
+
+let cachedKey = ''
+
+export function getThreeWsApiKey(): string {
+ return cachedKey
+}
+
+/** Decrypt the stored key into the cache. Sync for the same reason as the HF
+ * token: process-runner builds child env synchronously. */
+export function initThreeWsAccount(userData: string): void {
+ const stored = getSettings(userData).threeWsApiKey ?? ''
+ if (!stored) { cachedKey = ''; return }
+ const decrypted = decryptSecretSync(stored)
+ if (decrypted === null) {
+ cachedKey = ''
+ logger.error('[three-ws] the stored three.ws key could not be decrypted, sign in again in Settings → three.ws')
+ return
+ }
+ cachedKey = decrypted
+}
+
+function storeKey(userData: string, key: string): void {
+ cachedKey = key
+ setSettings(userData, { threeWsApiKey: key ? encryptSecretSync(key) : '' })
+}
+
+export function signOut(userData: string): ThreeWsAccount {
+ storeKey(userData, '')
+ return SIGNED_OUT
+}
+
+// ─── HTTP ────────────────────────────────────────────────────────────────────
+
+interface RequestOptions {
+ method?: 'GET' | 'POST' | 'PUT'
+ body?: unknown
+ raw?: Buffer
+ headers?: Record<string, string>
+ auth?: boolean
+}
+
+async function request<T>(path: string, opts: RequestOptions = {}): Promise<T> {
+ const headers: Record<string, string> = { accept: 'application/json', 'user-agent': USER_AGENT, ...opts.headers }
+ if (opts.auth) {
+ if (!cachedKey) throw new ThreeWsError('Sign in to three.ws first (Settings → three.ws).', 'signed_out', 401)
+ headers.authorization = `Bearer ${cachedKey}`
+ }
+ let body: string | Uint8Array | undefined
+ if (opts.body !== undefined) {
+ headers['content-type'] = 'application/json'
+ body = JSON.stringify(opts.body)
+ } else if (opts.raw) {
+ body = new Uint8Array(opts.raw)
+ }
+
+ let res: Response
+ try {
+ res = await net.fetch(`${THREE_WS_ORIGIN}${path}`, { method: opts.method ?? 'GET', headers, body })
+ } catch (err) {
+ throw new ThreeWsError(`Could not reach ${THREE_WS_ORIGIN}: ${err instanceof Error ? err.message : String(err)}`, 'unreachable')
+ }
+ const text = await res.text()
+ let parsed: Record<string, unknown> = {}
+ try { parsed = text ? JSON.parse(text) : {} } catch { parsed = { error_description: text.slice(0, 300) } }
+ if (!res.ok) {
+ const message = String(parsed.error_description || parsed.message || parsed.error || `HTTP ${res.status}`)
+ throw new ThreeWsError(message, String(parsed.error || ''), res.status)
+ }
+ return parsed as T
+}
+
+// ─── Account ─────────────────────────────────────────────────────────────────
+
+interface WhoamiResponse {
+ user: { id: string; email?: string; display_name?: string | null; username?: string | null }
+ plan: { plan: string } | null
+ credential: { scope: string; api_key: { prefix: string } | null }
+}
+
+export async function getAccount(userData: string): Promise<ThreeWsAccount> {
+ if (!cachedKey) return SIGNED_OUT
+ try {
+ const me = await request<WhoamiResponse>('/api/cli/whoami', { auth: true })
+ return {
+ signedIn: true,
+ email: me.user.email ?? null,
+ displayName: me.user.display_name ?? null,
+ username: me.user.username ?? null,
+ scope: me.credential.scope,
+ keyPrefix: me.credential.api_key?.prefix ?? null,
+ plan: me.plan?.plan ?? null,
+ }
+ } catch (err) {
+ // A revoked or expired key is dead weight: drop it so the UI offers a
+ // fresh sign-in. Network trouble keeps it, the key is probably still good.
+ if (err instanceof ThreeWsError && err.status === 401) {
+ logger.warn('[three-ws] stored key was rejected, signing out')
+ return signOut(userData)
+ }
+ throw err
+ }
+}
+
+/** Save a pasted `sk_live_` key after checking that three.ws accepts it. */
+export async function signInWithKey(userData: string, key: string): Promise<ThreeWsAccount> {
+ const trimmed = key.trim()
+ if (!trimmed) throw new ThreeWsError('Paste an API key from three.ws/dashboard/api.', 'missing_key')
+ const previous = cachedKey
+ cachedKey = trimmed
+ try {
+ const account = await getAccount(userData)
+ if (!account.signedIn) throw new ThreeWsError('three.ws rejected that key. Check it was copied whole and has not been revoked.', 'invalid_token', 401)
+ storeKey(userData, trimmed)
+ return account
+ } catch (err) {
+ cachedKey = previous
+ throw err
+ }
+}
+
+// ─── Device sign-in ──────────────────────────────────────────────────────────
+
+interface LinkResponse {
+ device_code: string
+ user_code: string
+ verification_uri_complete: string
+ expires_in: number
+ interval: number
+}
+
+let activeLink: AbortController | null = null
+
+export function cancelDeviceLink(): void {
+ activeLink?.abort()
+ activeLink = null
+}
+
+/**
+ * Start a browser sign-in. Returns the code to show as soon as the link exists,
+ * and resolves `done` once the browser approves (or rejects on deny/expiry).
+ */
+export async function startDeviceLink(userData: string): Promise<{ link: DeviceLink; done: Promise<ThreeWsAccount> }> {
+ cancelDeviceLink()
+ const controller = new AbortController()
+ activeLink = controller
+
+ const created = await request<LinkResponse>('/api/cli/link', {
+ method: 'POST',
+ body: { client_name: CLIENT_NAME, hostname: hostname().slice(0, 120), scope: THREE_WS_SCOPE },
+ })
+ await shell.openExternal(created.verification_uri_complete)
+
+ const done = pollDeviceLink(userData, created, controller.signal).finally(() => {
+ if (activeLink === controller) activeLink = null
+ })
+ return {
+ link: { userCode: created.user_code, verificationUrl: created.verification_uri_complete, expiresIn: created.expires_in },
+ done,
+ }
+}
+
+function wait(ms: number, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve, reject) => {
+ if (signal.aborted) { reject(new ThreeWsError('Sign-in cancelled.', 'cancelled')); return }
+ const timer = setTimeout(resolve, ms)
+ signal.addEventListener('abort', () => {
+ clearTimeout(timer)
+ reject(new ThreeWsError('Sign-in cancelled.', 'cancelled'))
+ }, { once: true })
+ })
+}
+
+async function pollDeviceLink(userData: string, link: LinkResponse, signal: AbortSignal): Promise<ThreeWsAccount> {
+ let interval = Math.max(1, link.interval) * 1000
+ const deadline = Date.now() + link.expires_in * 1000
+ while (Date.now() < deadline) {
+ await wait(interval, signal)
+ try {
+ const token = await request<{ access_token: string }>('/api/cli/token', { method: 'POST', body: { device_code: link.device_code } })
+ storeKey(userData, token.access_token)
+ logger.info('[three-ws] signed in through the browser')
+ return await getAccount(userData)
+ } catch (err) {
+ if (!(err instanceof ThreeWsError)) throw err
+ if (err.code === 'authorization_pending') continue
+ if (err.code === 'slow_down') { interval += 2000; continue }
+ if (err.code === 'access_denied') throw new ThreeWsError('The sign-in was denied in the browser.', err.code, err.status)
+ if (err.code === 'expired_token') throw new ThreeWsError('The sign-in code expired. Start again.', err.code, err.status)
+ // Network blips while the user is in the browser: keep polling.
+ if (err.code === 'unreachable') continue
+ throw err
+ }
+ }
+ throw new ThreeWsError('The sign-in code expired. Start again.', 'expired_token')
+}
+
+// ─── Publish ─────────────────────────────────────────────────────────────────
+
+export interface PublishInput {
+ glb: Buffer
+ name: string
+ description?: string
+ visibility: AvatarVisibility
+ tags?: string[]
+ sourceMeta?: Record<string, unknown>
+}
+
+export function isGlb(data: Buffer): boolean {
+ return data.length >= 12
+ && data.toString('latin1', 0, 4) === 'glTF'
+ && data.readUInt32LE(4) === 2
+ && data.readUInt32LE(8) === data.length
+}
+
+export function slugify(text: string): string {
+ const slug = text.toLowerCase().normalize('NFKD').replace(/[^a-z0-9_-]+/g, '-').replace(/^[-_]+|[-_]+$/g, '').slice(0, 64).replace(/[-_]+$/, '')
+ return slug || 'model'
+}
+
+export function cleanTags(tags: string[] | undefined): string[] {
+ return (tags ?? []).map((t) => t.trim().slice(0, 40)).filter(Boolean).slice(0, 20)
+}
+
+export async function publishGlb(input: PublishInput): Promise<PublishResult> {
+ const { glb } = input
+ if (!isGlb(glb)) throw new ThreeWsError('That model is not a binary glTF 2.0 (.glb) file.', 'invalid_glb')
+ if (glb.length > MAX_AVATAR_BYTES) throw new ThreeWsError('The model is larger than the 500 MB account limit. Decimate it first.', 'too_large')
+ if (!AVATAR_VISIBILITIES.includes(input.visibility)) throw new ThreeWsError('Visibility must be private, unlisted or public.', 'invalid_visibility')
+
+ const name = input.name.trim().slice(0, 120) || 'Untitled model'
+ const slug = slugify(name)
+ let checksum = createHash('sha256').update(glb).digest('hex')
+ let storageKey: string | undefined
+ let sizeBytes = glb.length
+
+ if (glb.length <= MAX_PROXY_UPLOAD_BYTES) {
+ const query = new URLSearchParams({ slug, content_type: 'model/gltf-binary', sha256: checksum })
+ const stored = await request<{ storage_key?: string; size_bytes?: number; checksum_sha256?: string }>(
+ `/api/avatars/upload?${query}`,
+ { method: 'POST', raw: glb, headers: { 'content-type': 'model/gltf-binary' }, auth: true },
+ )
+ storageKey = stored.storage_key
+ sizeBytes = stored.size_bytes ?? glb.length
+ checksum = stored.checksum_sha256 ?? checksum
+ } else {
+ const presign = await request<{ storage_key?: string; upload_url?: string; headers?: Record<string, string> }>('/api/avatars/presign', {
+ method: 'POST',
+ body: { size_bytes: glb.length, content_type: 'model/gltf-binary', checksum_sha256: checksum, slug },
+ auth: true,
+ })
+ if (!presign.storage_key || !presign.upload_url) throw new ThreeWsError('three.ws returned no upload URL.', 'presign_failed')
+ const put = await net.fetch(presign.upload_url, {
+ method: 'PUT',
+ headers: presign.headers ?? { 'content-type': 'model/gltf-binary' },
+ body: new Uint8Array(glb),
+ })
+ if (!put.ok) throw new ThreeWsError(`The model upload failed (HTTP ${put.status}).`, 'upload_failed', put.status)
+ storageKey = presign.storage_key
+ }
+ if (!storageKey) throw new ThreeWsError('three.ws returned no storage key for the upload.', 'upload_failed')
+
+ const body: Record<string, unknown> = {
+ name,
+ storage_key: storageKey,
+ size_bytes: sizeBytes,
+ content_type: 'model/gltf-binary',
+ checksum_sha256: checksum,
+ visibility: input.visibility,
+ tags: cleanTags(input.tags),
+ source: 'upload',
+ source_meta: { client: 'three.ws Forge', ...input.sourceMeta },
+ }
+ const description = input.description?.trim()
+ if (description) body.description = description.slice(0, 2000)
+
+ const created = await request<{ avatar?: { id?: string; name?: string; visibility?: string } }>('/api/avatars', { method: 'POST', body, auth: true })
+ const avatar = created.avatar
+ if (!avatar?.id) throw new ThreeWsError('three.ws did not return the saved model.', 'create_failed')
+ return {
+ id: avatar.id,
+ name: avatar.name ?? name,
+ visibility: avatar.visibility ?? input.visibility,
+ url: `${THREE_WS_ORIGIN}/avatars/${encodeURIComponent(avatar.id)}`,
+ }
+}
+
+// ─── CC0 object library ──────────────────────────────────────────────────────
+
+function toLibraryObject(raw: Record<string, unknown>): LibraryObject | null {
+ const url = typeof raw.url === 'string' ? raw.url : ''
+ if (!/^https:\/\//.test(url)) return null
+ const name = String(raw.name ?? '')
+ return {
+ name,
+ label: String(raw.label ?? raw.title ?? name),
+ url,
+ thumb: typeof raw.thumb === 'string' ? raw.thumb : null,
+ bytes: typeof raw.bytes === 'number' ? raw.bytes : null,
+ categories: Array.isArray(raw.categories) ? raw.categories.map(String) : [],
+ tags: Array.isArray(raw.tags) ? raw.tags.map(String) : [],
+ license: String(raw.license ?? 'CC0'),
+ source: typeof raw.source === 'string' ? raw.source : null,
+ }
+}
+
+export async function listLibrary(offset: number, limit: number): Promise<LibraryPage> {
+ const query = new URLSearchParams({ offset: String(Math.max(0, offset)), limit: String(Math.min(Math.max(1, limit), 100)) })
+ const page = await request<{ objects?: Record<string, unknown>[]; total?: number }>(`/api/objects/library?${query}`)
+ const objects = (page.objects ?? []).map(toLibraryObject).filter((o): o is LibraryObject => o !== null)
+ return { objects, total: page.total ?? objects.length }
+}
+
+export async function searchLibrary(q: string, limit: number): Promise<LibraryPage> {
+ const query = new URLSearchParams({ q: q.trim().slice(0, 120), kind: 'object', limit: String(Math.min(Math.max(1, limit), 50)) })
+ const page = await request<{ items?: Record<string, unknown>[]; matched?: number }>(`/api/catalog?${query}`)
+ const objects = (page.items ?? []).map(toLibraryObject).filter((o): o is LibraryObject => o !== null)
+ return { objects, total: page.matched ?? objects.length }
+}
+
+/** Download one library object into `dir` and return the local path. */
+export async function downloadLibraryObject(object: Pick<LibraryObject, 'url' | 'name'>, dir: string): Promise<string> {
+ const url = new URL(object.url)
+ if (url.protocol !== 'https:') throw new ThreeWsError('Library objects are only fetched over HTTPS.', 'invalid_url')
+ const res = await net.fetch(url.toString(), { headers: { 'user-agent': USER_AGENT } })
+ if (!res.ok) throw new ThreeWsError(`Could not download ${object.name} (HTTP ${res.status}).`, 'download_failed', res.status)
+ const data = Buffer.from(await res.arrayBuffer())
+ if (!isGlb(data)) throw new ThreeWsError(`${object.name} is not a valid GLB file.`, 'invalid_glb')
+ await mkdir(dir, { recursive: true })
+ const file = join(dir, `${slugify(object.name)}.glb`)
+ await writeFile(file, data)
+ return file
+}
diff --git a/apps/forge-desktop/electron/main/three-ws-ipc.ts b/apps/forge-desktop/electron/main/three-ws-ipc.ts
new file mode 100644
index 000000000..d39b22b70
--- /dev/null
+++ b/apps/forge-desktop/electron/main/three-ws-ipc.ts
@@ -0,0 +1,133 @@
+import { ipcMain, app, shell } from 'electron'
+import { join } from 'path'
+import { tmpdir } from 'os'
+import { API_BASE_URL } from './python-bridge'
+import { logger } from './logger'
+import {
+ THREE_WS_ORIGIN,
+ ThreeWsError,
+ cancelDeviceLink,
+ downloadLibraryObject,
+ getAccount,
+ getThreeWsApiKey,
+ initThreeWsAccount,
+ listLibrary,
+ publishGlb,
+ searchLibrary,
+ signInWithKey,
+ signOut,
+ startDeviceLink,
+ type LibraryObject,
+} from './three-ws-account'
+import type { PublishRequest, ThreeWsResult } from '../../src/shared/types/threeWs'
+
+type WindowGetter = () => Electron.BrowserWindow | null
+
+
+// IPC errors lose their class across the bridge, so each handler returns a
+// tagged result the renderer can show as-is.
+async function wrap<T>(label: string, fn: () => Promise<T>): Promise<ThreeWsResult<T>> {
+ try {
+ return { ok: true, value: await fn() }
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err)
+ const code = err instanceof ThreeWsError ? err.code : ''
+ if (code !== 'cancelled') logger.warn(`[three-ws] ${label} failed: ${message}`)
+ return { ok: false, error: message, code }
+ }
+}
+
+// The cloud generator runs inside the FastAPI process, which was spawned with
+// whatever key existed at launch. Push changes so it never needs a restart.
+async function syncBackendKey(): Promise<void> {
+ try {
+ await fetch(`${API_BASE_URL}/settings/three-ws`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ api_key: getThreeWsApiKey(), base_url: THREE_WS_ORIGIN }),
+ signal: AbortSignal.timeout(3000),
+ })
+ } catch (err) {
+ // Not started yet: it reads the key from its spawn env when it does.
+ logger.info(`[three-ws] backend key sync skipped: ${err instanceof Error ? err.message : String(err)}`)
+ }
+}
+
+/** Read a model the local backend serves (a /workspace/... or /optimize/... URL). */
+async function readLocalModel(outputUrl: string): Promise<Buffer> {
+ if (!outputUrl.startsWith('/')) throw new ThreeWsError('Only models in the Forge workspace can be published.', 'invalid_source')
+ const res = await fetch(`${API_BASE_URL}${outputUrl}`)
+ if (!res.ok) throw new ThreeWsError(`Could not read the model from the local backend (HTTP ${res.status}).`, 'read_failed', res.status)
+ return Buffer.from(await res.arrayBuffer())
+}
+
+export function registerThreeWsIpcHandlers(getWindow: WindowGetter): void {
+ const userData = app.getPath('userData')
+ initThreeWsAccount(userData)
+
+ ipcMain.handle('threews:origin', () => THREE_WS_ORIGIN)
+
+ ipcMain.handle('threews:account', () => wrap('account', () => getAccount(userData)))
+
+ ipcMain.handle('threews:signInWithKey', (_e, key: string) =>
+ wrap('sign-in with key', async () => {
+ const account = await signInWithKey(userData, String(key ?? ''))
+ await syncBackendKey()
+ return account
+ }))
+
+ ipcMain.handle('threews:signOut', () => wrap('sign-out', async () => {
+ const account = signOut(userData)
+ await syncBackendKey()
+ return account
+ }))
+
+ // Starts the browser sign-in and answers with the code right away; the
+ // outcome arrives later as a threews:linkResult event.
+ ipcMain.handle('threews:startLink', () => wrap('start sign-in', async () => {
+ const { link, done } = await startDeviceLink(userData)
+ done.then(
+ async (account) => {
+ await syncBackendKey()
+ getWindow()?.webContents.send('threews:linkResult', { ok: true, value: account })
+ },
+ (err: unknown) => {
+ const code = err instanceof ThreeWsError ? err.code : ''
+ if (code === 'cancelled') return
+ getWindow()?.webContents.send('threews:linkResult', { ok: false, error: err instanceof Error ? err.message : String(err), code })
+ },
+ )
+ return link
+ }))
+
+ ipcMain.handle('threews:cancelLink', () => { cancelDeviceLink() })
+
+ ipcMain.handle('threews:publish', (_e, args: PublishRequest) =>
+ wrap('publish', async () => {
+ const glb = await readLocalModel(String(args?.outputUrl ?? ''))
+ return publishGlb({
+ glb,
+ name: String(args.name ?? ''),
+ description: args.description,
+ visibility: args.visibility,
+ tags: Array.isArray(args.tags) ? args.tags.map(String) : [],
+ sourceMeta: { app_version: app.getVersion() },
+ })
+ }))
+
+ ipcMain.handle('threews:libraryList', (_e, args: { offset?: number; limit?: number }) =>
+ wrap('library list', () => listLibrary(Number(args?.offset ?? 0), Number(args?.limit ?? 48))))
+
+ ipcMain.handle('threews:librarySearch', (_e, args: { q: string; limit?: number }) =>
+ wrap('library search', () => searchLibrary(String(args?.q ?? ''), Number(args?.limit ?? 48))))
+
+ ipcMain.handle('threews:libraryDownload', (_e, object: Pick<LibraryObject, 'url' | 'name'>) =>
+ wrap('library download', () => downloadLibraryObject(object, join(tmpdir(), 'three-ws-forge-library'))))
+
+ // Only three.ws pages: the renderer opens published models and the dashboard.
+ ipcMain.handle('threews:open', (_e, path: string) => {
+ const url = new URL(String(path ?? '/'), THREE_WS_ORIGIN)
+ if (url.origin !== new URL(THREE_WS_ORIGIN).origin) return
+ void shell.openExternal(url.toString())
+ })
+}
diff --git a/apps/forge-desktop/electron/preload/electron-api.ts b/apps/forge-desktop/electron/preload/electron-api.ts
index 0d5f4250d..b97a8d65b 100644
--- a/apps/forge-desktop/electron/preload/electron-api.ts
+++ b/apps/forge-desktop/electron/preload/electron-api.ts
@@ -5,6 +5,15 @@ import type {
AssetLibraryReadRequest,
AssetLibraryReadResult,
} from '../../src/shared/types/assetLibrary'
+import type {
+ DeviceLink,
+ LibraryObject,
+ LibraryPage,
+ PublishRequest,
+ PublishResult,
+ ThreeWsAccount,
+ ThreeWsResult,
+} from '../../src/shared/types/threeWs'
export interface IpcRendererLike {
invoke(channel: string, ...args: unknown[]): Promise<unknown>
@@ -302,6 +311,34 @@ export function createElectronApi(ipcRenderer: IpcRendererLike, webFrame: WebFra
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 }>,
},
+ // three.ws account, publishing and the CC0 object library. The API key
+ // stays in the main process; these calls only ever return account info.
+ threews: {
+ origin: (): Promise<string> => ipcRenderer.invoke('threews:origin') as Promise<string>,
+ account: (): Promise<ThreeWsResult<ThreeWsAccount>> =>
+ ipcRenderer.invoke('threews:account') as Promise<ThreeWsResult<ThreeWsAccount>>,
+ signInWithKey: (key: string): Promise<ThreeWsResult<ThreeWsAccount>> =>
+ ipcRenderer.invoke('threews:signInWithKey', key) as Promise<ThreeWsResult<ThreeWsAccount>>,
+ signOut: (): Promise<ThreeWsResult<ThreeWsAccount>> =>
+ ipcRenderer.invoke('threews:signOut') as Promise<ThreeWsResult<ThreeWsAccount>>,
+ startLink: (): Promise<ThreeWsResult<DeviceLink>> =>
+ ipcRenderer.invoke('threews:startLink') as Promise<ThreeWsResult<DeviceLink>>,
+ cancelLink: (): Promise<void> => ipcRenderer.invoke('threews:cancelLink') as Promise<void>,
+ onLinkResult: (cb: (result: ThreeWsResult<ThreeWsAccount>) => void) => {
+ ipcRenderer.on('threews:linkResult', (_event, result) => cb(result as ThreeWsResult<ThreeWsAccount>))
+ },
+ offLinkResult: () => ipcRenderer.removeAllListeners('threews:linkResult'),
+ publish: (args: PublishRequest): Promise<ThreeWsResult<PublishResult>> =>
+ ipcRenderer.invoke('threews:publish', args) as Promise<ThreeWsResult<PublishResult>>,
+ libraryList: (args: { offset?: number; limit?: number }): Promise<ThreeWsResult<LibraryPage>> =>
+ ipcRenderer.invoke('threews:libraryList', args) as Promise<ThreeWsResult<LibraryPage>>,
+ librarySearch: (args: { q: string; limit?: number }): Promise<ThreeWsResult<LibraryPage>> =>
+ ipcRenderer.invoke('threews:librarySearch', args) as Promise<ThreeWsResult<LibraryPage>>,
+ libraryDownload: (object: Pick<LibraryObject, 'url' | 'name'>): Promise<ThreeWsResult<string>> =>
+ ipcRenderer.invoke('threews:libraryDownload', object) as Promise<ThreeWsResult<string>>,
+ open: (path: string): Promise<void> => ipcRenderer.invoke('threews:open', path) as Promise<void>,
+ },
+
// Auto-updater
updater: {
check: (): Promise<{ success: boolean }> =>
diff --git a/apps/forge-desktop/package.json b/apps/forge-desktop/package.json
index d661d5457..f9922caf2 100644
--- a/apps/forge-desktop/package.json
+++ b/apps/forge-desktop/package.json
@@ -12,11 +12,14 @@
"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",
+ "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 src/areas/generate/threeWsPublish.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 --config electron-builder.config.cjs",
+ "package:mac": "cross-env CSC_IDENTITY_AUTO_DISCOVERY=false npm run build && npm run prepare-resources -- --platform darwin --arch arm64 && electron-builder --config electron-builder.config.cjs --mac",
"lint": "eslint .",
- "icons": "node scripts/make-icons.mjs"
+ "icons": "node scripts/make-icons.mjs",
+ "package:linux": "npm run build && npm run prepare-resources -- --platform linux --arch x64 && electron-builder --config electron-builder.config.cjs --linux --publish never",
+ "package:win": "npm run build && npm run prepare-resources -- --platform win32 --arch x64 && electron-builder --config electron-builder.config.cjs --win --publish never",
+ "release:manifest": "node scripts/release-manifest.mjs"
},
"dependencies": {
"@electron-toolkit/utils": "^4.0.0",
@@ -61,88 +64,6 @@
"overrides": {
"esbuild": "^0.28.0"
},
- "build": {
- "appId": "ws.three.forge",
- "productName": "three.ws Forge",
- "directories": {
- "output": "dist"
- },
- "afterPack": "scripts/after-pack.js",
- "files": [
- "out/**/*",
- "resources/icons/**/*"
- ],
- "extraResources": [
- {
- "from": "api",
- "to": "api",
- "filter": [
- "**/*",
- "!.venv/**/*",
- "!__pycache__/**/*",
- "!**/build/**/*",
- "!**/*.pyd",
- "!**/*.egg-info/**/*"
- ]
- },
- {
- "from": "out/builtin-extensions",
- "to": "builtin-extensions"
- }
- ],
- "publish": [
- {
- "provider": "generic",
- "url": "https://three.ws/releases/forge",
- "channel": "latest"
- }
- ],
- "nsis": {
- "oneClick": false,
- "allowToChangeInstallationDirectory": true,
- "shortcutName": "three.ws Forge"
- },
- "win": {
- "target": "nsis",
- "artifactName": "${productName}-Setup-${version}.${ext}",
- "icon": "resources/icons/icon.png",
- "extraResources": [
- {
- "from": "resources/python-embed",
- "to": "python-embed"
- }
- ]
- },
- "mac": {
- "target": "dmg",
- "icon": "resources/icons/icon.png",
- "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"
- }
- ],
- "category": "Graphics",
- "executableName": "three-ws-forge",
- "maintainer": "three.ws <[email protected]>",
- "vendor": "three.ws",
- "synopsis": "Image-to-3D generation and mesh workflows on your machine or the three.ws cloud"
- },
- "copyright": "Copyright three.ws. Based on Modly by Lightning Pixel (MIT)."
- },
"homepage": "https://three.ws/forge-desktop",
"license": "MIT"
}
diff --git a/apps/forge-desktop/releases.json b/apps/forge-desktop/releases.json
new file mode 100644
index 000000000..9d4bee621
--- /dev/null
+++ b/apps/forge-desktop/releases.json
@@ -0,0 +1,17 @@
+{
+ "$comment": "Release history for three.ws Forge, newest first. scripts/release-manifest.mjs copies the current version's notes into the published release.json that https://three.ws/forge-desktop and the in-app updater show. Add an entry here before building a new version.",
+ "releases": [
+ {
+ "version": "0.5.0",
+ "date": "2026-10-09",
+ "notes": [
+ {
+ "date": "2026-10-09",
+ "title": "three.ws Forge, the desktop 3D studio",
+ "summary": "Generate 3D models from images and prompts with local open-source generators or the three.ws Forge cloud, chain mesh processing in a node workflow editor, browse the CC0 object library, and publish straight to your three.ws account. Built on Modly by Lightning Pixel (MIT).",
+ "tags": ["feature"]
+ }
+ ]
+ }
+ ]
+}
diff --git a/apps/forge-desktop/scripts/build-builtins.mjs b/apps/forge-desktop/scripts/build-builtins.mjs
index 0d723821b..b3d1da042 100644
--- a/apps/forge-desktop/scripts/build-builtins.mjs
+++ b/apps/forge-desktop/scripts/build-builtins.mjs
@@ -1,16 +1,22 @@
/**
- * Compile built-in extensions (TypeScript → CommonJS JS) and copy manifests.
+ * Compile built-in extensions (TypeScript → CommonJS JS) and copy manifests,
+ * then bundle the three.ws cloud extensions from integrations/modly/.
* Output: out/builtin-extensions/{id}/processor.js + manifest.json
*/
import { execSync } from 'child_process'
-import { readdirSync, existsSync, cpSync, mkdirSync, statSync } from 'fs'
+import { readdirSync, existsSync, cpSync, mkdirSync, rmSync, 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')
+// The three.ws Forge extensions are published for upstream Modly users from
+// integrations/modly/ in this repo. The desktop app ships the same source as
+// built-ins, so a fix there lands in both places at once.
+const cloudSrcDir = join(root, '..', '..', 'integrations', 'modly')
+const CLOUD_EXTENSIONS = ['three-ws', 'three-ws-publish']
if (!existsSync(srcDir)) {
console.log('[build-builtins] No builtin-extensions directory found, skipping.')
@@ -59,4 +65,20 @@ for (const id of readdirSync(srcDir)) {
}
}
+// 3. Bundle the three.ws cloud generator and the Publish to three.ws node.
+for (const id of CLOUD_EXTENSIONS) {
+ const extSrcDir = join(cloudSrcDir, id)
+ if (!existsSync(join(extSrcDir, 'manifest.json'))) {
+ console.error(`[build-builtins] ${id}: missing ${extSrcDir}/manifest.json. The cloud extensions are part of the app; restore integrations/modly/${id}.`)
+ process.exit(1)
+ }
+ const extOutDir = join(outDir, id)
+ rmSync(extOutDir, { recursive: true, force: true })
+ cpSync(extSrcDir, extOutDir, {
+ recursive: true,
+ filter: (src) => !/(^|[\\/])(__pycache__|test_[^\\/]*\.py)$/.test(src),
+ })
+ console.log(`[build-builtins] ${id}: bundled from integrations/modly`)
+}
+
console.log('[build-builtins] Done.')
diff --git a/apps/forge-desktop/scripts/download-python-embed.js b/apps/forge-desktop/scripts/download-python-embed.js
index 4d104d66a..a03623ba8 100644
--- a/apps/forge-desktop/scripts/download-python-embed.js
+++ b/apps/forge-desktop/scripts/download-python-embed.js
@@ -12,11 +12,25 @@ const EMBED_DIR = path.join(RESOURCES_DIR, 'python-embed')
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'
+// The target defaults to the host. Release builds pass --platform and --arch
+// so one Linux machine can package the Windows installer with a Windows Python.
+function parseTarget(argv) {
+ const target = { platform: process.platform, arch: process.arch }
+ for (let i = 0; i < argv.length; i++) {
+ if (argv[i] === '--platform') target.platform = argv[++i]
+ else if (argv[i] === '--arch') target.arch = argv[++i]
+ else throw new Error(`Unknown argument: ${argv[i]}`)
+ }
+ if (!['win32', 'darwin', 'linux'].includes(target.platform)) throw new Error(`Unsupported platform: ${target.platform}`)
+ if (!['x64', 'arm64'].includes(target.arch)) throw new Error(`Unsupported arch: ${target.arch}`)
+ return target
+}
+
+function getPbsUrl({ platform, arch: nodeArch }) {
+ const arch = nodeArch === 'arm64' ? 'aarch64' : 'x86_64'
+ const triple = platform === 'win32'
? `${arch}-pc-windows-msvc`
- : process.platform === 'darwin'
+ : platform === 'darwin'
? `${arch}-apple-darwin`
: `${arch}-unknown-linux-gnu`
return (
@@ -68,30 +82,39 @@ function extractTar(tarPath, destDir) {
// --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 {}
+ // Quarantine flags only exist on a Mac host; elsewhere there is nothing to clear.
+ try { execSync(`xattr -cr "${destDir}"`) } catch { console.warn('xattr -cr failed; Gatekeeper may flag the bundled Python') }
}
}
// ── Main ──────────────────────────────────────────────────────────────────────
async function main() {
+ const target = parseTarget(process.argv.slice(2))
+ const targetKey = `${target.platform}-${target.arch}-${PBS_VERSION}+${PBS_RELEASE}`
+ const markerPath = path.join(EMBED_DIR, '.target')
fs.mkdirSync(RESOURCES_DIR, { recursive: true })
- const pythonExe = process.platform === 'win32'
+ const pythonExe = target.platform === 'win32'
? path.join(EMBED_DIR, 'python.exe')
: path.join(EMBED_DIR, 'bin', 'python3')
+ const presentKey = fs.existsSync(markerPath) ? fs.readFileSync(markerPath, 'utf8').trim() : null
- if (fs.existsSync(pythonExe)) {
- console.log('python-embed already present, skipping.')
+ if (fs.existsSync(pythonExe) && (presentKey === targetKey || presentKey === null && target.platform === process.platform && target.arch === process.arch)) {
+ console.log(`python-embed for ${targetKey} already present, skipping.`)
return
}
+ // A different platform's Python is in place (a Linux build ran before the
+ // Windows one): replace it rather than ship the wrong interpreter.
+ fs.rmSync(EMBED_DIR, { recursive: true, force: true })
- const tarUrl = getPbsUrl()
+ const tarUrl = getPbsUrl(target)
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.')
+ fs.writeFileSync(markerPath, `${targetKey}\n`)
+ console.log(`Done. Python standalone ${targetKey} extracted.`)
}
main().catch((err) => {
diff --git a/apps/forge-desktop/scripts/release-mac.sh b/apps/forge-desktop/scripts/release-mac.sh
new file mode 100755
index 000000000..3a9f017d5
--- /dev/null
+++ b/apps/forge-desktop/scripts/release-mac.sh
@@ -0,0 +1,87 @@
+#!/usr/bin/env bash
+# Build, sign, notarize and publish the macOS half of a three.ws Forge release.
+# Forge ships under the same Apple Developer ID as three.ws Desktop, so it reads
+# the same desktop-* secrets.
+#
+# Runs on a Mac (Xcode command line tools, Node 20+, gcloud signed in to
+# aerial-vehicle-466722-p5). Cloud Build has no macOS workers, and code
+# signing and notarization (notarytool) need Apple's toolchain.
+#
+# bash apps/forge-desktop/scripts/release-mac.sh # build and stage only
+# PUBLISH=1 bash apps/forge-desktop/scripts/release-mac.sh # also publish (owner-gated)
+#
+# Signing comes from Secret Manager when the secrets exist:
+# desktop-macos-csc-link Developer ID Application certificate (.p12, base64)
+# desktop-macos-csc-password its password
+# desktop-apple-api-key App Store Connect API key (.p8 contents) for notarization
+# desktop-apple-api-key-id its key id
+# desktop-apple-api-issuer its issuer id
+# Without them the app is ad-hoc signed and not notarized; /forge-desktop then shows
+# the "Open Anyway" steps. The release merges into the release.json that the
+# Linux and Windows build published, so run it after apps/forge-desktop/cloudbuild.yaml.
+
+set -euo pipefail
+
+PROJECT="${PROJECT:-aerial-vehicle-466722-p5}"
+BUCKET="${BUCKET:-three-ws-desktop-releases}"
+PUBLISH="${PUBLISH:-0}"
+APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+WORK="$(mktemp -d)"
+trap 'rm -rf "$WORK"' EXIT
+
+log() { printf '[release-mac] %s\n' "$*"; }
+die() { printf '[release-mac] error: %s\n' "$*" >&2; exit 1; }
+
+[ "$(uname -s)" = "Darwin" ] || die "run this on macOS; Linux and Windows build on Cloud Build (apps/forge-desktop/cloudbuild.yaml)"
+command -v gcloud >/dev/null || die "gcloud is required (https://cloud.google.com/sdk/docs/install)"
+command -v node >/dev/null || die "Node 20+ is required"
+
+secret() { gcloud secrets versions access latest --secret="$1" --project="$PROJECT" 2>/dev/null; }
+
+export THREE_WS_SIGNED_MAC=0
+if CSC_LINK="$(secret desktop-macos-csc-link)" && CSC_KEY_PASSWORD="$(secret desktop-macos-csc-password)"; then
+ export CSC_LINK CSC_KEY_PASSWORD
+ export THREE_WS_SIGNED_MAC=1
+ log "Developer ID certificate found: signing"
+ if secret desktop-apple-api-key > "$WORK/AuthKey.p8" && APPLE_API_KEY_ID="$(secret desktop-apple-api-key-id)" && APPLE_API_ISSUER="$(secret desktop-apple-api-issuer)"; then
+ export APPLE_API_KEY="$WORK/AuthKey.p8" APPLE_API_KEY_ID APPLE_API_ISSUER
+ log "App Store Connect key found: notarizing"
+ else
+ log "no App Store Connect key: signed but not notarized, Gatekeeper will still warn"
+ fi
+else
+ unset CSC_LINK CSC_KEY_PASSWORD
+ export CSC_IDENTITY_AUTO_DISCOVERY=false
+ log "no Developer ID certificate in Secret Manager: ad-hoc signing (users follow the Open Anyway steps)"
+fi
+
+cd "$APP_DIR"
+VERSION="$(node -p "require('./package.json').version")"
+log "three.ws Forge $VERSION"
+npm ci --no-audit --no-fund
+rm -rf dist
+npm run build
+node scripts/download-python-embed.js --platform darwin --arch arm64
+npx electron-builder --config electron-builder.config.cjs --mac --publish never
+
+if ! gcloud storage cp "gs://$BUCKET/releases/forge/release.json" "$WORK/published.json" 2>/dev/null; then
+ echo '{}' > "$WORK/published.json"
+fi
+node scripts/release-manifest.mjs --merge "$WORK/published.json"
+
+shopt -s nullglob
+BINARIES=(dist/*.dmg dist/*.zip dist/*.blockmap)
+FEED_FILES=(dist/latest-mac.yml dist/release.json)
+STAGE="gs://$BUCKET/staging/forge/$VERSION/mac-$(date +%s)"
+gcloud storage cp "${BINARIES[@]}" "${FEED_FILES[@]}" "$STAGE/"
+log "staged at $STAGE/"
+
+if [ "$PUBLISH" != "1" ]; then
+ log "dry run: the live feed is unchanged. Publish with PUBLISH=1 once the owner approves."
+ exit 0
+fi
+LIVE="gs://$BUCKET/releases/forge"
+gcloud storage cp "${BINARIES[@]}" "$LIVE/" --cache-control="public, max-age=31536000, immutable"
+gcloud storage cp dist/release.json "$LIVE/versions/$VERSION.json" --cache-control="public, max-age=300"
+gcloud storage cp "${FEED_FILES[@]}" "$LIVE/" --cache-control="no-cache, max-age=0"
+log "published macOS $VERSION to https://three.ws/releases/forge/"
diff --git a/apps/forge-desktop/scripts/release-manifest.mjs b/apps/forge-desktop/scripts/release-manifest.mjs
new file mode 100644
index 000000000..d12fc82ff
--- /dev/null
+++ b/apps/forge-desktop/scripts/release-manifest.mjs
@@ -0,0 +1,80 @@
+#!/usr/bin/env node
+// Describe the built artifacts of one three.ws Forge version as release.json,
+// the file https://three.ws/forge-desktop reads to list every download with its
+// size and SHA-256.
+//
+// node apps/forge-desktop/scripts/release-manifest.mjs [--dist dist] [--base-url URL]
+// [--merge path/to/current-release.json] [--out dist/release.json]
+//
+// Classification, hashing and the cross-platform merge are shared with
+// three.ws Desktop (apps/desktop/scripts/release-manifest.mjs), so both apps
+// publish the same release.json shape from the same bucket. Only the product,
+// the feed URL, the OS floors and the release history differ.
+
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describeArtifacts, mergeManifest } from '../../desktop/scripts/release-manifest.mjs';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const APP = resolve(HERE, '..');
+
+export const PRODUCT = 'three.ws Forge';
+export const DEFAULT_BASE_URL = 'https://three.ws/releases/forge';
+
+// Electron 42 supports macOS 12 and later and Windows 10 and later. The mac
+// build is arm64 only because the bundled CPython is per-architecture. Local
+// GPU generation additionally needs an NVIDIA GPU (CUDA) or Apple silicon;
+// cloud generation runs on any of these.
+export const MINIMUM_OS = {
+ mac: 'macOS 12 Monterey or later on Apple silicon',
+ win: 'Windows 10 or 11, 64-bit',
+ linux: '64-bit Ubuntu 20.04+, Debian 11+, Fedora 39+ or another current glibc distribution',
+};
+
+function parseArgs(argv) {
+ const out = { dist: join(APP, 'dist'), baseUrl: process.env.THREE_WS_RELEASE_FEED || DEFAULT_BASE_URL, merge: null, out: null };
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--dist') out.dist = resolve(argv[++i]);
+ else if (a === '--base-url') out.baseUrl = argv[++i];
+ else if (a === '--merge') out.merge = resolve(argv[++i]);
+ else if (a === '--out') out.out = resolve(argv[++i]);
+ else throw new Error(`Unknown argument: ${a}`);
+ }
+ out.out ||= join(out.dist, 'release.json');
+ return out;
+}
+
+async function main() {
+ const args = parseArgs(process.argv.slice(2));
+ const pkg = JSON.parse(readFileSync(join(APP, 'package.json'), 'utf8'));
+ const history = JSON.parse(readFileSync(join(APP, 'releases.json'), 'utf8'));
+ const release = history.releases.find((r) => r.version === pkg.version);
+ if (!release) throw new Error(`${pkg.version} has no entry in apps/forge-desktop/releases.json. Add one (version, date, notes) before building.`);
+ if (!existsSync(args.dist)) throw new Error(`${args.dist} does not exist. Build first (npm run package:<platform>).`);
+ const files = await describeArtifacts(args.dist, {
+ baseUrl: args.baseUrl,
+ signed: { mac: process.env.THREE_WS_SIGNED_MAC === '1', win: process.env.THREE_WS_SIGNED_WIN === '1', linux: false },
+ });
+ if (!files.length) throw new Error(`No release artifacts found in ${args.dist}.`);
+ let previous = null;
+ if (args.merge && existsSync(args.merge)) {
+ try {
+ previous = JSON.parse(readFileSync(args.merge, 'utf8'));
+ } catch {
+ throw new Error(`${args.merge} is not valid JSON`);
+ }
+ }
+ const manifest = mergeManifest({ version: pkg.version, date: release.date, notes: release.notes, files }, previous, { product: PRODUCT, minimumOS: MINIMUM_OS });
+ writeFileSync(args.out, `${JSON.stringify(manifest, null, '\t')}\n`);
+ console.log(`[release-manifest] ${manifest.product} ${manifest.version}: ${manifest.files.length} file(s) -> ${args.out}`);
+ for (const f of manifest.files) console.log(` ${f.platform.padEnd(5)} ${f.kind.padEnd(8)} ${String(f.size).padStart(11)} ${f.sha256} ${f.name}${f.signed ? '' : ' (unsigned)'}`);
+}
+
+if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
+ main().catch((err) => {
+ console.error(`[release-manifest] ${err.message}`);
+ process.exit(1);
+ });
+}
diff --git a/apps/forge-desktop/src/areas/generate/GeneratePage.tsx b/apps/forge-desktop/src/areas/generate/GeneratePage.tsx
index f8ceda333..c9b4ec413 100644
--- a/apps/forge-desktop/src/areas/generate/GeneratePage.tsx
+++ b/apps/forge-desktop/src/areas/generate/GeneratePage.tsx
@@ -7,6 +7,9 @@ import { ColorPicker } from '@shared/components/ui'
import GenerationHUD from './components/GenerationHUD'
import Viewer3D from './components/Viewer3D'
import WorkflowPanel from './components/WorkflowPanel'
+import PublishPopover from './components/PublishPopover'
+import ThreeWsLibraryPopover from './components/ThreeWsLibraryPopover'
+import { canPublishToThreeWs } from './threeWsPublish'
import { getDefaultAssetLibraryService } from './assetLibraryService'
import { buildOrcaSlicerDeepLink, canOpenInOrcaSlicer } from './orcaSlicerLink'
import { resolveAssetLibraryOpenTarget, type ProjectedAssetLibraryEntry } from './assetLibraryProjection'
@@ -715,6 +718,7 @@ export default function GeneratePage(): JSX.Element {
const hasModel = currentJob?.status === 'done' && !!currentJob.outputUrl
const showOpenInSlicer = hasModel && canOpenInOrcaSlicer(currentJob?.outputUrl)
+ const canPublish = hasModel && canPublishToThreeWs(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 →
@@ -800,24 +804,39 @@ export default function GeneratePage(): JSX.Element {
return url
}
+ async function openImportedMesh(filePath: string) {
+ 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)
+ }
+
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)
+ await openImportedMesh(filePath)
+ } finally {
+ setImporting(false)
+ }
+ }
+
+ // A model picked from the three.ws library was downloaded by the main
+ // process; it opens exactly like a mesh imported from disk.
+ async function handleImportFromThreeWs(filePath: string) {
+ setImporting(true)
+ try {
+ await openImportedMesh(filePath)
} finally {
setImporting(false)
}
@@ -1036,8 +1055,27 @@ export default function GeneratePage(): JSX.Element {
<p className="text-[10px] text-zinc-500">.glb .obj .stl .ply .splat</p>
</div>
</button>
+ <button
+ onClick={() => setOpenPanel('threewsLibrary')}
+ 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 2l8.66 5v10L12 22l-8.66-5V7L12 2z" />
+ <path d="M12 22V12M12 12l8.66-5M12 12L3.34 7" />
+ </svg>
+ <div>
+ <p className="text-xs text-zinc-200">three.ws library</p>
+ <p className="text-[10px] text-zinc-500">Free CC0 models</p>
+ </div>
+ </button>
</div>
)}
+ {openPanel === 'threewsLibrary' && (
+ <ThreeWsLibraryPopover
+ onImport={(filePath) => handleImportFromThreeWs(filePath)}
+ onClose={() => setOpenPanel(null)}
+ />
+ )}
</div>
<div className="relative">
@@ -1107,6 +1145,35 @@ export default function GeneratePage(): JSX.Element {
)}
</div>
+ {/* Publish to three.ws */}
+ {canPublish && currentJob?.outputUrl && (
+ <div className="relative">
+ <button
+ onClick={() => setOpenPanel((p) => (p === 'publish' ? null : 'publish'))}
+ title="Save this model to your three.ws account"
+ className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-medium border transition-colors
+ ${openPanel === 'publish'
+ ? 'bg-accent/25 border-accent/50 text-accent-light'
+ : 'bg-accent/10 border-accent/30 text-accent-light hover:bg-accent/20 hover:border-accent/50'
+ }`}
+ >
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75">
+ <path d="M12 2l8.66 5v10L12 22l-8.66-5V7L12 2z" />
+ <polyline points="8.5 11 12 7.5 15.5 11" />
+ <line x1="12" y1="7.5" x2="12" y2="16" />
+ </svg>
+ Publish
+ </button>
+ {openPanel === 'publish' && (
+ <PublishPopover
+ key={currentJob.outputUrl}
+ outputUrl={currentJob.outputUrl}
+ onClose={() => setOpenPanel(null)}
+ />
+ )}
+ </div>
+ )}
+
{/* Smooth */}
<div className="relative">
<button
diff --git a/apps/forge-desktop/src/areas/generate/assetLibraryUi.ts b/apps/forge-desktop/src/areas/generate/assetLibraryUi.ts
index 5e83e65a8..46b1f49f0 100644
--- a/apps/forge-desktop/src/areas/generate/assetLibraryUi.ts
+++ b/apps/forge-desktop/src/areas/generate/assetLibraryUi.ts
@@ -2,7 +2,7 @@ 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 GenerateOpenPanel = 'export' | 'publish' | 'decimate' | 'smooth' | 'import' | 'library' | 'threewsLibrary' | 'light' | null
export type AssetLibrarySortMode = 'type' | 'name' | 'date'
export interface AssetLibraryEntryGroup {
diff --git a/apps/forge-desktop/src/areas/generate/components/PublishPopover.tsx b/apps/forge-desktop/src/areas/generate/components/PublishPopover.tsx
new file mode 100644
index 000000000..8a8de5c86
--- /dev/null
+++ b/apps/forge-desktop/src/areas/generate/components/PublishPopover.tsx
@@ -0,0 +1,250 @@
+import { useEffect, useRef, useState } from 'react'
+import { useThreeWsStore } from '@shared/stores/threeWsStore'
+import { AVATAR_VISIBILITIES, type AvatarVisibility, type PublishResult } from '@shared/types/threeWs'
+import { defaultPublishName, parseTags } from '../threeWsPublish'
+
+// Publish the open model to the signed-in three.ws account. It lands in the
+// account's library at three.ws/avatars/<id>, where it can be shared, embedded,
+// rigged or used as an agent body.
+
+const VISIBILITY_HINT: Record<AvatarVisibility, string> = {
+ private: 'Only you can see it.',
+ unlisted: 'Anyone with the link can see it.',
+ public: 'Listed on your profile and in search.',
+}
+
+function SignInPrompt(): JSX.Element {
+ const link = useThreeWsStore((s) => s.link)
+ const startLink = useThreeWsStore((s) => s.startLink)
+ const cancelLink = useThreeWsStore((s) => s.cancelLink)
+
+ if (link.status === 'waiting') {
+ return (
+ <div className="flex flex-col gap-2">
+ <p className="text-[11px] text-zinc-400">Approve Forge in your browser. The page should show this code:</p>
+ <p className="font-mono text-lg tracking-[0.25em] text-zinc-100 select-all">{link.link.userCode}</p>
+ <div className="flex items-center gap-3 text-[11px]">
+ <span className="inline-flex items-center gap-1.5 text-zinc-500">
+ <span className="w-1.5 h-1.5 rounded-full bg-accent animate-pulse" />
+ Waiting for approval
+ </span>
+ <button type="button" onClick={() => window.electron.threews.open(link.link.verificationUrl)} className="text-accent-light hover:underline">
+ Open again
+ </button>
+ <button type="button" onClick={() => void cancelLink()} className="text-zinc-500 hover:text-zinc-300">Cancel</button>
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div className="flex flex-col gap-2.5">
+ <p className="text-[11px] text-zinc-400 leading-relaxed">
+ Sign in to save this model to your three.ws account, where you can share it, embed it, or give it to an agent.
+ </p>
+ <button
+ type="button"
+ onClick={() => void startLink()}
+ disabled={link.status === 'starting'}
+ className="self-start px-3 py-1.5 rounded-lg bg-accent hover:bg-accent-dark text-white text-xs font-semibold transition-colors disabled:opacity-60 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent-light"
+ >
+ {link.status === 'starting' ? 'Opening three.ws…' : 'Sign in to three.ws'}
+ </button>
+ </div>
+ )
+}
+
+function Published({ result, onAnother }: { result: PublishResult; onAnother: () => void }): JSX.Element {
+ const [copied, setCopied] = useState(false)
+
+ async function copy(): Promise<void> {
+ await navigator.clipboard.writeText(result.url)
+ setCopied(true)
+ setTimeout(() => setCopied(false), 1500)
+ }
+
+ return (
+ <div className="flex flex-col gap-3" role="status">
+ <div className="flex items-start gap-2.5">
+ <span className="mt-0.5 w-5 h-5 rounded-full bg-emerald-500/15 text-emerald-400 flex items-center justify-center shrink-0">
+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round"><polyline points="20 6 9 17 4 12" /></svg>
+ </span>
+ <div className="min-w-0">
+ <p className="text-xs font-semibold text-zinc-100 truncate">{result.name}</p>
+ <p className="text-[11px] text-zinc-500 capitalize">Published, {result.visibility}</p>
+ </div>
+ </div>
+ <div className="flex items-center gap-1.5 px-2 py-1.5 rounded-lg bg-zinc-800/80 border border-zinc-700/50">
+ <span className="flex-1 min-w-0 truncate text-[11px] font-mono text-zinc-400">{result.url}</span>
+ <button type="button" onClick={() => void copy()} className="shrink-0 text-[11px] text-zinc-400 hover:text-zinc-100 transition-colors">
+ {copied ? 'Copied' : 'Copy'}
+ </button>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => window.electron.threews.open(result.url)}
+ className="px-3 py-1.5 rounded-lg bg-accent hover:bg-accent-dark text-white text-xs font-semibold transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-accent-light"
+ >
+ Open on three.ws
+ </button>
+ <button type="button" onClick={onAnother} className="px-3 py-1.5 rounded-lg text-xs text-zinc-400 hover:text-zinc-200 transition-colors">
+ Publish again
+ </button>
+ </div>
+ </div>
+ )
+}
+
+export default function PublishPopover({ outputUrl, onClose }: { outputUrl: string; onClose: () => void }): JSX.Element {
+ const account = useThreeWsStore((s) => s.account)
+ const accountError = useThreeWsStore((s) => s.error)
+ const refresh = useThreeWsStore((s) => s.refresh)
+ const [name, setName] = useState(() => defaultPublishName(outputUrl))
+ const [description, setDescription] = useState('')
+ const [tags, setTags] = useState('')
+ const [visibility, setVisibility] = useState<AvatarVisibility>('unlisted')
+ const [publishing, setPublishing] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+ const [result, setResult] = useState<PublishResult | null>(null)
+ const nameRef = useRef<HTMLInputElement>(null)
+
+ useEffect(() => { if (!account) void refresh() }, [account, refresh])
+ useEffect(() => { if (account?.signedIn) nameRef.current?.select() }, [account?.signedIn])
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent): void => { if (e.key === 'Escape' && !publishing) onClose() }
+ window.addEventListener('keydown', onKey)
+ return () => window.removeEventListener('keydown', onKey)
+ }, [onClose, publishing])
+
+ async function publish(): Promise<void> {
+ if (!name.trim() || publishing) return
+ setPublishing(true)
+ setError(null)
+ const res = await window.electron.threews.publish({
+ outputUrl,
+ name: name.trim(),
+ description: description.trim() || undefined,
+ visibility,
+ tags: parseTags(tags),
+ })
+ setPublishing(false)
+ if (res.ok) setResult(res.value)
+ else {
+ setError(res.error)
+ // A revoked key signs Forge out in the main process; show the prompt.
+ if (res.code === 'signed_out' || res.code === 'unauthorized') void refresh()
+ }
+ }
+
+ return (
+ <div
+ role="dialog"
+ aria-label="Publish to three.ws"
+ className="absolute top-full left-0 mt-1 z-50 w-80 bg-zinc-900 border border-zinc-700/60 rounded-xl p-3.5 shadow-xl flex flex-col gap-3"
+ >
+ <div className="flex items-center justify-between">
+ <p className="text-xs font-semibold text-zinc-100">Publish to three.ws</p>
+ {account?.signedIn && (
+ <span className="text-[10px] text-zinc-500 truncate max-w-[140px]" title={account.email ?? undefined}>
+ {account.username ? `@${account.username}` : account.email ?? 'Signed in'}
+ </span>
+ )}
+ </div>
+
+ {account === null ? (
+ accountError ? (
+ <div role="alert" className="flex items-center justify-between gap-3 text-[11px] text-red-300">
+ <span>{accountError}</span>
+ <button type="button" onClick={() => void refresh()} className="shrink-0 hover:underline">Retry</button>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-2" aria-busy="true">
+ <div className="h-3 w-3/4 rounded bg-zinc-800 animate-pulse" />
+ <div className="h-7 w-32 rounded-lg bg-zinc-800 animate-pulse" />
+ </div>
+ )
+ ) : !account.signedIn ? (
+ <SignInPrompt />
+ ) : result ? (
+ <Published result={result} onAnother={() => setResult(null)} />
+ ) : (
+ <form
+ className="flex flex-col gap-2.5"
+ onSubmit={(e) => { e.preventDefault(); void publish() }}
+ >
+ <label className="flex flex-col gap-1">
+ <span className="text-[10px] font-medium text-zinc-500 uppercase tracking-wider">Name</span>
+ <input
+ ref={nameRef}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ maxLength={100}
+ required
+ className="px-2.5 py-1.5 rounded-lg bg-zinc-800 border border-zinc-700/60 text-xs text-zinc-100 focus:outline-none focus:border-zinc-500 transition-colors"
+ />
+ </label>
+ <label className="flex flex-col gap-1">
+ <span className="text-[10px] font-medium text-zinc-500 uppercase tracking-wider">Description</span>
+ <textarea
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ maxLength={500}
+ rows={2}
+ placeholder="Optional"
+ className="px-2.5 py-1.5 rounded-lg bg-zinc-800 border border-zinc-700/60 text-xs text-zinc-100 placeholder:text-zinc-600 resize-none focus:outline-none focus:border-zinc-500 transition-colors"
+ />
+ </label>
+ <label className="flex flex-col gap-1">
+ <span className="text-[10px] font-medium text-zinc-500 uppercase tracking-wider">Tags</span>
+ <input
+ value={tags}
+ onChange={(e) => setTags(e.target.value)}
+ placeholder="chair, furniture"
+ className="px-2.5 py-1.5 rounded-lg bg-zinc-800 border border-zinc-700/60 text-xs text-zinc-100 placeholder:text-zinc-600 focus:outline-none focus:border-zinc-500 transition-colors"
+ />
+ </label>
+ <fieldset className="flex flex-col gap-1">
+ <legend className="text-[10px] font-medium text-zinc-500 uppercase tracking-wider mb-1">Visibility</legend>
+ <div className="grid grid-cols-3 gap-1 p-0.5 rounded-lg bg-zinc-800 border border-zinc-700/60">
+ {AVATAR_VISIBILITIES.map((v) => (
+ <button
+ key={v}
+ type="button"
+ aria-pressed={visibility === v}
+ onClick={() => setVisibility(v)}
+ className={`py-1 rounded-md text-[11px] capitalize transition-colors focus:outline-none focus-visible:ring-1 focus-visible:ring-accent-light ${
+ visibility === v ? 'bg-zinc-600 text-zinc-100' : 'text-zinc-400 hover:text-zinc-200'
+ }`}
+ >
+ {v}
+ </button>
+ ))}
+ </div>
+ <p className="text-[10px] text-zinc-500">{VISIBILITY_HINT[visibility]}</p>
+ </fieldset>
+
+ {error && <p role="alert" className="text-[11px] text-red-300 leading-relaxed">{error}</p>}
+
+ <div className="flex items-center gap-2 pt-0.5">
+ <button
+ type="submit"
+ disabled={publishing || !name.trim()}
+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-accent hover:bg-accent-dark text-white text-xs font-semibold transition-colors disabled:opacity-60 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent-light"
+ >
+ {publishing && (
+ <svg className="animate-spin" width="12" height="12" 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>
+ )}
+ {publishing ? 'Uploading…' : error ? 'Try again' : 'Publish'}
+ </button>
+ <button type="button" onClick={onClose} disabled={publishing} className="px-3 py-1.5 rounded-lg text-xs text-zinc-400 hover:text-zinc-200 transition-colors disabled:opacity-50">
+ Cancel
+ </button>
+ </div>
+ </form>
+ )}
+ </div>
+ )
+}
diff --git a/apps/forge-desktop/src/areas/generate/components/ThreeWsLibraryPopover.tsx b/apps/forge-desktop/src/areas/generate/components/ThreeWsLibraryPopover.tsx
new file mode 100644
index 000000000..e130c0fcf
--- /dev/null
+++ b/apps/forge-desktop/src/areas/generate/components/ThreeWsLibraryPopover.tsx
@@ -0,0 +1,214 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import type { LibraryObject } from '@shared/types/threeWs'
+
+// The three.ws CC0 object library: free, public-domain models
+// (the same catalog behind three.ws/objects) to drop into the viewer as a
+// starting point, a reference, or a workflow input. No account needed.
+
+const PAGE_SIZE = 36
+const SEARCH_DEBOUNCE_MS = 300
+
+function formatBytes(bytes: number | null): string {
+ if (!bytes) return ''
+ if (bytes < 1024 * 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
+}
+
+function Thumb({ object }: { object: LibraryObject }): JSX.Element {
+ const [failed, setFailed] = useState(false)
+ if (!object.thumb || failed) {
+ return (
+ <div className="w-full h-full flex items-center justify-center text-zinc-600">
+ <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
+ <path d="M12 2l8.66 5v10L12 22l-8.66-5V7L12 2z" />
+ <path d="M12 22V12M12 12l8.66-5M12 12L3.34 7" />
+ </svg>
+ </div>
+ )
+ }
+ return <img src={object.thumb} alt="" loading="lazy" onError={() => setFailed(true)} className="w-full h-full object-contain" />
+}
+
+export default function ThreeWsLibraryPopover({
+ onImport,
+ onClose,
+}: {
+ /** Imports the downloaded .glb into the viewer; rejects with a readable error. */
+ onImport: (filePath: string, object: LibraryObject) => Promise<void>
+ onClose: () => void
+}): JSX.Element {
+ const [query, setQuery] = useState('')
+ const [objects, setObjects] = useState<LibraryObject[]>([])
+ const [total, setTotal] = useState(0)
+ const [loading, setLoading] = useState(true)
+ const [loadingMore, setLoadingMore] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+ const [importingUrl, setImportingUrl] = useState<string | null>(null)
+ const requestId = useRef(0)
+ const searchRef = useRef<HTMLInputElement>(null)
+
+ const load = useCallback(async (q: string) => {
+ const id = ++requestId.current
+ setLoading(true)
+ setError(null)
+ const res = q.trim()
+ ? await window.electron.threews.librarySearch({ q: q.trim(), limit: PAGE_SIZE * 2 })
+ : await window.electron.threews.libraryList({ offset: 0, limit: PAGE_SIZE })
+ if (id !== requestId.current) return
+ setLoading(false)
+ if (res.ok) {
+ setObjects(res.value.objects)
+ setTotal(res.value.total)
+ } else {
+ setObjects([])
+ setTotal(0)
+ setError(res.error)
+ }
+ }, [])
+
+ useEffect(() => {
+ const id = setTimeout(() => void load(query), query ? SEARCH_DEBOUNCE_MS : 0)
+ return () => clearTimeout(id)
+ }, [query, load])
+
+ useEffect(() => { searchRef.current?.focus() }, [])
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent): void => { if (e.key === 'Escape' && !importingUrl) onClose() }
+ window.addEventListener('keydown', onKey)
+ return () => window.removeEventListener('keydown', onKey)
+ }, [onClose, importingUrl])
+
+ async function loadMore(): Promise<void> {
+ const id = requestId.current
+ setLoadingMore(true)
+ const res = await window.electron.threews.libraryList({ offset: objects.length, limit: PAGE_SIZE })
+ if (id !== requestId.current) return
+ setLoadingMore(false)
+ if (res.ok) {
+ const seen = new Set(objects.map((o) => o.url))
+ setObjects([...objects, ...res.value.objects.filter((o) => !seen.has(o.url))])
+ setTotal(res.value.total)
+ } else {
+ setError(res.error)
+ }
+ }
+
+ async function pick(object: LibraryObject): Promise<void> {
+ if (importingUrl) return
+ setImportingUrl(object.url)
+ setError(null)
+ const res = await window.electron.threews.libraryDownload({ url: object.url, name: object.name })
+ if (!res.ok) {
+ setImportingUrl(null)
+ setError(res.error)
+ return
+ }
+ try {
+ await onImport(res.value, object)
+ onClose()
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Could not open the model.')
+ } finally {
+ setImportingUrl(null)
+ }
+ }
+
+ const searching = query.trim().length > 0
+ const canLoadMore = !searching && !loading && objects.length < total
+
+ return (
+ <div
+ role="dialog"
+ aria-label="three.ws object library"
+ className="absolute top-full left-0 mt-1 z-50 w-[420px] max-h-[70vh] bg-zinc-900 border border-zinc-700/60 rounded-xl shadow-xl flex flex-col overflow-hidden"
+ >
+ <div className="p-3 border-b border-zinc-800 flex flex-col gap-2">
+ <div className="flex items-center justify-between">
+ <p className="text-xs font-semibold text-zinc-100">three.ws library</p>
+ <span className="text-[10px] text-zinc-500">
+ {loading ? 'Loading…' : searching ? `${objects.length} match${objects.length === 1 ? '' : 'es'}` : `${total.toLocaleString()} free CC0 models`}
+ </span>
+ </div>
+ <input
+ ref={searchRef}
+ type="search"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Search chairs, trees, cars…"
+ aria-label="Search the library"
+ className="px-2.5 py-1.5 rounded-lg bg-zinc-800 border border-zinc-700/60 text-xs text-zinc-100 placeholder:text-zinc-600 focus:outline-none focus:border-zinc-500 transition-colors"
+ />
+ </div>
+
+ {error && (
+ <div role="alert" className="mx-3 mt-3 px-3 py-2 rounded-lg bg-red-500/10 border border-red-500/20 text-[11px] text-red-300 flex items-center justify-between gap-3">
+ <span>{error}</span>
+ <button type="button" onClick={() => void load(query)} className="shrink-0 text-red-200 hover:underline">Retry</button>
+ </div>
+ )}
+
+ <div className="flex-1 overflow-y-auto p-3">
+ {loading ? (
+ <div className="grid grid-cols-3 gap-2" aria-busy="true">
+ {Array.from({ length: 9 }, (_, i) => (
+ <div key={i} className="aspect-square rounded-lg bg-zinc-800/80 animate-pulse" />
+ ))}
+ </div>
+ ) : objects.length === 0 && !error ? (
+ <div className="py-10 text-center">
+ <p className="text-xs text-zinc-300">Nothing matches “{query.trim()}”.</p>
+ <p className="text-[11px] text-zinc-500 mt-1">Try a broader word, like “chair” instead of “office chair”.</p>
+ <button type="button" onClick={() => setQuery('')} className="mt-3 text-[11px] text-accent-light hover:underline">Browse everything</button>
+ </div>
+ ) : (
+ <>
+ <div className="grid grid-cols-3 gap-2">
+ {objects.map((o) => {
+ const busy = importingUrl === o.url
+ return (
+ <button
+ key={o.url}
+ type="button"
+ onClick={() => void pick(o)}
+ disabled={!!importingUrl}
+ title={`${o.label}${o.bytes ? `, ${formatBytes(o.bytes)}` : ''}\n${o.license}${o.source ? `, ${o.source}` : ''}`}
+ className="group relative flex flex-col rounded-lg bg-zinc-800/60 border border-zinc-700/40 overflow-hidden text-left transition-colors hover:border-accent/60 hover:bg-zinc-800 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent-light disabled:cursor-wait"
+ >
+ <div className={`aspect-square bg-zinc-900/60 transition-opacity ${importingUrl && !busy ? 'opacity-40' : ''}`}>
+ <Thumb object={o} />
+ </div>
+ <div className="px-1.5 py-1">
+ <p className="text-[10px] text-zinc-300 truncate">{o.label}</p>
+ </div>
+ {busy && (
+ <div className="absolute inset-0 flex items-center justify-center bg-zinc-900/70">
+ <svg className="animate-spin text-accent-light" width="18" height="18" 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>
+ )}
+ </button>
+ )
+ })}
+ </div>
+ {canLoadMore && (
+ <button
+ type="button"
+ onClick={() => void loadMore()}
+ disabled={loadingMore}
+ className="mt-3 w-full py-1.5 rounded-lg bg-zinc-800 hover:bg-zinc-700 text-[11px] text-zinc-300 transition-colors disabled:opacity-60"
+ >
+ {loadingMore ? 'Loading…' : `Load more (${(total - objects.length).toLocaleString()} left)`}
+ </button>
+ )}
+ </>
+ )}
+ </div>
+
+ <div className="px-3 py-2 border-t border-zinc-800 flex items-center justify-between text-[10px] text-zinc-500">
+ <span>Public domain (CC0). Free to use, remix and sell.</span>
+ <button type="button" onClick={() => window.electron.threews.open('/objects')} className="hover:text-zinc-300">three.ws/objects</button>
+ </div>
+ </div>
+ )
+}
diff --git a/apps/forge-desktop/src/areas/generate/threeWsPublish.test.ts b/apps/forge-desktop/src/areas/generate/threeWsPublish.test.ts
new file mode 100644
index 000000000..849f5a58b
--- /dev/null
+++ b/apps/forge-desktop/src/areas/generate/threeWsPublish.test.ts
@@ -0,0 +1,27 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { canPublishToThreeWs, defaultPublishName, parseTags } from './threeWsPublish'
+
+test('workspace and imported GLB meshes are publishable', () => {
+ assert.equal(canPublishToThreeWs('/workspace/Default/chair.glb'), true)
+ assert.equal(canPublishToThreeWs(`/optimize/serve-file?path=${encodeURIComponent('/home/me/Models/Lamp.GLB')}`), true)
+})
+
+test('splats and missing outputs are not publishable', () => {
+ assert.equal(canPublishToThreeWs(undefined), false)
+ assert.equal(canPublishToThreeWs('/workspace/Default/scan.ply'), false)
+ assert.equal(canPublishToThreeWs(`/optimize/serve-file?path=${encodeURIComponent('/tmp/forge_import_1/splat.splat')}`), false)
+})
+
+test('default names drop Forge suffixes and ids', () => {
+ assert.equal(defaultPublishName('/workspace/Default/red_chair_opt20000.glb'), 'Red chair')
+ assert.equal(defaultPublishName('/workspace/Default/lamp_smooth3_xf_1a2b3c4d.glb'), 'Lamp')
+ assert.equal(defaultPublishName(`/optimize/serve-file?path=${encodeURIComponent('/tmp/forge_import_x/mesh.glb')}`), 'Forge model')
+ assert.equal(defaultPublishName('/workspace/Default/3f9a1c2e4b5d6a7f.glb'), 'Forge model')
+ assert.equal(defaultPublishName(undefined), 'Forge model')
+})
+
+test('tags parse from a comma list', () => {
+ assert.deepEqual(parseTags(' chair, furniture ,,wood '), ['chair', 'furniture', 'wood'])
+ assert.deepEqual(parseTags(''), [])
+})
diff --git a/apps/forge-desktop/src/areas/generate/threeWsPublish.ts b/apps/forge-desktop/src/areas/generate/threeWsPublish.ts
new file mode 100644
index 000000000..1dccaa3ac
--- /dev/null
+++ b/apps/forge-desktop/src/areas/generate/threeWsPublish.ts
@@ -0,0 +1,45 @@
+// Pure helpers for publishing the open model to three.ws, kept out of the
+// component so they run under node --test.
+
+const SERVE_FILE_PREFIX = '/optimize/serve-file?path='
+
+/** The file path an output URL points at: a workspace path or an imported file. */
+function sourcePath(outputUrl: string): string {
+ if (outputUrl.startsWith('/workspace/')) return outputUrl.slice('/workspace/'.length)
+ if (outputUrl.startsWith(SERVE_FILE_PREFIX)) return decodeURIComponent(outputUrl.slice(SERVE_FILE_PREFIX.length))
+ return outputUrl.split('?')[0]
+}
+
+/**
+ * Whether the open model can be published. three.ws stores GLB models; every
+ * mesh Forge shows is served as GLB (imports are converted on the way in),
+ * while Gaussian splats stay .splat/.ply and have no GLB form.
+ */
+export function canPublishToThreeWs(outputUrl: string | undefined): boolean {
+ if (!outputUrl) return false
+ return /\.glb$/i.test(sourcePath(outputUrl))
+}
+
+/**
+ * A readable default name from the model's file: "chair_opt20000.glb" becomes
+ * "Chair". Forge's own suffixes (_opt, _smooth, _xf_) and generated ids are
+ * dropped; anything left empty falls back to "Forge model".
+ */
+export function defaultPublishName(outputUrl: string | undefined): string {
+ if (!outputUrl) return 'Forge model'
+ const file = sourcePath(outputUrl).split(/[\\/]/).pop() ?? ''
+ const stem = file
+ .replace(/\.[a-z0-9]+$/i, '')
+ .replace(/_(opt\d+|smooth\d+|xf_[0-9a-f]+)/gi, '')
+ .replace(/[-_]+/g, ' ')
+ .replace(/\b[0-9a-f]{8,}\b/gi, '')
+ .replace(/\s+/g, ' ')
+ .trim()
+ if (!stem || /^(mesh|model|output|result)$/i.test(stem)) return 'Forge model'
+ return stem.charAt(0).toUpperCase() + stem.slice(1)
+}
+
+/** "a, b ,,c" to ["a", "b", "c"]: the tags field is a comma list. */
+export function parseTags(text: string): string[] {
+ return text.split(',').map((t) => t.trim()).filter(Boolean)
+}
diff --git a/apps/forge-desktop/src/areas/settings/SettingsPage.tsx b/apps/forge-desktop/src/areas/settings/SettingsPage.tsx
index d81999404..339d21b2e 100644
--- a/apps/forge-desktop/src/areas/settings/SettingsPage.tsx
+++ b/apps/forge-desktop/src/areas/settings/SettingsPage.tsx
@@ -6,8 +6,9 @@ import { IntegrationsSection } from './components/IntegrationsSection'
import { AgentSection } from './components/AgentSection'
import { ApplicationSection } from './components/ApplicationSection'
import { AccessibilitySection } from './components/AccessibilitySection'
+import { ThreeWsSection } from './components/ThreeWsSection'
-type Section = 'application' | 'storage' | 'integrations' | 'accessibility' | 'agent' | 'logs' | 'about'
+type Section = 'application' | 'threews' | 'storage' | 'integrations' | 'accessibility' | 'agent' | 'logs' | 'about'
const SECTIONS: { id: Section; label: string; icon: JSX.Element }[] = [
{
@@ -21,6 +22,16 @@ const SECTIONS: { id: Section; label: string; icon: JSX.Element }[] = [
</svg>
)
},
+ {
+ id: 'threews',
+ label: 'three.ws',
+ icon: (
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
+ <path d="M12 2l8.66 5v10L12 22l-8.66-5V7L12 2z" />
+ <path d="M12 22V12M12 12l8.66-5M12 12L3.34 7" />
+ </svg>
+ )
+ },
{
id: 'storage',
label: 'Storage',
@@ -122,6 +133,7 @@ export default function SettingsPage(): JSX.Element {
<div className="flex-1 overflow-y-auto bg-surface-400">
<div className="p-8">
{section === 'application' && <ApplicationSection />}
+ {section === 'threews' && <ThreeWsSection />}
{section === 'storage' && <StorageSection />}
{section === 'integrations' && <IntegrationsSection />}
{section === 'accessibility' && <AccessibilitySection />}
diff --git a/apps/forge-desktop/src/areas/settings/components/AboutSection.tsx b/apps/forge-desktop/src/areas/settings/components/AboutSection.tsx
index 40746ce16..0997dbd36 100644
--- a/apps/forge-desktop/src/areas/settings/components/AboutSection.tsx
+++ b/apps/forge-desktop/src/areas/settings/components/AboutSection.tsx
@@ -13,23 +13,32 @@ export function AboutSection(): JSX.Element {
<div className="grid grid-cols-2 gap-4">
<Card>
- <Row label="three.ws Forge" description="Local 3D mesh generation app.">
+ <Row label="three.ws Forge" description="3D generation on your machine or the three.ws cloud.">
<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 label="Documentation" description="Guides, extensions and the local API.">
+ <LinkButton label="Open" href="https://three.ws/docs/forge-desktop" />
</Row>
- <Row label="GitHub" description="Source code and issues.">
- <LinkButton label="Open" href="https://github.com/lightningpixel/modly" />
+ <Row label="Downloads" description="Every release for macOS, Windows and Linux.">
+ <LinkButton label="Open" href="https://three.ws/forge-desktop" />
+ </Row>
+ <Row label="Source code" description="Source and issues for three.ws Forge.">
+ <LinkButton label="Open" href="https://github.com/nirholas/three.ws/tree/main/apps/forge-desktop" />
</Row>
</Card>
<Card>
- <Row label="Discord" description="Community support.">
- <LinkButton label="Join" href="https://discord.gg/FjzjRgweVk" />
+ <Row label="Telegram" description="Community, release notes and support.">
+ <LinkButton label="Join" href="https://t.me/three_ws" />
+ </Row>
+ <Row label="X" description="Follow @trythreews for updates.">
+ <LinkButton label="Follow" href="https://x.com/trythreews" />
+ </Row>
+ <Row label="Based on Modly" description="Built on the MIT-licensed Modly by Lightning Pixel.">
+ <LinkButton label="View" href="https://github.com/lightningpixel/modly" />
</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 label="Licenses" description="MIT license and third-party notices.">
+ <LinkButton label="View" href="https://github.com/nirholas/three.ws/blob/main/apps/forge-desktop/NOTICE" />
</Row>
</Card>
diff --git a/apps/forge-desktop/src/areas/settings/components/ThreeWsSection.tsx b/apps/forge-desktop/src/areas/settings/components/ThreeWsSection.tsx
new file mode 100644
index 000000000..c08b9d52d
--- /dev/null
+++ b/apps/forge-desktop/src/areas/settings/components/ThreeWsSection.tsx
@@ -0,0 +1,273 @@
+import { useEffect, useState } from 'react'
+import { Section, Card, Row } from '@shared/ui'
+import { useThreeWsStore } from '@shared/stores/threeWsStore'
+
+// Settings → three.ws: connect Forge to a three.ws account. Browser sign-in uses
+// the same device flow as the three-ws CLI, so nothing is typed into Forge; a
+// pasted API key is the alternative for headless or managed machines.
+
+function useCountdown(startedAt: number, seconds: number): number {
+ const [now, setNow] = useState(Date.now())
+ useEffect(() => {
+ const id = setInterval(() => setNow(Date.now()), 1000)
+ return () => clearInterval(id)
+ }, [])
+ return Math.max(0, Math.round(seconds - (now - startedAt) / 1000))
+}
+
+function formatRemaining(seconds: number): string {
+ const m = Math.floor(seconds / 60)
+ const s = seconds % 60
+ return `${m}:${String(s).padStart(2, '0')}`
+}
+
+function WaitingForApproval(): JSX.Element | null {
+ const link = useThreeWsStore((s) => s.link)
+ const cancelLink = useThreeWsStore((s) => s.cancelLink)
+ const startedAt = link.status === 'waiting' ? link.startedAt : Date.now()
+ const expiresIn = link.status === 'waiting' ? link.link.expiresIn : 0
+ const remaining = useCountdown(startedAt, expiresIn)
+ if (link.status !== 'waiting') return null
+
+ return (
+ <div className="px-4 py-4 flex flex-col gap-3">
+ <p className="text-[11px] text-zinc-400">
+ Your browser opened three.ws. Check that it shows this code, then approve:
+ </p>
+ <p className="font-mono text-2xl tracking-[0.3em] text-zinc-100 select-all" aria-label="Sign-in code">
+ {link.link.userCode}
+ </p>
+ <div className="flex items-center gap-3 text-[11px] text-zinc-500">
+ <span className="inline-flex items-center gap-1.5">
+ <span className="w-1.5 h-1.5 rounded-full bg-accent animate-pulse" />
+ Waiting for approval, expires in {formatRemaining(remaining)}
+ </span>
+ <button
+ type="button"
+ onClick={() => window.electron.threews.open(link.link.verificationUrl)}
+ className="text-accent-light hover:underline focus:outline-none focus-visible:underline"
+ >
+ Open the page again
+ </button>
+ <button
+ type="button"
+ onClick={() => void cancelLink()}
+ className="text-zinc-500 hover:text-zinc-300 focus:outline-none focus-visible:text-zinc-300"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ )
+}
+
+function SignedOut(): JSX.Element {
+ const link = useThreeWsStore((s) => s.link)
+ const loading = useThreeWsStore((s) => s.loading)
+ const startLink = useThreeWsStore((s) => s.startLink)
+ const signInWithKey = useThreeWsStore((s) => s.signInWithKey)
+ const [key, setKey] = useState('')
+ const [visible, setVisible] = useState(false)
+
+ async function submitKey(): Promise<void> {
+ if (!key.trim()) return
+ if (await signInWithKey(key.trim())) setKey('')
+ }
+
+ return (
+ <div className="grid grid-cols-2 gap-4">
+ <Card
+ title="Sign in with your browser"
+ description="Recommended. Approve Forge on three.ws and it receives its own API key, which you can revoke at any time from your dashboard."
+ >
+ {link.status === 'waiting' ? (
+ <WaitingForApproval />
+ ) : (
+ <div className="px-4 py-4">
+ <button
+ type="button"
+ onClick={() => void startLink()}
+ disabled={link.status === 'starting'}
+ className="px-4 py-2 rounded-lg bg-accent hover:bg-accent-dark text-white text-xs font-semibold transition-colors disabled:opacity-60 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent-light"
+ >
+ {link.status === 'starting' ? 'Opening three.ws…' : 'Sign in to three.ws'}
+ </button>
+ </div>
+ )}
+ </Card>
+
+ <Card
+ title="Use an API key"
+ description={
+ <>
+ For managed machines. Create a key at{' '}
+ <button
+ type="button"
+ onClick={() => window.electron.threews.open('/dashboard/developers')}
+ className="text-accent-light hover:underline"
+ >
+ three.ws/dashboard/developers
+ </button>{' '}
+ with the avatars:write scope.
+ </>
+ }
+ >
+ <Row label="API key" description="Stored encrypted on this machine.">
+ <div className="flex items-center gap-2">
+ <div className="relative">
+ <input
+ type={visible ? 'text' : 'password'}
+ value={key}
+ onChange={(e) => setKey(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && void submitKey()}
+ placeholder="sk_live_…"
+ spellCheck={false}
+ aria-label="three.ws API key"
+ className="w-52 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 key' : 'Show key'}
+ aria-label={visible ? 'Hide key' : 'Show key'}
+ className="absolute right-2 top-1/2 -translate-y-1/2 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">
+ <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>
+ <button
+ type="button"
+ onClick={() => void submitKey()}
+ disabled={loading || !key.trim()}
+ className="shrink-0 px-3 py-1.5 rounded-lg text-xs font-semibold bg-accent/15 hover:bg-accent/25 text-accent-light transition-colors disabled:opacity-50 focus:outline-none focus-visible:ring-1 focus-visible:ring-accent-light"
+ >
+ {loading ? 'Checking…' : 'Connect'}
+ </button>
+ </div>
+ </Row>
+ </Card>
+ </div>
+ )
+}
+
+function SignedIn(): JSX.Element {
+ const account = useThreeWsStore((s) => s.account)
+ const signOut = useThreeWsStore((s) => s.signOut)
+ const [confirming, setConfirming] = useState(false)
+ if (!account) return <></>
+
+ const name = account.displayName || account.username || account.email || 'three.ws account'
+ const scopes = account.scope.split(/\s+/).filter(Boolean)
+
+ return (
+ <div className="flex flex-col gap-4">
+ <Card
+ title="Connected"
+ description="Forge publishes models to this account and runs three.ws Forge cloud generation on its plan."
+ aside={<span className="px-2 py-0.5 rounded-full bg-emerald-500/15 text-emerald-400 text-[10px] font-semibold">Signed in</span>}
+ >
+ <Row label="Account" description={account.email && account.email !== name ? account.email : undefined}>
+ <span className="text-xs text-zinc-200">{name}</span>
+ </Row>
+ {account.plan && (
+ <Row label="Plan">
+ <span className="text-xs text-zinc-300 capitalize">{account.plan}</span>
+ </Row>
+ )}
+ {account.keyPrefix && (
+ <Row label="API key" description="Revoke it from the three.ws dashboard to disconnect every copy of Forge using it.">
+ <span className="text-xs font-mono text-zinc-400">{account.keyPrefix}…</span>
+ </Row>
+ )}
+ {scopes.length > 0 && (
+ <Row label="Permissions">
+ <div className="flex flex-wrap justify-end gap-1 max-w-xs">
+ {scopes.map((s) => (
+ <span key={s} className="px-1.5 py-0.5 rounded bg-zinc-800 text-[10px] font-mono text-zinc-400">{s}</span>
+ ))}
+ </div>
+ </Row>
+ )}
+ <div className="flex items-center gap-2 px-4 py-3">
+ <button
+ type="button"
+ onClick={() => window.electron.threews.open('/dashboard')}
+ className="px-3 py-1.5 rounded-lg text-xs font-semibold bg-zinc-800 hover:bg-zinc-700 text-zinc-200 transition-colors focus:outline-none focus-visible:ring-1 focus-visible:ring-accent-light"
+ >
+ Open dashboard
+ </button>
+ {account.username && (
+ <button
+ type="button"
+ onClick={() => window.electron.threews.open(`/u/${encodeURIComponent(account.username ?? '')}`)}
+ className="px-3 py-1.5 rounded-lg text-xs font-semibold bg-zinc-800 hover:bg-zinc-700 text-zinc-200 transition-colors focus:outline-none focus-visible:ring-1 focus-visible:ring-accent-light"
+ >
+ View profile
+ </button>
+ )}
+ <div className="flex-1" />
+ {confirming ? (
+ <>
+ <span className="text-[11px] text-zinc-500">Forget the key on this machine?</span>
+ <button
+ type="button"
+ onClick={() => { setConfirming(false); void signOut() }}
+ className="px-3 py-1.5 rounded-lg text-xs font-semibold bg-red-500/15 hover:bg-red-500/25 text-red-400 transition-colors"
+ >
+ Sign out
+ </button>
+ <button
+ type="button"
+ onClick={() => setConfirming(false)}
+ className="px-3 py-1.5 rounded-lg text-xs text-zinc-400 hover:text-zinc-200 transition-colors"
+ >
+ Keep
+ </button>
+ </>
+ ) : (
+ <button
+ type="button"
+ onClick={() => setConfirming(true)}
+ className="px-3 py-1.5 rounded-lg text-xs text-zinc-400 hover:text-red-400 transition-colors focus:outline-none focus-visible:text-red-400"
+ >
+ Sign out
+ </button>
+ )}
+ </div>
+ </Card>
+ </div>
+ )
+}
+
+export function ThreeWsSection(): JSX.Element {
+ const account = useThreeWsStore((s) => s.account)
+ const loading = useThreeWsStore((s) => s.loading)
+ const error = useThreeWsStore((s) => s.error)
+ const refresh = useThreeWsStore((s) => s.refresh)
+
+ useEffect(() => { void refresh() }, [refresh])
+
+ return (
+ <Section title="three.ws" subtitle="Publish what you make to your three.ws account and use three.ws Forge cloud generation.">
+ {error && (
+ <div role="alert" className="mb-4 px-4 py-3 rounded-lg bg-red-500/10 border border-red-500/20 text-xs text-red-300 flex items-center justify-between gap-4">
+ <span>{error}</span>
+ <button type="button" onClick={() => void refresh()} className="shrink-0 text-red-200 hover:underline">Retry</button>
+ </div>
+ )}
+ {account === null && loading ? (
+ <div className="grid grid-cols-2 gap-4" aria-busy="true">
+ <div className="h-32 rounded-xl bg-surface-300 border border-zinc-800 animate-pulse" />
+ <div className="h-32 rounded-xl bg-surface-300 border border-zinc-800 animate-pulse" />
+ </div>
+ ) : account?.signedIn ? (
+ <SignedIn />
+ ) : (
+ <SignedOut />
+ )}
+ </Section>
+ )
+}
diff --git a/apps/forge-desktop/src/areas/setup/FirstRunSetup.tsx b/apps/forge-desktop/src/areas/setup/FirstRunSetup.tsx
index 391bdc3c1..ec2c22631 100644
--- a/apps/forge-desktop/src/areas/setup/FirstRunSetup.tsx
+++ b/apps/forge-desktop/src/areas/setup/FirstRunSetup.tsx
@@ -3,7 +3,7 @@ import { useAppStore, SetupProgress } from '@shared/stores/appStore'
// ─── Logo (shared) ──────────────────────────────────────────────────────────
-function three.ws ForgeLogo(): JSX.Element {
+function ForgeLogo(): JSX.Element {
return (
<div className="mb-8">
<svg width="64" height="64" viewBox="0 0 609 609" xmlns="http://www.w3.org/2000/svg">
@@ -27,7 +27,7 @@ function three.ws ForgeLogo(): JSX.Element {
function AppHeader(): JSX.Element {
return (
<>
- <three.ws ForgeLogo />
+ <ForgeLogo />
<h1 className="text-2xl font-semibold text-zinc-100 mb-1">three.ws Forge</h1>
<p className="text-sm text-zinc-500 mb-10">AI-powered 3D mesh generation</p>
</>
diff --git a/apps/forge-desktop/src/index.html b/apps/forge-desktop/src/index.html
index 3bc91a8bb..aa0866169 100644
--- a/apps/forge-desktop/src/index.html
+++ b/apps/forge-desktop/src/index.html
@@ -3,7 +3,7 @@
<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: https://three.ws https://*.three.ws https://storage.googleapis.com; connect-src 'self' blob: http://127.0.0.1:8765 http://localhost:8080 https://api.github.com https://three.ws https://*.three.ws https://storage.googleapis.com; worker-src 'self' blob:" />
+ <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: https://three.ws https://*.three.ws https://storage.googleapis.com https://*.r2.dev; connect-src 'self' blob: http://127.0.0.1:8765 http://localhost:8080 https://api.github.com https://three.ws https://*.three.ws https://storage.googleapis.com; worker-src 'self' blob:" />
<title>three.ws Forge</title>
</head>
<body>
diff --git a/apps/forge-desktop/src/shared/components/ui/UpdateModal.tsx b/apps/forge-desktop/src/shared/components/ui/UpdateModal.tsx
index 774b32eb5..d98487cd5 100644
--- a/apps/forge-desktop/src/shared/components/ui/UpdateModal.tsx
+++ b/apps/forge-desktop/src/shared/components/ui/UpdateModal.tsx
@@ -9,7 +9,7 @@ interface UpdateModalProps {
export function UpdateModal({ currentVersion, latestVersion, onDismiss }: UpdateModalProps): JSX.Element {
const handleDownload = (): void => {
- window.open('https://github.com/lightningpixel/modly/releases', '_blank')
+ window.open('https://three.ws/forge-desktop', '_blank')
}
return createPortal(
@@ -59,7 +59,7 @@ export function UpdateModal({ currentVersion, latestVersion, onDismiss }: Update
</div>
<p className="text-xs text-zinc-500 leading-relaxed">
- Download the latest release from GitHub to get bug fixes, improvements, and new features.
+ Download the latest release from three.ws to get bug fixes, improvements, and new features.
</p>
{/* Actions */}
diff --git a/apps/forge-desktop/src/shared/stores/threeWsStore.ts b/apps/forge-desktop/src/shared/stores/threeWsStore.ts
new file mode 100644
index 000000000..6811e3ecc
--- /dev/null
+++ b/apps/forge-desktop/src/shared/stores/threeWsStore.ts
@@ -0,0 +1,81 @@
+import { create } from 'zustand'
+import type { DeviceLink, ThreeWsAccount } from '@shared/types/threeWs'
+
+// The three.ws account as the renderer sees it: who is signed in, never the
+// key. Settings drives sign-in; the Generate toolbar reads it to gate publish.
+
+type LinkState =
+ | { status: 'idle' }
+ | { status: 'starting' }
+ | { status: 'waiting'; link: DeviceLink; startedAt: number }
+
+interface ThreeWsStore {
+ account: ThreeWsAccount | null
+ loading: boolean
+ error: string | null
+ link: LinkState
+ refresh: () => Promise<void>
+ startLink: () => Promise<void>
+ cancelLink: () => Promise<void>
+ signInWithKey: (key: string) => Promise<boolean>
+ signOut: () => Promise<void>
+}
+
+let listening = false
+
+export const useThreeWsStore = create<ThreeWsStore>((set, get) => {
+ function listen(): void {
+ if (listening) return
+ listening = true
+ window.electron.threews.onLinkResult((result) => {
+ if (result.ok) set({ account: result.value, error: null, link: { status: 'idle' } })
+ else set({ error: result.error, link: { status: 'idle' } })
+ })
+ }
+
+ return {
+ account: null,
+ loading: false,
+ error: null,
+ link: { status: 'idle' },
+
+ refresh: async () => {
+ listen()
+ set({ loading: true })
+ const result = await window.electron.threews.account()
+ if (result.ok) set({ account: result.value, loading: false, error: null })
+ else set({ loading: false, error: result.error })
+ },
+
+ startLink: async () => {
+ listen()
+ set({ link: { status: 'starting' }, error: null })
+ const result = await window.electron.threews.startLink()
+ if (result.ok) set({ link: { status: 'waiting', link: result.value, startedAt: Date.now() } })
+ else set({ link: { status: 'idle' }, error: result.error })
+ },
+
+ cancelLink: async () => {
+ await window.electron.threews.cancelLink()
+ set({ link: { status: 'idle' } })
+ },
+
+ signInWithKey: async (key) => {
+ set({ loading: true, error: null })
+ const result = await window.electron.threews.signInWithKey(key)
+ if (result.ok) {
+ set({ account: result.value, loading: false })
+ return true
+ }
+ set({ loading: false, error: result.error })
+ return false
+ },
+
+ signOut: async () => {
+ if (get().link.status !== 'idle') await get().cancelLink()
+ const result = await window.electron.threews.signOut()
+ if (result.ok) set({ account: result.value, error: null })
+ else set({ error: result.error })
+ },
+ }
+})
diff --git a/apps/forge-desktop/src/shared/types/electron.d.ts b/apps/forge-desktop/src/shared/types/electron.d.ts
index e899f15c5..ee123586e 100644
--- a/apps/forge-desktop/src/shared/types/electron.d.ts
+++ b/apps/forge-desktop/src/shared/types/electron.d.ts
@@ -8,6 +8,15 @@ import type {
AssetLibraryReadRequest,
AssetLibraryReadResult,
} from './assetLibrary'
+import type {
+ DeviceLink,
+ LibraryObject,
+ LibraryPage,
+ PublishRequest,
+ PublishResult,
+ ThreeWsAccount,
+ ThreeWsResult,
+} from './threeWs'
// ─── Extension types ──────────────────────────────────────────────────────────
@@ -212,6 +221,24 @@ declare global {
deleteDirectory: (dirPath: string) => Promise<{ success: boolean; error?: string }>
readScreenshotDataUrl: (filename: string) => Promise<string>
}
+ threews: {
+ origin: () => Promise<string>
+ account: () => Promise<ThreeWsResult<ThreeWsAccount>>
+ signInWithKey: (key: string) => Promise<ThreeWsResult<ThreeWsAccount>>
+ signOut: () => Promise<ThreeWsResult<ThreeWsAccount>>
+ /** Opens the browser; the outcome arrives through onLinkResult. */
+ startLink: () => Promise<ThreeWsResult<DeviceLink>>
+ cancelLink: () => Promise<void>
+ onLinkResult: (cb: (result: ThreeWsResult<ThreeWsAccount>) => void) => void
+ offLinkResult: () => void
+ publish: (args: PublishRequest) => Promise<ThreeWsResult<PublishResult>>
+ libraryList: (args: { offset?: number; limit?: number }) => Promise<ThreeWsResult<LibraryPage>>
+ librarySearch: (args: { q: string; limit?: number }) => Promise<ThreeWsResult<LibraryPage>>
+ /** Resolves to the local path of the downloaded .glb. */
+ libraryDownload: (object: Pick<LibraryObject, 'url' | 'name'>) => Promise<ThreeWsResult<string>>
+ /** Opens a three.ws page (a path or a three.ws URL) in the browser. */
+ open: (path: string) => Promise<void>
+ }
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 }>
diff --git a/apps/forge-desktop/src/shared/types/threeWs.ts b/apps/forge-desktop/src/shared/types/threeWs.ts
new file mode 100644
index 000000000..5e8acd50a
--- /dev/null
+++ b/apps/forge-desktop/src/shared/types/threeWs.ts
@@ -0,0 +1,58 @@
+// The three.ws account, publishing and CC0 library shapes shared by the main
+// process (electron/main/three-ws-account.ts), the preload bridge and the
+// renderer. The API key itself never crosses into the renderer.
+
+export const AVATAR_VISIBILITIES = ['private', 'unlisted', 'public'] as const
+export type AvatarVisibility = typeof AVATAR_VISIBILITIES[number]
+
+export interface ThreeWsAccount {
+ signedIn: boolean
+ email: string | null
+ displayName: string | null
+ username: string | null
+ scope: string
+ keyPrefix: string | null
+ plan: string | null
+}
+
+export interface DeviceLink {
+ userCode: string
+ verificationUrl: string
+ expiresIn: number
+}
+
+export interface PublishResult {
+ id: string
+ name: string
+ url: string
+ visibility: string
+}
+
+export interface PublishRequest {
+ /** A model the local backend serves, as in GenerationJob.outputUrl. */
+ outputUrl: string
+ name: string
+ description?: string
+ visibility: AvatarVisibility
+ tags?: string[]
+}
+
+export interface LibraryObject {
+ name: string
+ label: string
+ url: string
+ thumb: string | null
+ bytes: number | null
+ categories: string[]
+ tags: string[]
+ license: string
+ source: string | null
+}
+
+export interface LibraryPage {
+ objects: LibraryObject[]
+ total: number
+}
+
+/** Every threews:* IPC call answers with this, since errors lose their class across IPC. */
+export type ThreeWsResult<T> = { ok: true; value: T } | { ok: false; error: string; code: string }
diff --git a/apps/forge-desktop/tsconfig.node.json b/apps/forge-desktop/tsconfig.node.json
index d90232c6b..01058a1b2 100644
--- a/apps/forge-desktop/tsconfig.node.json
+++ b/apps/forge-desktop/tsconfig.node.json
@@ -12,5 +12,5 @@
"@main/*": ["./electron/main/*"]
}
},
- "include": ["electron.vite.config.*", "electron/**/*"]
+ "include": ["electron.vite.config.*", "electron/**/*", "src/shared/types/assetLibrary.ts", "src/shared/types/artifacts.ts", "src/shared/types/threeWs.ts"]
}
diff --git a/integrations/modly/tests/host/services/__init__.py b/integrations/modly/tests/host/services/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/integrations/modly/tests/host/services/generators/__init__.py b/integrations/modly/tests/host/services/generators/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/integrations/modly/tests/host/services/generators/base.py b/integrations/modly/tests/host/services/generators/base.py
new file mode 100644
index 000000000..507f64ff8
--- /dev/null
+++ b/integrations/modly/tests/host/services/generators/base.py
@@ -0,0 +1,248 @@
+# Adapted from Modly (https://github.com/lightningpixel/modly), MIT License,
+# Copyright (c) 2026 Lightning Pixel. Copy of api/services/generators/base.py (only dash
+# punctuation normalized) so the extension is tested against the real host contract.
+
+"""
+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/integrations/modly/tests/test_generator.py b/integrations/modly/tests/test_generator.py
new file mode 100644
index 000000000..109d15142
--- /dev/null
+++ b/integrations/modly/tests/test_generator.py
@@ -0,0 +1,305 @@
+"""Tests for the three.ws Modly extension.
+
+The generator is loaded the way Modly's direct mode loads it: by file path,
+with the extension folder and Modly's ``services.generators.base`` importable.
+``host/`` holds a copy of Modly's real ``BaseGenerator`` so the contract under
+test is the one the extension plugs into. A real in-process HTTP server stands
+in for three.ws Forge (no live network). Run with:
+
+ python -m unittest discover -s integrations/modly/tests -p 'test_*.py'
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import os
+import sys
+import tempfile
+import threading
+import unittest
+import urllib.parse
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from pathlib import Path
+from unittest import mock
+
+_HERE = Path(__file__).resolve().parent
+_EXT = _HERE.parent / "three-ws"
+sys.path[:0] = [str(_HERE / "host"), str(_EXT)]
+
+_spec = importlib.util.spec_from_file_location("extensions.three-ws.generator", _EXT / "generator.py")
+generator_mod = importlib.util.module_from_spec(_spec)
+_spec.loader.exec_module(generator_mod)
+
+from services.generators.base import GenerationCancelled # noqa: E402
+
+PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 300
+
+
+def glb(payload: bytes = b"mesh") -> bytes:
+ total = 12 + len(payload)
+ return b"glTF" + (2).to_bytes(4, "little") + total.to_bytes(4, "little") + payload
+
+
+class _Forge(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def _send(self, status, obj):
+ body = json.dumps(obj).encode("utf-8")
+ self.send_response(status)
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def _body(self):
+ n = int(self.headers.get("content-length", 0))
+ raw = self.rfile.read(n) if n else b""
+ try:
+ return json.loads(raw) if raw else {}
+ except ValueError:
+ return {"raw": raw}
+
+ @property
+ def host(self):
+ return f"http://127.0.0.1:{self.server.server_address[1]}"
+
+ def do_GET(self):
+ st = self.server.state
+ u = urllib.parse.urlparse(self.path)
+ qs = urllib.parse.parse_qs(u.query, keep_blank_values=True)
+ if u.path == "/api/forge" and "catalog" in qs:
+ st["catalog_hits"] = st.get("catalog_hits", 0) + 1
+ return self._send(200, {"backends": [
+ {"id": "hunyuan3d", "label": "Hunyuan3D", "paths": ["image"], "byok": None, "configured": True},
+ {"id": "trellis", "label": "TRELLIS", "paths": ["image"], "byok": None, "configured": False},
+ {"id": "meshy", "label": "Meshy 6", "paths": ["geometry", "image"], "byok": "meshy", "configured": True},
+ ]})
+ if u.path in ("/api/forge", "/api/forge-remesh") and "job" in qs:
+ job = qs["job"][0]
+ key = "result_url" if u.path.endswith("remesh") else "glb_url"
+ if st.get("fail_job"):
+ return self._send(200, {"status": "failed", "error": "lane exploded"})
+ return self._send(200, {"status": "done", key: f"{self.host}/_glb/{job}.glb"})
+ if u.path.startswith("/_glb/"):
+ data = st["glbs"].get(u.path, glb(u.path.encode()))
+ self.send_response(200)
+ self.send_header("content-length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ return
+ return self._send(404, {"error": "not_found"})
+
+ def do_POST(self):
+ st = self.server.state
+ u = urllib.parse.urlparse(self.path)
+ qs = urllib.parse.parse_qs(u.query)
+ body = self._body()
+ st.setdefault("posts", []).append((self.path, body, {k.lower(): v for k, v in self.headers.items()}))
+ if u.path in ("/api/forge-upload", "/api/scene-glb-upload"):
+ return self._send(200, {"upload_url": f"{self.host}/_put/x", "public_url": f"https://cdn.example{u.path}/x"})
+ if u.path == "/api/forge" and qs.get("action") == ["rig"]:
+ return self._send(202, {"job_id": "rig1"})
+ if u.path == "/api/forge":
+ return self._send(200, {"job_id": "gen1", "backend": body.get("backend") or "hunyuan3d"})
+ if u.path == "/api/forge-remesh":
+ return self._send(202, {"job_id": "rm1"})
+ if u.path == "/api/avatars/upload":
+ return self._send(200, {"storage_key": "u/k.glb", "size_bytes": 16})
+ if u.path == "/api/avatars":
+ return self._send(201, {"avatar": {"id": "av_1", "name": body.get("name")}})
+ return self._send(404, {"error": "not_found"})
+
+ def do_PUT(self):
+ n = int(self.headers.get("content-length", 0))
+ self.server.state.setdefault("puts", []).append(self.rfile.read(n))
+ self.send_response(200)
+ self.send_header("content-length", "0")
+ self.end_headers()
+
+
+class GeneratorTest(unittest.TestCase):
+ def setUp(self):
+ self.server = HTTPServer(("127.0.0.1", 0), _Forge)
+ self.server.state = {"glbs": {}}
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
+ self.tmp = tempfile.TemporaryDirectory()
+ root = Path(self.tmp.name)
+ self.models = root / "models"
+ self.workspace = root / "workspace"
+ self.workspace.mkdir()
+ self.env = mock.patch.dict(os.environ, {
+ "THREE_WS_BASE_URL": f"http://127.0.0.1:{self.server.server_address[1]}",
+ "WORKSPACE_DIR": str(self.workspace),
+ })
+ self.env.start()
+ os.environ.pop("THREE_WS_PROVIDER_KEY", None)
+ os.environ.pop("THREE_WS_API_KEY", None)
+ self.events = []
+ # The poll loop sleeps between ticks; a done-on-first-poll stub never sleeps.
+
+ def tearDown(self):
+ self.env.stop()
+ self.server.shutdown()
+ self.server.server_close()
+ self.tmp.cleanup()
+
+ def node(self, node_id):
+ """Instantiate exactly as the registry does in direct mode."""
+ gen = generator_mod.ThreeWSGenerator(self.models / f"three-ws/{node_id}", self.workspace)
+ gen.MODEL_ID = f"three-ws/{node_id}"
+ gen.MODEL_NODE_ID = node_id
+ gen.outputs_dir = self.workspace / "Default"
+ return gen
+
+ def run_node(self, node_id, data, params=None, cancel=None):
+ gen = self.node(node_id)
+ self.assertTrue(gen.is_downloaded())
+ gen.load()
+ out = gen.generate(data, params or {}, lambda p, s: self.events.append((p, s)), cancel or threading.Event())
+ return gen, Path(out)
+
+ def submits(self, path="/api/forge"):
+ return [b for p, b, _h in self.server.state.get("posts", []) if p == path]
+
+ def test_image_to_3d_writes_a_glb_into_the_collection(self):
+ _gen, out = self.run_node("image-to-3d", PNG, {"engine": "hunyuan3d", "tier": "high"})
+ self.assertEqual(out.parent, self.workspace / "Default")
+ self.assertTrue(out.read_bytes().startswith(b"glTF"))
+ self.assertEqual(self.submits()[0]["backend"], "hunyuan3d")
+ self.assertEqual(self.submits()[0]["tier"], "high")
+ self.assertEqual(self.submits()[0]["image_urls"], ["https://cdn.example/api/forge-upload/x"])
+ pcts = [p for p, _s in self.events]
+ self.assertEqual(pcts, sorted(pcts))
+
+ def test_engine_not_live_falls_back_to_server_default_and_says_so(self):
+ self.run_node("image-to-3d", PNG, {"engine": "trellis"})
+ self.assertNotIn("backend", self.submits()[0])
+ self.assertTrue(any("not available" in s for _p, s in self.events))
+
+ def test_byok_engine_without_a_key_explains_how_to_fix_it(self):
+ with self.assertRaises(ValueError) as ctx:
+ self.run_node("image-to-3d", PNG, {"engine": "meshy"})
+ self.assertIn("THREE_WS_PROVIDER_KEY", str(ctx.exception))
+ self.assertEqual(self.submits(), [])
+
+ def test_byok_key_travels_as_header(self):
+ self.run_node("text-to-3d", b"", {"prompt": "a brass lantern", "route": "geometry", "engine": "meshy", "provider_key": "msy_test"})
+ headers = [h for p, _b, h in self.server.state["posts"] if p == "/api/forge"][0]
+ self.assertEqual(headers.get("x-forge-provider-key"), "msy_test")
+ self.assertEqual(self.submits()[0]["path"], "geometry")
+
+ def test_text_to_3d_reads_the_prompt_the_workflow_runner_injects(self):
+ _gen, out = self.run_node("text-to-3d", PNG, {"prompt": "a red fox", "text": "a red fox"})
+ self.assertEqual(self.submits()[0]["prompt"], "a red fox")
+ self.assertTrue(out.is_file())
+
+ def test_text_to_3d_requires_a_prompt(self):
+ with self.assertRaises(ValueError):
+ self.run_node("text-to-3d", PNG, {})
+
+ def test_sketch_needs_a_real_drawing_and_a_prompt(self):
+ tiny = b"\x89PNG\r\n\x1a\n" + b"\x00" * 60
+ with self.assertRaises(ValueError):
+ self.run_node("sketch-to-3d", tiny, {"prompt": "a chair"})
+ with self.assertRaises(ValueError):
+ self.run_node("sketch-to-3d", PNG, {})
+ self.run_node("sketch-to-3d", PNG, {"prompt": "a chair with curved legs"})
+ self.assertEqual(self.submits()[0]["path"], "sketch")
+
+ def test_chaining_reuses_the_cloud_url_instead_of_reuploading(self):
+ _gen, made = self.run_node("image-to-3d", PNG)
+ uploads_before = len(self.submits("/api/scene-glb-upload"))
+ # The workflow runner hands the upstream GLB to a mesh node as bytes.
+ self.run_node("rig", made.read_bytes())
+ self.assertEqual(len(self.submits("/api/scene-glb-upload")), uploads_before)
+ rig_body = self.submits("/api/forge?action=rig")[0]
+ self.assertTrue(rig_body["glb_url"].endswith("/_glb/gen1.glb"))
+
+ def test_local_mesh_is_uploaded_once_then_remembered(self):
+ local = self.workspace / "Default" / "local.glb"
+ local.parent.mkdir(parents=True, exist_ok=True)
+ local.write_bytes(glb(b"made-by-a-local-model"))
+ params = {"mesh_path": "Default/local.glb", "remesh_mode": "quad", "target_faces": 4000, "texture_size": 2048}
+ _gen, out = self.run_node("remesh", PNG, params)
+ self.run_node("remesh", PNG, params)
+ self.assertEqual(len(self.submits("/api/scene-glb-upload")), 1)
+ body = self.submits("/api/forge-remesh")[0]
+ self.assertEqual((body["remesh_mode"], body["target_faces"], body["texture_size"]), ("quad", 4000, 2048))
+ self.assertIn("three-ws-remesh-quad", out.name)
+
+ def test_mesh_path_accepts_the_generate_page_url_form(self):
+ local = self.workspace / "Default" / "a.glb"
+ local.parent.mkdir(parents=True, exist_ok=True)
+ local.write_bytes(glb(b"a"))
+ self.run_node("rig", PNG, {"mesh_path": "/workspace/Default/a.glb"})
+ self.assertEqual(len(self.submits("/api/scene-glb-upload")), 1)
+
+ def test_mesh_path_cannot_escape_the_workspace(self):
+ with self.assertRaises(ValueError):
+ self.run_node("rig", PNG, {"mesh_path": "../../etc/passwd"})
+
+ def test_mesh_nodes_reject_non_glb_input(self):
+ with self.assertRaises(ValueError):
+ self.run_node("remesh", PNG)
+
+ def test_failed_job_surfaces_the_server_error(self):
+ self.server.state["fail_job"] = True
+ with self.assertRaises(RuntimeError) as ctx:
+ self.run_node("image-to-3d", PNG)
+ self.assertIn("lane exploded", str(ctx.exception))
+
+ def test_cancel_maps_to_modly_generation_cancelled(self):
+ cancel = threading.Event()
+ cancel.set()
+ gen = self.node("rig")
+ gen.load()
+ with self.assertRaises(GenerationCancelled):
+ gen.generate(glb(b"x"), {}, None, cancel)
+
+ def test_publish_saves_to_the_account_and_passes_the_mesh_through(self):
+ data = glb(b"publish-me")
+ with mock.patch.object(generator_mod.webbrowser, "open") as opened:
+ _gen, out = self.run_node("publish", data, {"api_key": "sk_live_x", "name": "Fox", "visibility": "public"})
+ self.assertEqual(out.read_bytes(), data)
+ opened.assert_called_once()
+ self.assertTrue(opened.call_args[0][0].endswith("/avatars/av_1"))
+ created = self.submits("/api/avatars")[0]
+ self.assertEqual((created["name"], created["visibility"]), ("Fox", "public"))
+
+ def test_publish_without_a_key_says_where_to_get_one(self):
+ with self.assertRaises(RuntimeError) as ctx:
+ self.run_node("publish", glb(b"x"))
+ self.assertIn("dashboard/api", str(ctx.exception))
+
+ def test_client_handle_is_stable_across_nodes(self):
+ a = self.node("image-to-3d")
+ a.load()
+ b = self.node("rig")
+ b.load()
+ self.assertEqual(a._model.client_handle, b._model.client_handle)
+
+
+class ManifestTest(unittest.TestCase):
+ def test_manifest_matches_what_modly_requires(self):
+ manifest = json.loads((_EXT / "manifest.json").read_text(encoding="utf-8"))
+ self.assertEqual(manifest["id"], _EXT.name)
+ self.assertEqual(manifest["type"], "model")
+ self.assertTrue(hasattr(generator_mod, manifest["generator_class"]))
+ handled = {"image-to-3d", "text-to-3d", "sketch-to-3d", "rig", "remesh", "publish"}
+ self.assertEqual({n["id"] for n in manifest["nodes"]}, handled)
+ for node in manifest["nodes"]:
+ self.assertNotIn("hf_repo", node)
+ for param in node["params_schema"]:
+ self.assertIn(param["type"], {"select", "int", "float", "string"})
+ if param["type"] == "select":
+ self.assertIn(param["default"], [o["value"] for o in param["options"]])
+
+ def test_direct_mode_needs_no_setup(self):
+ for name in ("setup.py", "build_vendor.py", "requirements.txt"):
+ self.assertFalse((_EXT / name).exists(), name)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/integrations/modly/three-ws/LICENSE b/integrations/modly/three-ws/LICENSE
new file mode 100644
index 000000000..b5ae2a4e1
--- /dev/null
+++ b/integrations/modly/three-ws/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2026 nirholas
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/integrations/modly/three-ws/generator.py b/integrations/modly/three-ws/generator.py
new file mode 100644
index 000000000..8afebe890
--- /dev/null
+++ b/integrations/modly/three-ws/generator.py
@@ -0,0 +1,472 @@
+"""three.ws Cloud for Modly.
+
+One generator class serves every node in ``manifest.json``. Modly instantiates
+it once per node and sets ``MODEL_NODE_ID`` (``image-to-3d``, ``text-to-3d``,
+``sketch-to-3d``, ``rig``, ``remesh``, ``publish``), so ``generate`` dispatches
+on that id.
+
+The extension runs in Modly's direct mode: no venv, no setup step, no weights.
+Everything it needs is the Python standard library plus the vendored
+``three_ws_client.py`` beside this file. Work happens on three.ws Forge; the
+mesh that comes back is written into the Modly workspace like any local model's
+output, so it flows into Modly's viewer, mesh tools, exports and workflows.
+
+Meshes that three.ws produced keep their cloud URL in a small index (keyed by
+the SHA-256 of the GLB bytes), so chaining Image to 3D into Auto-Rig or Remesh
+never re-uploads the file. A mesh made by a local Modly model is uploaded once
+through the public GLB presign and then reused the same way.
+
+Configuration (all optional):
+
+* ``THREE_WS_BASE_URL`` deployment origin, default ``https://three.ws``
+* ``THREE_WS_PROVIDER_KEY`` Meshy/Tripo/Rodin/Stability/Replicate key for BYOK engines
+* ``THREE_WS_API_KEY`` three.ws key with ``avatars:write`` for the Publish node
+"""
+
+from __future__ import annotations
+
+import contextlib
+import hashlib
+import json
+import math
+import os
+import threading
+import time
+import uuid
+import webbrowser
+from pathlib import Path
+from typing import Callable, Optional
+
+from services.generators.base import BaseGenerator, GenerationCancelled, smooth_progress
+
+from three_ws_client import DEFAULT_BASE_URL, ThreeWSClient, ThreeWSError, is_glb
+
+_STATE_FILE = "three-ws-state.json"
+_INDEX_LIMIT = 500
+
+ProgressCb = Optional[Callable[[int, str], None]]
+
+
+class ThreeWSGenerator(BaseGenerator):
+ MODEL_ID = "three-ws"
+ DISPLAY_NAME = "three.ws Cloud"
+ VRAM_GB = 0
+
+ def __init__(self, model_dir: Path, outputs_dir: Path) -> None:
+ super().__init__(model_dir, outputs_dir)
+ self._state_lock = threading.Lock()
+ self._catalog: Optional[dict] = None
+ self._catalog_at = 0.0
+
+ # ------------------------------------------------------------------ #
+ # Lifecycle: nothing to download, nothing to hold in VRAM
+ # ------------------------------------------------------------------ #
+
+ def is_downloaded(self) -> bool:
+ return True
+
+ def load(self) -> None:
+ self._model = ThreeWSClient(
+ os.environ.get("THREE_WS_BASE_URL") or DEFAULT_BASE_URL,
+ client_handle=self._client_handle(),
+ timeout=60.0,
+ )
+
+ def unload(self) -> None:
+ self._model = None
+
+ # ------------------------------------------------------------------ #
+ # Dispatch
+ # ------------------------------------------------------------------ #
+
+ def generate(
+ self,
+ image_bytes: bytes,
+ params: dict,
+ progress_cb: ProgressCb = None,
+ cancel_event: Optional[threading.Event] = None,
+ ) -> Path:
+ if self._model is None:
+ self.load()
+ node = self.MODEL_NODE_ID or "image-to-3d"
+ handlers = {
+ "image-to-3d": self._image_to_3d,
+ "text-to-3d": self._text_to_3d,
+ "sketch-to-3d": self._sketch_to_3d,
+ "rig": self._rig,
+ "remesh": self._remesh,
+ "publish": self._publish,
+ }
+ handler = handlers.get(node)
+ if handler is None:
+ raise ValueError(f"Unknown three.ws node '{node}'.")
+ try:
+ return handler(image_bytes or b"", params or {}, progress_cb, cancel_event)
+ except ThreeWSError as exc:
+ if exc.code == "cancelled":
+ raise GenerationCancelled() from exc
+ raise RuntimeError(_explain(exc)) from exc
+
+ # ------------------------------------------------------------------ #
+ # Generation nodes
+ # ------------------------------------------------------------------ #
+
+ def _image_to_3d(self, image_bytes, params, progress_cb, cancel_event) -> Path:
+ if is_glb(image_bytes) or not image_bytes:
+ raise ValueError("three.ws Image to 3D needs an image input.")
+ client = self._client_for(params)
+ content_type = _sniff_image_type(image_bytes)
+ backend, note = self._resolve_engine(params.get("engine"), "image", client)
+ with _easing(progress_cb, 2, 8, note or "Sending image to three.ws"):
+ image_url = client.upload_image(image_bytes, content_type)
+ self._check_cancelled(cancel_event)
+ job = client.submit_image_to_3d(
+ image_url,
+ prompt=str(params.get("prompt") or ""),
+ tier=_tier(params),
+ backend=backend,
+ path="image",
+ )
+ label = f"Generating on {job.get('backend') or backend or 'three.ws'}"
+ url = client.poll(
+ job["job_id"],
+ on_progress=_ticker(self, progress_cb, 8, 90, 120.0, label),
+ should_cancel=_canceller(cancel_event),
+ timeout=600.0,
+ )
+ return self._download(client, url, progress_cb, "image-to-3d")
+
+ def _text_to_3d(self, image_bytes, params, progress_cb, cancel_event) -> Path:
+ prompt = str(params.get("prompt") or params.get("text") or "").strip()
+ if len(prompt) < 3:
+ raise ValueError("Connect a text node with a prompt of at least 3 characters.")
+ client = self._client_for(params)
+ path = "geometry" if params.get("route") == "geometry" else "image"
+ backend, note = self._resolve_engine(params.get("engine"), path, client)
+ with _easing(progress_cb, 2, 8, note or "Sending prompt to three.ws"):
+ job = client.submit_text_to_3d(
+ prompt,
+ tier=_tier(params),
+ backend=backend,
+ path=path,
+ aspect_ratio=str(params.get("aspect_ratio") or "1:1"),
+ )
+ label = f"Generating on {job.get('backend') or backend or 'three.ws'}"
+ url = client.poll(
+ job["job_id"],
+ on_progress=_ticker(self, progress_cb, 8, 90, 150.0, label),
+ should_cancel=_canceller(cancel_event),
+ timeout=900.0,
+ )
+ return self._download(client, url, progress_cb, "text-to-3d")
+
+ def _sketch_to_3d(self, image_bytes, params, progress_cb, cancel_event) -> Path:
+ if is_glb(image_bytes) or not image_bytes or _is_placeholder_png(image_bytes):
+ raise ValueError("three.ws Sketch to 3D needs a drawing as its image input.")
+ prompt = str(params.get("prompt") or params.get("text") or "").strip()
+ if len(prompt) < 3:
+ raise ValueError(
+ "Say what the sketch shows (for example: a wooden chair with curved legs), "
+ "either in the node's field or from a connected text node."
+ )
+ client = self._client_for(params)
+ with _easing(progress_cb, 2, 8, "Sending sketch to three.ws"):
+ sketch_url = client.upload_image(image_bytes, _sniff_image_type(image_bytes))
+ self._check_cancelled(cancel_event)
+ job = client.submit_image_to_3d(sketch_url, prompt=prompt, tier=_tier(params), path="sketch")
+ url = client.poll(
+ job["job_id"],
+ on_progress=_ticker(self, progress_cb, 8, 90, 90.0, "Lifting the sketch to 3D"),
+ should_cancel=_canceller(cancel_event),
+ timeout=600.0,
+ )
+ return self._download(client, url, progress_cb, "sketch-to-3d")
+
+ # ------------------------------------------------------------------ #
+ # Mesh nodes
+ # ------------------------------------------------------------------ #
+
+ def _rig(self, image_bytes, params, progress_cb, cancel_event) -> Path:
+ client = self._client_for(params)
+ mesh_url = self._mesh_url(client, image_bytes, params, progress_cb)
+ self._check_cancelled(cancel_event)
+ url = client.rig(
+ mesh_url,
+ on_progress=_ticker(self, progress_cb, 15, 90, 60.0, "Fitting a humanoid skeleton"),
+ should_cancel=_canceller(cancel_event),
+ )
+ return self._download(client, url, progress_cb, "rigged")
+
+ def _remesh(self, image_bytes, params, progress_cb, cancel_event) -> Path:
+ client = self._client_for(params)
+ mesh_url = self._mesh_url(client, image_bytes, params, progress_cb)
+ self._check_cancelled(cancel_event)
+ mode = str(params.get("remesh_mode") or "quad")
+ url = client.remesh(
+ mesh_url,
+ remesh_mode=mode,
+ operation=str(params.get("operation") or "full"),
+ target_faces=_int(params.get("target_faces"), 0),
+ texture_size=_int(params.get("texture_size"), 1024),
+ on_progress=_ticker(self, progress_cb, 15, 90, 120.0, f"Remeshing to {mode}"),
+ should_cancel=_canceller(cancel_event),
+ )
+ return self._download(client, url, progress_cb, f"remesh-{mode}")
+
+ def _publish(self, image_bytes, params, progress_cb, cancel_event) -> Path:
+ api_key = str(params.get("api_key") or os.environ.get("THREE_WS_API_KEY") or "").strip()
+ glb = self._mesh_bytes(image_bytes, params)
+ client = self._client_for(params)
+ self._report(progress_cb, 10, "Publishing to three.ws")
+ avatar = client.publish_glb(
+ glb,
+ api_key=api_key,
+ name=str(params.get("name") or "Made in Modly"),
+ visibility=str(params.get("visibility") or "unlisted"),
+ tags=("modly",),
+ source_meta={"tool": "modly", "extension": "three-ws"},
+ )
+ self._check_cancelled(cancel_event)
+ page = client.avatar_page_url(avatar)
+ print(f"[three.ws] Published: {page}")
+ if params.get("open_page", "yes") == "yes":
+ webbrowser.open(page)
+ self._report(progress_cb, 95, f"Published: {page}")
+ out = self._new_output_path("published")
+ out.write_bytes(glb)
+ return out
+
+ # ------------------------------------------------------------------ #
+ # Mesh resolution and the cloud URL index
+ # ------------------------------------------------------------------ #
+
+ def _mesh_bytes(self, image_bytes: bytes, params: dict) -> bytes:
+ mesh_path = params.get("mesh_path")
+ if mesh_path:
+ path = self._resolve_workspace_path(str(mesh_path))
+ data = path.read_bytes()
+ else:
+ data = image_bytes
+ if not is_glb(data):
+ raise ValueError(
+ "This node needs a GLB mesh input. Connect it after a model node, or convert "
+ "OBJ/STL/PLY to GLB with Modly's export first."
+ )
+ return data
+
+ def _mesh_url(self, client: ThreeWSClient, image_bytes: bytes, params: dict, progress_cb) -> str:
+ glb = self._mesh_bytes(image_bytes, params)
+ digest = hashlib.sha256(glb).hexdigest()
+ known = self._state().get("urls", {}).get(digest)
+ if known:
+ self._report(progress_cb, 10, "Mesh already on three.ws")
+ return known
+ self._report(progress_cb, 5, f"Uploading mesh ({len(glb) // 1024} KB)")
+ url = client.upload_glb(glb)
+ self._remember(digest, url)
+ return url
+
+ def _resolve_workspace_path(self, raw: str) -> Path:
+ workspace = self._workspace_dir().resolve()
+ cleaned = raw.replace("\\", "/")
+ if cleaned.startswith("/workspace/"):
+ cleaned = cleaned[len("/workspace/"):]
+ candidate = Path(cleaned)
+ if not candidate.is_absolute():
+ candidate = (workspace / candidate).resolve()
+ if workspace != candidate and workspace not in candidate.parents:
+ raise ValueError("mesh_path points outside the Modly workspace.")
+ if not candidate.is_file():
+ raise ValueError(f"Mesh file not found: {raw}")
+ return candidate
+
+ def _workspace_dir(self) -> Path:
+ env = os.environ.get("WORKSPACE_DIR")
+ if env:
+ return Path(env)
+ # Modly points outputs_dir at WORKSPACE_DIR/<collection> for each job.
+ return Path(self.outputs_dir).parent
+
+ def _state_path(self) -> Path:
+ # model_dir is MODELS_DIR/three-ws/<node>; the parent is shared by every
+ # node of this extension, so a mesh made by one node is known to the rest.
+ return Path(self.model_dir).parent / _STATE_FILE
+
+ def _state(self) -> dict:
+ with self._state_lock:
+ try:
+ data = json.loads(self._state_path().read_text(encoding="utf-8"))
+ return data if isinstance(data, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+ def _write_state(self, state: dict) -> None:
+ path = self._state_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_suffix(".tmp")
+ tmp.write_text(json.dumps(state, indent=1), encoding="utf-8")
+ os.replace(tmp, path)
+
+ def _remember(self, digest: str, url: str) -> None:
+ state = self._state()
+ urls = state.get("urls") or {}
+ urls.pop(digest, None)
+ urls[digest] = url
+ while len(urls) > _INDEX_LIMIT:
+ urls.pop(next(iter(urls)))
+ state["urls"] = urls
+ with self._state_lock:
+ self._write_state(state)
+
+ def _client_handle(self) -> str:
+ """A stable anonymous handle so every generation from this machine is
+ scoped together on three.ws (rate limits, the creations list)."""
+ state = self._state()
+ handle = state.get("client_handle")
+ if isinstance(handle, str) and len(handle) >= 16:
+ return handle
+ state["client_handle"] = handle = uuid.uuid4().hex
+ with self._state_lock:
+ self._write_state(state)
+ return handle
+
+ # ------------------------------------------------------------------ #
+ # Engines, clients, output
+ # ------------------------------------------------------------------ #
+
+ def _client_for(self, params: dict) -> ThreeWSClient:
+ base: ThreeWSClient = self._model
+ key = str(params.get("provider_key") or os.environ.get("THREE_WS_PROVIDER_KEY") or "").strip()
+ if not key:
+ return base
+ return ThreeWSClient(base.base_url, provider_key=key, client_handle=base.client_handle, timeout=base.timeout)
+
+ def _live_catalog(self, client: ThreeWSClient) -> dict:
+ if self._catalog is None or time.monotonic() - self._catalog_at > 600:
+ self._catalog = client.get_catalog()
+ self._catalog_at = time.monotonic()
+ return self._catalog
+
+ def _resolve_engine(self, engine, path: str, client: ThreeWSClient):
+ """Validate an engine against the live catalog.
+
+ Returns ``(backend_or_None, note)``. ``None`` lets the server pick its
+ default lane. An engine that is not live for this path falls back to the
+ default instead of failing the run, and ``note`` tells the user why.
+ """
+ engine = str(engine or "auto")
+ if engine == "auto":
+ return None, ""
+ try:
+ backends = self._live_catalog(client).get("backends") or []
+ except ThreeWSError:
+ return engine, ""
+ entry = next((b for b in backends if b.get("id") == engine), None)
+ if not entry or not entry.get("configured") or path not in (entry.get("paths") or []):
+ return None, f"{engine} is not available for this route on three.ws yet, using the default engine"
+ if entry.get("byok") and not client.provider_key:
+ raise ValueError(
+ f"{entry.get('label') or engine} runs on your own provider account. Paste the key "
+ "into the node's Provider key field or set THREE_WS_PROVIDER_KEY, or pick a free engine."
+ )
+ return engine, ""
+
+ def _new_output_path(self, tag: str) -> Path:
+ out_dir = Path(self.outputs_dir)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ return out_dir / f"{int(time.time())}_{uuid.uuid4().hex[:8]}_three-ws-{tag}.glb"
+
+ def _download(self, client: ThreeWSClient, url: str, progress_cb, tag: str) -> Path:
+ self._report(progress_cb, 92, "Downloading mesh")
+ out = self._new_output_path(tag)
+ client.download(url, str(out))
+ data = out.read_bytes()
+ if not is_glb(data):
+ out.unlink(missing_ok=True)
+ raise RuntimeError("three.ws returned a file that is not a valid GLB.")
+ self._remember(hashlib.sha256(data).hexdigest(), url)
+ self._report(progress_cb, 99, "Done")
+ return out
+
+
+# ---------------------------------------------------------------------- #
+# Helpers
+# ---------------------------------------------------------------------- #
+
+_PLACEHOLDER_MAX_BYTES = 128
+
+
+def _is_placeholder_png(data: bytes) -> bool:
+ """Modly sends a 1x1 PNG to model nodes that have no image connected."""
+ return data[:8] == b"\x89PNG\r\n\x1a\n" and len(data) <= _PLACEHOLDER_MAX_BYTES
+
+
+def _sniff_image_type(data: bytes) -> str:
+ if data[:8] == b"\x89PNG\r\n\x1a\n":
+ return "image/png"
+ if data[:3] == b"\xff\xd8\xff":
+ return "image/jpeg"
+ if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
+ return "image/webp"
+ raise ValueError("three.ws accepts PNG, JPEG or WebP images.")
+
+
+def _tier(params: dict) -> str:
+ tier = str(params.get("tier") or "standard")
+ return tier if tier in ("draft", "standard", "high") else "standard"
+
+
+def _int(value, default: int) -> int:
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return default
+
+
+def _canceller(cancel_event: Optional[threading.Event]):
+ return (lambda: cancel_event.is_set()) if cancel_event is not None else None
+
+
+def _easing(progress_cb, start: int, end: int, label: str):
+ """Keep the bar moving through a blocking upload or submit: a cold lane can
+ take tens of seconds to accept a job and reports nothing meanwhile."""
+ if progress_cb:
+ progress_cb(start, label)
+ stop = threading.Event()
+ worker = None
+ if progress_cb:
+ worker = threading.Thread(
+ target=smooth_progress, args=(progress_cb, start, end, label, stop, 2.0), daemon=True
+ )
+ worker.start()
+ try:
+ yield
+ finally:
+ stop.set()
+ if worker:
+ worker.join(timeout=1)
+
+
+def _ticker(gen: BaseGenerator, progress_cb, start: int, end: int, expected_s: float, label: str):
+ """Map elapsed seconds onto Modly's percent bar. Forge reports a status, not
+ a percentage, so progress eases toward ``end`` over the lane's typical time."""
+
+ def tick(status: str, elapsed: float) -> None:
+ frac = 1.0 - math.exp(-elapsed / max(expected_s, 1.0))
+ pct = int(start + (end - start) * frac)
+ gen._report(progress_cb, pct, f"{label} ({int(elapsed)}s)")
+
+ return tick
+
+
+def _explain(exc: ThreeWSError) -> str:
+ if exc.code == "rate_limited" or exc.status == 429:
+ return "three.ws is rate limiting this machine. Wait a minute and run again."
+ if exc.code == "unreachable":
+ return f"{exc.message}. Check your internet connection."
+ if exc.code == "needs_key":
+ return "That engine needs your provider key. Set it on the node or in THREE_WS_PROVIDER_KEY."
+ if exc.code == "missing_api_key":
+ return "Publishing needs a three.ws API key with avatars:write. Create one at three.ws/dashboard/api."
+ return exc.message
diff --git a/integrations/modly/three-ws/manifest.json b/integrations/modly/three-ws/manifest.json
new file mode 100644
index 000000000..4161c317e
--- /dev/null
+++ b/integrations/modly/three-ws/manifest.json
@@ -0,0 +1,261 @@
+{
+ "id": "three-ws",
+ "name": "three.ws Cloud",
+ "type": "model",
+ "source": "https://github.com/nirholas/three.ws/tree/main/integrations/modly",
+ "description": "Cloud 3D generation, auto-rigging and retopology from three.ws Forge. No GPU, no weights, no setup: image, text and sketch to 3D on hosted TRELLIS and Hunyuan3D lanes, a humanoid auto-rigger, a quad remesher, and one-click publishing to a shareable three.ws page.",
+ "version": "1.0.0",
+ "author": "three.ws",
+ "generator_class": "ThreeWSGenerator",
+ "tags": ["image-to-3d", "text-to-3d", "sketch-to-3d", "rigging", "remesh", "cloud", "no-gpu"],
+ "vram_gb": 0,
+ "nodes": [
+ {
+ "id": "image-to-3d",
+ "name": "three.ws Image to 3D",
+ "input": "image",
+ "output": "mesh",
+ "params_schema": [
+ {
+ "id": "engine",
+ "label": "Engine",
+ "type": "select",
+ "default": "auto",
+ "tooltip": "Which three.ws lane builds the mesh. Auto picks the healthiest free lane. Engines marked (your key) need a provider key.",
+ "options": [
+ { "value": "auto", "label": "Auto (free)" },
+ { "value": "hunyuan3d", "label": "Hunyuan3D (free)" },
+ { "value": "nvidia", "label": "TRELLIS on NVIDIA (free)" },
+ { "value": "trellis_selfhost", "label": "TRELLIS self-host (free)" },
+ { "value": "trellis2", "label": "TRELLIS.2 (free)" },
+ { "value": "huggingface", "label": "Hugging Face Spaces (free)" },
+ { "value": "meshy", "label": "Meshy 6 (your key)" },
+ { "value": "tripo", "label": "Tripo v3.1 (your key)" },
+ { "value": "rodin", "label": "Rodin Hyper3D (your key)" },
+ { "value": "stability", "label": "Stable Fast 3D (your key)" },
+ { "value": "replicate_byok", "label": "Replicate (your key)" }
+ ]
+ },
+ {
+ "id": "tier",
+ "label": "Quality",
+ "type": "select",
+ "default": "standard",
+ "tooltip": "Draft is fast and low-poly. High spends the deepest sampler budget and adds PBR textures.",
+ "options": [
+ { "value": "draft", "label": "Draft" },
+ { "value": "standard", "label": "Standard" },
+ { "value": "high", "label": "High" }
+ ]
+ },
+ {
+ "id": "prompt",
+ "label": "Hint (optional)",
+ "type": "string",
+ "default": "",
+ "tooltip": "A few words naming the subject. Helps lanes that accept a text hint."
+ },
+ {
+ "id": "provider_key",
+ "label": "Provider key (optional)",
+ "type": "string",
+ "default": "",
+ "tooltip": "Only for engines marked (your key). Prefer the THREE_WS_PROVIDER_KEY environment variable so the key is not saved into workflow files."
+ }
+ ]
+ },
+ {
+ "id": "text-to-3d",
+ "name": "three.ws Text to 3D",
+ "input": "text",
+ "output": "mesh",
+ "params_schema": [
+ {
+ "id": "route",
+ "label": "Route",
+ "type": "select",
+ "default": "image",
+ "tooltip": "Reference image renders the prompt to a picture and lifts it to 3D on a free lane. Native text-to-3D sends the prompt straight to Meshy, Tripo or Rodin with your key.",
+ "options": [
+ { "value": "image", "label": "Reference image, then 3D (free)" },
+ { "value": "geometry", "label": "Native text-to-3D (your key)" }
+ ]
+ },
+ {
+ "id": "engine",
+ "label": "Engine",
+ "type": "select",
+ "default": "auto",
+ "tooltip": "Auto uses the server default for the chosen route.",
+ "options": [
+ { "value": "auto", "label": "Auto" },
+ { "value": "hunyuan3d", "label": "Hunyuan3D (free, image route)" },
+ { "value": "nvidia", "label": "TRELLIS on NVIDIA (free, image route)" },
+ { "value": "trellis_selfhost", "label": "TRELLIS self-host (free, image route)" },
+ { "value": "trellis2", "label": "TRELLIS.2 (free, image route)" },
+ { "value": "meshy", "label": "Meshy 6 (your key)" },
+ { "value": "tripo", "label": "Tripo v3.1 (your key)" },
+ { "value": "rodin", "label": "Rodin Hyper3D (your key)" }
+ ]
+ },
+ {
+ "id": "tier",
+ "label": "Quality",
+ "type": "select",
+ "default": "standard",
+ "options": [
+ { "value": "draft", "label": "Draft" },
+ { "value": "standard", "label": "Standard" },
+ { "value": "high", "label": "High" }
+ ]
+ },
+ {
+ "id": "aspect_ratio",
+ "label": "Reference framing",
+ "type": "select",
+ "default": "1:1",
+ "tooltip": "Framing of the reference image on the image route.",
+ "options": [
+ { "value": "1:1", "label": "Square" },
+ { "value": "3:4", "label": "Portrait" },
+ { "value": "4:3", "label": "Landscape" }
+ ]
+ },
+ {
+ "id": "provider_key",
+ "label": "Provider key (optional)",
+ "type": "string",
+ "default": "",
+ "tooltip": "Needed for the native route. Prefer the THREE_WS_PROVIDER_KEY environment variable."
+ }
+ ]
+ },
+ {
+ "id": "sketch-to-3d",
+ "name": "three.ws Sketch to 3D",
+ "inputs": ["image", "text"],
+ "output": "mesh",
+ "params_schema": [
+ {
+ "id": "prompt",
+ "label": "What the sketch shows",
+ "type": "string",
+ "default": "",
+ "tooltip": "Required unless a text node is connected. The sketch model is prompt-conditioned, for example: a wooden chair with curved legs."
+ },
+ {
+ "id": "tier",
+ "label": "Quality",
+ "type": "select",
+ "default": "standard",
+ "options": [
+ { "value": "draft", "label": "Draft" },
+ { "value": "standard", "label": "Standard" },
+ { "value": "high", "label": "High" }
+ ]
+ }
+ ]
+ },
+ {
+ "id": "rig",
+ "name": "three.ws Auto-Rig",
+ "input": "mesh",
+ "output": "mesh",
+ "params_schema": []
+ },
+ {
+ "id": "remesh",
+ "name": "three.ws Remesh",
+ "input": "mesh",
+ "output": "mesh",
+ "params_schema": [
+ {
+ "id": "remesh_mode",
+ "label": "Topology",
+ "type": "select",
+ "default": "quad",
+ "tooltip": "Quad gives clean edge loops for animation and sculpting. Low poly is for games and the web.",
+ "options": [
+ { "value": "quad", "label": "Quads" },
+ { "value": "triangle", "label": "Triangles" },
+ { "value": "lowpoly", "label": "Low poly" }
+ ]
+ },
+ {
+ "id": "operation",
+ "label": "Operation",
+ "type": "select",
+ "default": "full",
+ "tooltip": "Full retopologizes and rebakes textures. Simplify only reduces faces. Repair fixes holes and non-manifold edges.",
+ "options": [
+ { "value": "full", "label": "Retopology + texture bake" },
+ { "value": "simplify", "label": "Simplify" },
+ { "value": "repair", "label": "Repair" }
+ ]
+ },
+ {
+ "id": "target_faces",
+ "label": "Target faces",
+ "type": "int",
+ "default": 8000,
+ "min": 0,
+ "max": 200000,
+ "tooltip": "Face budget for the output. 0 lets the worker choose."
+ },
+ {
+ "id": "texture_size",
+ "label": "Texture size",
+ "type": "select",
+ "default": 1024,
+ "options": [
+ { "value": 512, "label": "512" },
+ { "value": 1024, "label": "1024" },
+ { "value": 2048, "label": "2048" }
+ ]
+ }
+ ]
+ },
+ {
+ "id": "publish",
+ "name": "three.ws Publish",
+ "input": "mesh",
+ "output": "mesh",
+ "params_schema": [
+ {
+ "id": "api_key",
+ "label": "three.ws API key",
+ "type": "string",
+ "default": "",
+ "tooltip": "A key with the avatars:write scope from three.ws/dashboard/api. Prefer the THREE_WS_API_KEY environment variable."
+ },
+ {
+ "id": "name",
+ "label": "Name",
+ "type": "string",
+ "default": "Made in Modly"
+ },
+ {
+ "id": "visibility",
+ "label": "Visibility",
+ "type": "select",
+ "default": "unlisted",
+ "options": [
+ { "value": "unlisted", "label": "Unlisted (link only)" },
+ { "value": "public", "label": "Public" },
+ { "value": "private", "label": "Private" }
+ ]
+ },
+ {
+ "id": "open_page",
+ "label": "Open the page when done",
+ "type": "select",
+ "default": "yes",
+ "options": [
+ { "value": "yes", "label": "Yes" },
+ { "value": "no", "label": "No" }
+ ]
+ }
+ ]
+ }
+ ]
+}
diff --git a/integrations/modly/three-ws/three_ws_client.py b/integrations/modly/three-ws/three_ws_client.py
new file mode 100644
index 000000000..98ad00cd9
--- /dev/null
+++ b/integrations/modly/three-ws/three_ws_client.py
@@ -0,0 +1,721 @@
+"""three.ws Forge client, shared by the Blender add-on, the ComfyUI nodes and the Modly extension.
+
+Single source of truth for the public Forge generation contract
+(``api/forge.js`` + ``api/forge-upload.js``). Stdlib-only (``urllib``) so it
+runs unmodified inside Blender's bundled Python and inside ComfyUI without
+forcing a ``pip install`` into either host.
+
+Public contract this wraps
+---------------------------
+* ``POST /api/forge`` ``{prompt, aspect_ratio?, path?, tier?, backend?}`` → text→3D
+* ``POST /api/forge`` ``{image_urls[], prompt?, path?, tier?, backend?}`` → image→3D
+* ``GET /api/forge?job=<id>`` → poll ``{status, glb_url?, error?, backend?, ...}``
+* ``GET /api/forge?catalog`` → tier/backend/cost matrix
+* ``POST /api/forge-upload`` ``{content_type, size_bytes, checksum_sha256?}`` → presigned PUT
+* ``POST /api/scene-glb-upload`` ``{content_type, size_bytes}`` → presigned PUT for a GLB
+* ``POST /api/forge?action=rig`` ``{glb_url}`` → auto-rig, polled on ``?job=``
+* ``POST /api/forge-remesh`` ``{mesh_url, remesh_mode?, operation?, ...}`` → retopology job
+* ``GET /api/forge-remesh?job=`` → poll ``{status, result_url?, face_count?, error?}``
+* ``POST /api/avatars/upload`` raw GLB body, bearer ``avatars:write`` → ``{storage_key, ...}``
+* ``POST /api/avatars/presign`` ``{size_bytes, content_type, checksum_sha256}`` → presigned PUT (large GLBs)
+* ``POST /api/avatars`` ``{name, storage_key, size_bytes, ...}`` → the saved avatar
+
+Generation is auth-free (IP rate-limited, scoped to an anonymous client handle).
+The geometry path (Meshy/Tripo) is BYOK: pass ``provider_key`` and it travels as
+the ``x-forge-provider-key`` header. Publishing a GLB into an account
+(``publish_glb``) is the one authenticated call: it takes an API key from
+three.ws/dashboard/api carrying the ``avatars:write`` scope.
+
+This file is vendored byte-for-byte into each plugin package; the canonical copy
+lives at ``integrations/_pyclient/three_ws_client.py`` and a drift test keeps the
+vendored copies identical.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import ssl
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+import uuid
+from typing import Callable, Optional
+
+DEFAULT_BASE_URL = "https://three.ws"
+DEFAULT_TIMEOUT = 30.0 # per HTTP request
+DEFAULT_POLL_INTERVAL = 2.0 # seconds between job polls
+DEFAULT_POLL_TIMEOUT = 300.0 # overall ceiling for a generation
+
+# Mirrors api/_lib/forge-tiers.js so the plugins can present choices without a
+# network round-trip. ``get_catalog()`` fetches the live matrix when needed.
+TIERS = ("draft", "standard", "high")
+PATHS = ("image", "geometry", "sketch")
+BACKENDS = (
+ "trellis2",
+ "hunyuan3d",
+ "nvidia",
+ "trellis_selfhost",
+ "huggingface",
+ "trellis",
+ "triposg",
+ "meshy",
+ "tripo",
+ "rodin",
+ "stability",
+ "replicate_byok",
+)
+ASPECT_RATIOS = ("1:1", "4:3", "3:4", "16:9", "9:16")
+AVATAR_VISIBILITIES = ("private", "unlisted", "public")
+REMESH_MODES = ("triangle", "quad", "lowpoly")
+REMESH_OPERATIONS = ("full", "simplify", "repair", "convert")
+REMESH_TEXTURE_SIZES = (512, 1024, 2048)
+MAX_SCENE_GLB_BYTES = 200 * 1024 * 1024
+
+# The upload proxy (``/api/avatars/upload``) accepts bodies up to 50 MB and
+# canonicalizes humanoid bone names at ingest. Anything larger goes through the
+# presigned direct-to-storage path instead.
+MAX_PROXY_UPLOAD_BYTES = 50 * 1024 * 1024
+MAX_AVATAR_BYTES = 500 * 1024 * 1024
+
+_CONTENT_TYPE_BY_EXT = {
+ "png": "image/png",
+ "jpg": "image/jpeg",
+ "jpeg": "image/jpeg",
+ "webp": "image/webp",
+}
+
+
+def _ssl_context() -> ssl.SSLContext:
+ """CA bundle for HTTPS. Embedded Pythons (Blender, Modly, python.org macOS
+ builds) often ship without system roots, so prefer certifi when present."""
+ try:
+ import certifi # type: ignore
+
+ return ssl.create_default_context(cafile=certifi.where())
+ except ImportError:
+ return ssl.create_default_context()
+
+
+_SSL = _ssl_context()
+
+
+def _urlopen(req: urllib.request.Request, timeout: float):
+ if req.full_url.startswith("https://"):
+ return urllib.request.urlopen(req, timeout=timeout, context=_SSL)
+ return urllib.request.urlopen(req, timeout=timeout)
+
+
+class ThreeWSError(Exception):
+ """A Forge request failed. ``message`` is safe to show a user."""
+
+ def __init__(self, message: str, *, code: str = "", status: int = 0):
+ super().__init__(message)
+ self.message = message
+ self.code = code
+ self.status = status
+
+
+def content_type_for_path(path: str) -> str:
+ """Map an image filename to the content-type Forge accepts, or raise."""
+ ext = path.rsplit(".", 1)[-1].lower() if "." in path else ""
+ ct = _CONTENT_TYPE_BY_EXT.get(ext)
+ if not ct:
+ raise ThreeWSError(
+ f"Unsupported image type '.{ext}'. Use PNG, JPEG, or WebP.",
+ code="invalid_content_type",
+ )
+ return ct
+
+
+class ThreeWSClient:
+ """Submit, poll, and download three.ws Forge generations.
+
+ Parameters
+ ----------
+ base_url: deployment origin (default ``https://three.ws``).
+ provider_key: optional Meshy/Tripo key for the BYOK geometry path.
+ client_handle: anonymous handle that scopes creations; generated if omitted.
+ timeout: per-request timeout in seconds.
+ """
+
+ def __init__(
+ self,
+ base_url: str = DEFAULT_BASE_URL,
+ *,
+ provider_key: Optional[str] = None,
+ client_handle: Optional[str] = None,
+ timeout: float = DEFAULT_TIMEOUT,
+ ):
+ self.base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
+ self.provider_key = (provider_key or "").strip() or None
+ self.client_handle = client_handle or uuid.uuid4().hex
+ self.timeout = timeout
+
+ # -- low-level HTTP ------------------------------------------------------
+
+ def _headers(self, extra: Optional[dict] = None) -> dict:
+ headers = {
+ "accept": "application/json",
+ "x-forge-client": self.client_handle,
+ "user-agent": "three-ws-plugin/1.0",
+ }
+ if self.provider_key:
+ headers["x-forge-provider-key"] = self.provider_key
+ if extra:
+ headers.update(extra)
+ return headers
+
+ def _request(
+ self,
+ method: str,
+ path: str,
+ *,
+ body: Optional[dict] = None,
+ raw: Optional[bytes] = None,
+ headers: Optional[dict] = None,
+ timeout: Optional[float] = None,
+ ) -> dict:
+ url = f"{self.base_url}{path}"
+ data = None
+ merged = self._headers(headers)
+ if body is not None:
+ data = json.dumps(body).encode("utf-8")
+ merged["content-type"] = "application/json"
+ elif raw is not None:
+ data = raw
+ req = urllib.request.Request(url, data=data, headers=merged, method=method)
+ try:
+ with _urlopen(req, timeout or self.timeout) as resp:
+ payload = resp.read()
+ except urllib.error.HTTPError as exc:
+ payload = exc.read()
+ parsed = _safe_json(payload)
+ raise ThreeWSError(
+ parsed.get("message") or parsed.get("error") or f"HTTP {exc.code}",
+ code=parsed.get("error", ""),
+ status=exc.code,
+ ) from exc
+ except urllib.error.URLError as exc:
+ raise ThreeWSError(
+ f"Could not reach {self.base_url}: {exc.reason}",
+ code="unreachable",
+ ) from exc
+ return _safe_json(payload)
+
+ # -- catalog -------------------------------------------------------------
+
+ def get_catalog(self) -> dict:
+ """Live tier/backend/cost matrix from ``GET /api/forge?catalog``."""
+ return self._request("GET", "/api/forge?catalog")
+
+ # -- image upload (image→3D needs a public URL) --------------------------
+
+ def upload_image(self, image_bytes: bytes, content_type: str) -> str:
+ """Presign + PUT an image, returning its public URL for image→3D.
+
+ Raises ThreeWSError with actionable guidance if storage is not
+ configured on the deployment (the caller may pass a public URL instead).
+ """
+ if not image_bytes:
+ raise ThreeWSError("Image is empty.", code="invalid_size")
+ checksum = hashlib.sha256(image_bytes).hexdigest()
+ presign = self._request(
+ "POST",
+ "/api/forge-upload",
+ body={
+ "content_type": content_type,
+ "size_bytes": len(image_bytes),
+ "checksum_sha256": checksum,
+ },
+ )
+ return self._put_presigned(presign, image_bytes, content_type, "Image")
+
+ def upload_glb(self, glb_bytes: bytes) -> str:
+ """Presign + PUT a binary glTF, returning its public URL.
+
+ Rigging and remeshing take a public mesh URL, so a mesh that exists only
+ on the caller's disk goes up through ``/api/scene-glb-upload`` first.
+ """
+ if not is_glb(glb_bytes):
+ raise ThreeWSError("Mesh must be a binary glTF 2.0 (.glb) file.", code="invalid_glb")
+ if len(glb_bytes) > MAX_SCENE_GLB_BYTES:
+ raise ThreeWSError("Mesh is larger than the 200 MB upload limit.", code="too_large")
+ presign = self._request(
+ "POST",
+ "/api/scene-glb-upload",
+ body={"content_type": "model/gltf-binary", "size_bytes": len(glb_bytes)},
+ )
+ return self._put_presigned(presign, glb_bytes, "model/gltf-binary", "Mesh")
+
+ def _put_presigned(self, presign: dict, data: bytes, content_type: str, label: str) -> str:
+ upload_url = presign.get("upload_url")
+ public_url = presign.get("public_url")
+ if not upload_url or not public_url:
+ raise ThreeWSError("Upload presign returned no URL.", code="presign_failed")
+ put_headers = presign.get("headers") or {"content-type": content_type}
+ put_req = urllib.request.Request(upload_url, data=data, headers=put_headers, method="PUT")
+ try:
+ with _urlopen(put_req, max(self.timeout, 60)) as resp:
+ resp.read()
+ except urllib.error.HTTPError as exc:
+ raise ThreeWSError(
+ f"{label} upload failed (HTTP {exc.code}).", code="upload_failed", status=exc.code
+ ) from exc
+ except urllib.error.URLError as exc:
+ raise ThreeWSError(f"{label} upload failed: {exc.reason}", code="upload_failed") from exc
+ return public_url
+
+ # -- submit --------------------------------------------------------------
+
+ def submit_text_to_3d(
+ self,
+ prompt: str,
+ *,
+ tier: str = "standard",
+ backend: Optional[str] = None,
+ path: str = "image",
+ aspect_ratio: str = "1:1",
+ ) -> dict:
+ prompt = (prompt or "").strip()
+ if len(prompt) < 3:
+ raise ThreeWSError("Describe one subject in at least 3 characters.", code="invalid_prompt")
+ body = {"prompt": prompt, "tier": tier, "path": path, "aspect_ratio": aspect_ratio}
+ if backend:
+ body["backend"] = backend
+ return self._submit(body)
+
+ def submit_image_to_3d(
+ self,
+ image_urls,
+ *,
+ prompt: str = "",
+ tier: str = "standard",
+ backend: Optional[str] = None,
+ path: str = "image",
+ ) -> dict:
+ if isinstance(image_urls, str):
+ image_urls = [image_urls]
+ image_urls = [u for u in image_urls if isinstance(u, str) and u.startswith("https://")]
+ if not image_urls:
+ raise ThreeWSError("image_to_3d needs at least one public https image URL.", code="invalid_image_urls")
+ body = {"image_urls": image_urls, "tier": tier, "path": path}
+ if prompt.strip():
+ body["prompt"] = prompt.strip()
+ if backend:
+ body["backend"] = backend
+ return self._submit(body)
+
+ def _submit(self, body: dict) -> dict:
+ result = self._request("POST", "/api/forge", body=body)
+ err = result.get("error")
+ if err == "needs_key":
+ raise ThreeWSError(
+ "This backend (Meshy/Tripo) needs your provider API key. "
+ "Set it in the add-on preferences / node input.",
+ code="needs_key",
+ )
+ if err == "backend_unconfigured":
+ raise ThreeWSError(
+ result.get("message") or "That backend is not configured on this deployment.",
+ code="backend_unconfigured",
+ )
+ if err == "unconfigured":
+ raise ThreeWSError(
+ result.get("message") or "Generation is not configured on this deployment.",
+ code="unconfigured",
+ )
+ if err:
+ raise ThreeWSError(result.get("message") or err, code=err)
+ job_id = result.get("job_id")
+ if not job_id:
+ raise ThreeWSError("Forge returned no job id.", code="no_job")
+ return result
+
+ # -- poll ----------------------------------------------------------------
+
+ def poll(
+ self,
+ job_id: str,
+ *,
+ on_progress: Optional[Callable[[str, float], None]] = None,
+ interval: float = DEFAULT_POLL_INTERVAL,
+ timeout: float = DEFAULT_POLL_TIMEOUT,
+ should_cancel: Optional[Callable[[], bool]] = None,
+ _now: Callable[[], float] = time.monotonic,
+ _sleep: Callable[[float], None] = time.sleep,
+ ) -> str:
+ """Block until the job is done; return its GLB URL.
+
+ ``on_progress(status, elapsed_seconds)`` is called each tick. Raises
+ ThreeWSError on failure or timeout. ``should_cancel`` lets a host abort.
+ """
+ return self._poll_until(
+ f"/api/forge?job={urllib.parse.quote(job_id)}",
+ "glb_url",
+ "Generation",
+ on_progress=on_progress,
+ interval=interval,
+ timeout=timeout,
+ should_cancel=should_cancel,
+ _now=_now,
+ _sleep=_sleep,
+ )
+
+ def _poll_until(
+ self,
+ path: str,
+ result_key: str,
+ label: str,
+ *,
+ on_progress: Optional[Callable[[str, float], None]],
+ interval: float,
+ timeout: float,
+ should_cancel: Optional[Callable[[], bool]],
+ _now: Callable[[], float],
+ _sleep: Callable[[float], None],
+ ) -> str:
+ start = _now()
+ while True:
+ if should_cancel and should_cancel():
+ raise ThreeWSError(f"{label} cancelled.", code="cancelled")
+ elapsed = _now() - start
+ if elapsed > timeout:
+ raise ThreeWSError(f"{label} timed out after {int(elapsed)}s.", code="timeout")
+ try:
+ result = self._request("GET", path)
+ except ThreeWSError as exc:
+ # A 502/503/504 on a poll is a transient upstream hiccup (the
+ # remesh worker answers 502 while it cold-starts); keep polling.
+ if exc.status in (502, 503, 504):
+ _sleep(interval)
+ continue
+ raise
+ status = result.get("status") or "running"
+ if on_progress:
+ on_progress(status, elapsed)
+ if status == "done" and result.get(result_key):
+ return result[result_key]
+ if status == "failed":
+ raise ThreeWSError(result.get("error") or f"{label} failed.", code="failed")
+ _sleep(interval)
+
+ # -- rig -----------------------------------------------------------------
+
+ def submit_rig(self, glb_url: str) -> dict:
+ """Start auto-rigging a public GLB; returns ``{job_id, ...}``."""
+ if not _is_web_url(glb_url):
+ raise ThreeWSError("Rigging needs a public GLB URL.", code="invalid_glb_url")
+ result = self._request("POST", "/api/forge?action=rig", body={"glb_url": glb_url})
+ if result.get("error"):
+ raise ThreeWSError(result.get("message") or result["error"], code=result["error"])
+ if not result.get("job_id"):
+ raise ThreeWSError("The rigger returned no job id.", code="no_job")
+ return result
+
+ def rig(
+ self,
+ glb_url: str,
+ *,
+ on_progress: Optional[Callable[[str, float], None]] = None,
+ should_cancel: Optional[Callable[[], bool]] = None,
+ poll_timeout: float = 600.0,
+ _now: Callable[[], float] = time.monotonic,
+ _sleep: Callable[[float], None] = time.sleep,
+ ) -> str:
+ """Auto-rig a GLB with a humanoid skeleton; return the rigged GLB URL."""
+ job = self.submit_rig(glb_url)
+ return self._poll_until(
+ f"/api/forge?job={urllib.parse.quote(job['job_id'])}",
+ "glb_url",
+ "Rigging",
+ on_progress=on_progress,
+ interval=DEFAULT_POLL_INTERVAL,
+ timeout=poll_timeout,
+ should_cancel=should_cancel,
+ _now=_now,
+ _sleep=_sleep,
+ )
+
+ # -- remesh --------------------------------------------------------------
+
+ def submit_remesh(
+ self,
+ mesh_url: str,
+ *,
+ remesh_mode: str = "triangle",
+ operation: str = "full",
+ target_faces: Optional[int] = None,
+ texture_size: int = 1024,
+ ) -> dict:
+ """Start a remesh/retopology job on a public GLB; returns ``{job_id, ...}``."""
+ if not _is_web_url(mesh_url):
+ raise ThreeWSError("Remeshing needs a public mesh URL.", code="invalid_mesh_url")
+ if remesh_mode not in REMESH_MODES:
+ raise ThreeWSError(
+ f"remesh_mode must be one of: {', '.join(REMESH_MODES)}.", code="invalid_mode"
+ )
+ if operation not in REMESH_OPERATIONS:
+ raise ThreeWSError(
+ f"operation must be one of: {', '.join(REMESH_OPERATIONS)}.", code="invalid_operation"
+ )
+ if texture_size not in REMESH_TEXTURE_SIZES:
+ raise ThreeWSError("texture_size must be 512, 1024 or 2048.", code="invalid_texture_size")
+ body = {
+ "mesh_url": mesh_url,
+ "remesh_mode": remesh_mode,
+ "operation": operation,
+ "texture_size": texture_size,
+ "output_format": "glb",
+ }
+ if target_faces and int(target_faces) > 0:
+ body["target_faces"] = int(target_faces)
+ result = self._request("POST", "/api/forge-remesh", body=body)
+ if result.get("error"):
+ raise ThreeWSError(result.get("message") or result["error"], code=result["error"])
+ if not result.get("job_id"):
+ raise ThreeWSError("Mesh processing returned no job id.", code="no_job")
+ return result
+
+ def remesh(
+ self,
+ mesh_url: str,
+ *,
+ remesh_mode: str = "triangle",
+ operation: str = "full",
+ target_faces: Optional[int] = None,
+ texture_size: int = 1024,
+ on_progress: Optional[Callable[[str, float], None]] = None,
+ should_cancel: Optional[Callable[[], bool]] = None,
+ poll_timeout: float = 900.0,
+ _now: Callable[[], float] = time.monotonic,
+ _sleep: Callable[[float], None] = time.sleep,
+ ) -> str:
+ """Remesh a GLB on the remesh worker; return the processed GLB URL."""
+ job = self.submit_remesh(
+ mesh_url,
+ remesh_mode=remesh_mode,
+ operation=operation,
+ target_faces=target_faces,
+ texture_size=texture_size,
+ )
+ return self._poll_until(
+ f"/api/forge-remesh?job={urllib.parse.quote(job['job_id'])}",
+ "result_url",
+ "Mesh processing",
+ on_progress=on_progress,
+ interval=DEFAULT_POLL_INTERVAL,
+ timeout=poll_timeout,
+ should_cancel=should_cancel,
+ _now=_now,
+ _sleep=_sleep,
+ )
+
+ # -- download ------------------------------------------------------------
+
+ def download(self, url: str, dest_path: str) -> str:
+ """Stream a GLB (or any URL) to ``dest_path``; return the path."""
+ req = urllib.request.Request(url, headers={"user-agent": "three-ws-plugin/1.0"})
+ try:
+ with _urlopen(req, max(self.timeout, 120)) as resp, open(
+ dest_path, "wb"
+ ) as out:
+ while True:
+ chunk = resp.read(64 * 1024)
+ if not chunk:
+ break
+ out.write(chunk)
+ except (urllib.error.HTTPError, urllib.error.URLError) as exc:
+ raise ThreeWSError(f"Download failed: {exc}", code="download_failed") from exc
+ return dest_path
+
+ # -- publish into an account --------------------------------------------
+
+ def publish_glb(
+ self,
+ glb_bytes: bytes,
+ *,
+ api_key: str,
+ name: str,
+ description: str = "",
+ visibility: str = "private",
+ tags=(),
+ source_meta: Optional[dict] = None,
+ ) -> dict:
+ """Save a GLB into the API key owner's three.ws account; return the avatar.
+
+ The returned dict is the ``avatar`` object from ``POST /api/avatars``
+ (``id``, ``name``, ``slug``, ``visibility``, ...). Its page lives at
+ ``avatar_page_url(avatar)``. Static meshes are auto-rigged server-side
+ when they are humanoid, exactly like a dashboard upload.
+ """
+ api_key = (api_key or "").strip()
+ if not api_key:
+ raise ThreeWSError(
+ "Publishing needs a three.ws API key with the avatars:write scope. "
+ "Create one at three.ws/dashboard/api.",
+ code="missing_api_key",
+ )
+ name = (name or "").strip()[:120] or "Untitled model"
+ if visibility not in AVATAR_VISIBILITIES:
+ raise ThreeWSError(
+ f"visibility must be one of: {', '.join(AVATAR_VISIBILITIES)}.",
+ code="invalid_visibility",
+ )
+ if not is_glb(glb_bytes):
+ raise ThreeWSError(
+ "That file is not a binary glTF 2.0 (.glb). Export the mesh as GLB first.",
+ code="invalid_glb",
+ )
+ if len(glb_bytes) > MAX_AVATAR_BYTES:
+ raise ThreeWSError("GLB is larger than the 500 MB account limit.", code="too_large")
+
+ auth = {"authorization": f"Bearer {api_key}"}
+ checksum = hashlib.sha256(glb_bytes).hexdigest()
+ slug = slugify(name)
+ if len(glb_bytes) <= MAX_PROXY_UPLOAD_BYTES:
+ query = urllib.parse.urlencode(
+ {"slug": slug, "content_type": "model/gltf-binary", "sha256": checksum}
+ )
+ stored = self._request(
+ "POST",
+ f"/api/avatars/upload?{query}",
+ raw=glb_bytes,
+ headers={**auth, "content-type": "model/gltf-binary"},
+ timeout=max(self.timeout, 120),
+ )
+ storage_key = stored.get("storage_key")
+ size_bytes = stored.get("size_bytes") or len(glb_bytes)
+ checksum = stored.get("checksum_sha256") or checksum
+ else:
+ presign = self._request(
+ "POST",
+ "/api/avatars/presign",
+ body={
+ "size_bytes": len(glb_bytes),
+ "content_type": "model/gltf-binary",
+ "checksum_sha256": checksum,
+ "slug": slug,
+ },
+ headers=auth,
+ )
+ storage_key = presign.get("storage_key")
+ upload_url = presign.get("upload_url")
+ if not storage_key or not upload_url:
+ raise ThreeWSError("Upload presign returned no URL.", code="presign_failed")
+ put_headers = presign.get("headers") or {"content-type": "model/gltf-binary"}
+ put_req = urllib.request.Request(
+ upload_url, data=glb_bytes, headers=put_headers, method="PUT"
+ )
+ try:
+ with _urlopen(put_req, max(self.timeout, 600)) as resp:
+ resp.read()
+ except urllib.error.HTTPError as exc:
+ raise ThreeWSError(
+ f"GLB upload failed (HTTP {exc.code}).", code="upload_failed", status=exc.code
+ ) from exc
+ except urllib.error.URLError as exc:
+ raise ThreeWSError(f"GLB upload failed: {exc.reason}", code="upload_failed") from exc
+ size_bytes = len(glb_bytes)
+ if not storage_key:
+ raise ThreeWSError("Upload returned no storage key.", code="upload_failed")
+
+ body = {
+ "name": name,
+ "storage_key": storage_key,
+ "size_bytes": size_bytes,
+ "content_type": "model/gltf-binary",
+ "checksum_sha256": checksum,
+ "visibility": visibility,
+ "tags": [t.strip()[:40] for t in tags if isinstance(t, str) and t.strip()][:20],
+ "source": "upload",
+ "source_meta": dict(source_meta or {}),
+ }
+ if description.strip():
+ body["description"] = description.strip()[:2000]
+ created = self._request("POST", "/api/avatars", body=body, headers=auth)
+ avatar = created.get("avatar")
+ if not isinstance(avatar, dict) or not avatar.get("id"):
+ raise ThreeWSError("three.ws did not return the saved model.", code="create_failed")
+ return avatar
+
+ def avatar_page_url(self, avatar: dict) -> str:
+ """Public page for an avatar returned by ``publish_glb``."""
+ return f"{self.base_url}/avatars/{urllib.parse.quote(str(avatar.get('id', '')))}"
+
+ # -- high-level convenience ---------------------------------------------
+
+ def generate_text_to_3d(
+ self,
+ prompt: str,
+ *,
+ tier: str = "standard",
+ backend: Optional[str] = None,
+ path: str = "image",
+ aspect_ratio: str = "1:1",
+ on_progress: Optional[Callable[[str, float], None]] = None,
+ should_cancel: Optional[Callable[[], bool]] = None,
+ poll_timeout: float = DEFAULT_POLL_TIMEOUT,
+ ) -> str:
+ job = self.submit_text_to_3d(
+ prompt, tier=tier, backend=backend, path=path, aspect_ratio=aspect_ratio
+ )
+ return self.poll(
+ job["job_id"], on_progress=on_progress, should_cancel=should_cancel, timeout=poll_timeout
+ )
+
+ def generate_image_to_3d(
+ self,
+ image_bytes: bytes,
+ content_type: str,
+ *,
+ prompt: str = "",
+ tier: str = "standard",
+ backend: Optional[str] = None,
+ path: str = "image",
+ on_progress: Optional[Callable[[str, float], None]] = None,
+ should_cancel: Optional[Callable[[], bool]] = None,
+ poll_timeout: float = DEFAULT_POLL_TIMEOUT,
+ ) -> str:
+ public_url = self.upload_image(image_bytes, content_type)
+ job = self.submit_image_to_3d(public_url, prompt=prompt, tier=tier, backend=backend, path=path)
+ return self.poll(
+ job["job_id"], on_progress=on_progress, should_cancel=should_cancel, timeout=poll_timeout
+ )
+
+
+def is_glb(data: bytes) -> bool:
+ """True when ``data`` starts with a well-formed binary glTF 2.0 header."""
+ if not isinstance(data, (bytes, bytearray)) or len(data) < 12:
+ return False
+ magic = bytes(data[0:4])
+ version = int.from_bytes(data[4:8], "little")
+ length = int.from_bytes(data[8:12], "little")
+ return magic == b"glTF" and version == 2 and length == len(data)
+
+
+def slugify(text: str) -> str:
+ """Lowercase ``[a-z0-9_-]`` slug (max 64) that ``/api/avatars`` accepts."""
+ out = []
+ for ch in (text or "").lower():
+ if ch.isascii() and (ch.isalnum() or ch in "-_"):
+ out.append(ch)
+ elif out and out[-1] != "-":
+ out.append("-")
+ slug = "".join(out).strip("-_")[:64].strip("-_")
+ return slug or "model"
+
+
+def _is_web_url(url) -> bool:
+ """An http(s) URL. The server decides what is publicly reachable (it
+ SSRF-checks every mesh URL); this only stops local paths early."""
+ return isinstance(url, str) and url.startswith(("https://", "http://"))
+
+
+def _safe_json(payload: bytes) -> dict:
+ try:
+ parsed = json.loads(payload.decode("utf-8"))
+ return parsed if isinstance(parsed, dict) else {"value": parsed}
+ except (ValueError, UnicodeDecodeError):
+ return {}
diff --git a/pages/features.html b/pages/features.html
index dad7d00f9..39b1712a9 100644
--- a/pages/features.html
+++ b/pages/features.html
@@ -608,6 +608,9 @@
<a href="/forge" class="btn-primary feat-card-cta" data-i18n-html="features.open_forge">
Open Forge <span class="btn-arrow">→</span>
</a>
+ <p class="feat-card-who">
+ Have a graphics card? <a href="/modly">Generate on your own GPU with Modly</a>, free and private.
+ </p>
</div>
</article>
diff --git a/pages/modly.html b/pages/modly.html
new file mode 100644
index 000000000..f61c04b8b
--- /dev/null
+++ b/pages/modly.html
@@ -0,0 +1,363 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <script>/* three.ws theme boot: no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+ <title>Modly on three.ws · Image to 3D on your own GPU · three.ws</title>
+ <meta name="description" content="Everything Modly on three.ws. Detect the free, open-source Modly app on your computer, generate 3D from an image or a prompt on your own GPU, clean the mesh and save it to your account, plus the Forge GPU lane, the three.ws Forge desktop app and the Modly extensions." />
+ <link rel="canonical" href="https://three.ws/modly" />
+ <meta property="og:type" content="website" />
+ <meta property="og:title" content="Modly on three.ws" />
+ <meta property="og:description" content="Image or prompt to 3D on your own graphics card, free and private. Preview, repair and save to three.ws from the browser." />
+ <meta property="og:url" content="https://three.ws/modly" />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&amp;t=Modly+on+three.ws&amp;d=Image+or+prompt+to+3D+on+your+own+graphics+card%2C+free+and+private.&amp;p=%2Fmodly" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:title" content="Modly on three.ws" />
+ <meta name="twitter:description" content="Image or prompt to 3D on your own graphics card, free and private. Preview, repair and save to three.ws from the browser." />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&amp;t=Modly+on+three.ws&amp;d=Image+or+prompt+to+3D+on+your+own+graphics+card%2C+free+and+private.&amp;p=%2Fmodly" />
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:locale" content="en_US" />
+ <meta property="og:image:alt" content="Modly on three.ws" />
+ <meta name="twitter:site" content="@trythreews" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/mobile.css" />
+ <link rel="stylesheet" href="/src/modly-page.css" />
+ <script src="/model-viewer-meshopt.js" defer></script>
+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebApplication","name":"Modly on three.ws","applicationCategory":"DesignApplication","operatingSystem":"Windows, macOS, Linux","description":"Image or text prompt to 3D on your own GPU through the open-source Modly app, with preview, mesh repair and saving to three.ws.","url":"https://three.ws/modly","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"offers":{"@type":"Offer","price":"0","priceCurrency":"USD"}}]}</script>
+</head>
+<body class="md-body">
+ <header class="site-header"><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="md">
+ <section class="md-hero" aria-labelledby="mdTitle">
+ <p class="md-eyebrow"><span class="md-eyebrow__mark" aria-hidden="true"></span>Modly on three.ws</p>
+ <h1 id="mdTitle">Make 3D on your own graphics card.</h1>
+ <p class="md-lede">Modly is a free, open-source app that turns images into 3D models on your own GPU. three.ws connects to it straight from this page: your image never leaves your machine, there is no queue and no quota, and the finished model comes back here to preview, clean up and save. <a href="#md-ways">See every way to use Modly with three.ws</a>.</p>
+ <p class="md-credit">Based on <a href="https://github.com/lightningpixel/modly" rel="noopener" target="_blank">Modly by Lightning Pixel</a> (MIT license).</p>
+ </section>
+
+ <!-- Connection to the local Modly server -->
+ <section id="mdConn" class="md-conn" data-state="idle" aria-labelledby="mdConnTitle">
+ <div class="md-conn__head">
+ <h2 id="mdConnTitle" class="md-h2"><span class="md-dot" aria-hidden="true"></span><span id="mdConnStatus">Not connected</span></h2>
+ <form id="mdBaseForm" class="md-base" autocomplete="off" novalidate>
+ <label for="mdBase" class="md-base__label">Modly address</label>
+ <input id="mdBase" class="md-input md-input--mono" type="text" inputmode="url" spellcheck="false" placeholder="http://127.0.0.1:8765" aria-describedby="mdBaseHint" />
+ <button id="mdConnect" type="submit" class="md-btn md-btn--primary">
+ <span class="md-btn__label">Connect</span>
+ <span class="md-btn__spinner" aria-hidden="true"></span>
+ </button>
+ </form>
+ </div>
+ <p id="mdBaseHint" class="md-hint">Leave it empty to use Modly's default port, <code>8765</code> on this computer. Only fill it in if you changed the port.</p>
+ <p id="mdBaseError" class="md-field-error" role="alert" hidden></p>
+
+ <div class="md-conn__body" aria-live="polite">
+ <div class="md-panel" data-for="idle">
+ <p>Connect to check whether Modly is running on this computer. Your browser may ask whether three.ws can reach apps on your device: allow it, since that is exactly the connection being made.</p>
+ </div>
+
+ <div class="md-panel" data-for="probing">
+ <div class="md-skel-line" aria-hidden="true"></div>
+ <div class="md-skel-line md-skel-line--short" aria-hidden="true"></div>
+ <p class="md-sr" id="mdProbingText">Looking for Modly.</p>
+ </div>
+
+ <div class="md-panel" data-for="not-running">
+ <p class="md-panel__lead"><strong>Modly is not running on this computer.</strong> Install it once, start it, and connect again.</p>
+ <ol class="md-steps">
+ <li><span class="md-steps__n" aria-hidden="true">1</span><div><strong>Download Modly</strong> for Windows, Linux or Apple Silicon macOS from <a id="mdInstallLink" href="https://modly3d.app/" rel="noopener" target="_blank">modly3d.app</a> or its <a href="https://github.com/lightningpixel/modly/releases/latest" rel="noopener" target="_blank">latest GitHub release</a>.</div></li>
+ <li><span class="md-steps__n" aria-hidden="true">2</span><div><strong>Open the app.</strong> It starts its local server on port 8765 in the background. Keep it open while you work here.</div></li>
+ <li><span class="md-steps__n" aria-hidden="true">3</span><div><strong>Add a model</strong> from Modly's Models page with <em>Install from GitHub</em>. You can also do this after connecting; this page lists the official ones.</div></li>
+ </ol>
+ <p class="md-hint">Already running? Check that the address above matches Modly's port, and that your browser lets this site reach apps on your device (Chrome and Edge ask once; Brave has a per-site setting for it).</p>
+ <button type="button" class="md-btn" data-action="retry">Retry</button>
+ </div>
+
+ <div class="md-panel" data-for="blocked">
+ <div data-reason="lna-denied">
+ <p class="md-panel__lead"><strong>Your browser blocked the connection to your computer.</strong> This site was refused access to apps on your device earlier.</p>
+ <ol class="md-steps">
+ <li><span class="md-steps__n" aria-hidden="true">1</span><div>Click the site settings icon at the left of the address bar.</div></li>
+ <li><span class="md-steps__n" aria-hidden="true">2</span><div>Set <strong>Local network access</strong> for three.ws to <strong>Allow</strong>.</div></li>
+ <li><span class="md-steps__n" aria-hidden="true">3</span><div>Press Retry. Modly only answers on your own machine, so nothing on your network is exposed.</div></li>
+ </ol>
+ </div>
+ <div data-reason="mixed-content">
+ <p class="md-panel__lead"><strong>Safari does not let secure pages reach apps on your computer.</strong> It treats Modly's local <code>http://</code> address as insecure content and blocks it, with no setting to allow it.</p>
+ <p>Open <strong>three.ws/modly</strong> in Chrome, Edge or Firefox on this Mac, or use the <a href="#md-way-desktop">three.ws Forge desktop app</a>. Modly itself works the same either way.</p>
+ </div>
+ <button type="button" class="md-btn" data-action="retry">Retry</button>
+ </div>
+
+ <div class="md-panel md-panel--ok" data-for="connected">
+ <p><strong>Connected to Modly</strong> <span id="mdConnOrigin" class="md-muted md-mono"></span></p>
+ <p class="md-hint" id="mdConnSummary"></p>
+ </div>
+ </div>
+ </section>
+
+ <!-- Studio, shown once connected -->
+ <section id="mdStudio" class="md-studio" hidden aria-label="Local generation studio">
+ <div class="md-col md-col--controls">
+ <!-- Models -->
+ <section class="md-card" aria-labelledby="mdModelsTitle">
+ <div class="md-card__head">
+ <h2 id="mdModelsTitle" class="md-h3">Model</h2>
+ <div class="md-card__actions">
+ <button type="button" id="mdRefreshModels" class="md-btn md-btn--ghost md-btn--sm">
+ <span class="md-btn__label">Refresh</span>
+ <span class="md-btn__spinner" aria-hidden="true"></span>
+ </button>
+ </div>
+ </div>
+ <div id="mdModelsLoading" class="md-skel-list" aria-hidden="true">
+ <div class="md-skel-card"></div>
+ <div class="md-skel-card"></div>
+ </div>
+ <div id="mdModelsEmpty" class="md-empty" hidden>
+ <p class="md-panel__lead"><strong>No models installed in Modly yet.</strong> Modly runs models as extensions. Add one, then press Refresh.</p>
+ <ol class="md-steps md-steps--compact">
+ <li><span class="md-steps__n" aria-hidden="true">1</span><div>In Modly, open <strong>Models</strong> and click <strong>Install from GitHub</strong>.</div></li>
+ <li><span class="md-steps__n" aria-hidden="true">2</span><div>Paste one of the repository links below and confirm.</div></li>
+ <li><span class="md-steps__n" aria-hidden="true">3</span><div>Download the model weights when Modly offers to. Or skip this: the first generation downloads them.</div></li>
+ </ol>
+ <ul id="mdExtList" class="md-ext-list"></ul>
+ <p class="md-hint">No GPU to spare? The <a href="#md-way-cloud">three.ws Cloud extension</a> adds hosted generators to Modly that need no weights at all.</p>
+ </div>
+ <div id="mdModelsError" class="md-alert md-alert--error" role="alert" hidden></div>
+ <div id="mdModelList" class="md-model-list" role="radiogroup" aria-labelledby="mdModelsTitle" hidden></div>
+ <div id="mdParams" class="md-params" hidden>
+ <h3 class="md-h4">Model settings</h3>
+ <div id="mdParamsForm" class="md-form"></div>
+ </div>
+ </section>
+
+ <!-- Input -->
+ <section class="md-card" aria-labelledby="mdInputTitle">
+ <div class="md-card__head">
+ <h2 id="mdInputTitle" class="md-h3">Input</h2>
+ <div class="md-tabs" role="tablist" aria-label="Input type">
+ <button type="button" role="tab" id="mdTabImage" aria-controls="mdPaneImage" aria-selected="true" class="md-tab">Image</button>
+ <button type="button" role="tab" id="mdTabPrompt" aria-controls="mdPanePrompt" aria-selected="false" class="md-tab" tabindex="-1">Text prompt</button>
+ </div>
+ </div>
+
+ <div id="mdPaneImage" role="tabpanel" aria-labelledby="mdTabImage" class="md-pane">
+ <div id="mdDrop" class="md-drop" tabindex="0" role="button" aria-describedby="mdDropHint">
+ <input id="mdFile" type="file" accept="image/png,image/jpeg,image/webp" class="md-sr" tabindex="-1" />
+ <img id="mdDropImg" class="md-drop__img" alt="" hidden />
+ <div class="md-drop__empty" id="mdDropEmpty">
+ <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="3"/><circle cx="8.5" cy="9" r="1.6"/><path d="m21 15-4.5-4.5L6 21"/></svg>
+ <strong>Drop an image, paste one, or click to choose</strong>
+ <span id="mdDropHint" class="md-hint">One object, plain background, PNG, JPEG or WebP.</span>
+ </div>
+ </div>
+ <div class="md-drop__meta" id="mdDropMeta" hidden>
+ <span id="mdDropName" class="md-muted"></span>
+ <button type="button" id="mdClearImage" class="md-btn md-btn--ghost md-btn--sm">Remove</button>
+ </div>
+ </div>
+
+ <div id="mdPanePrompt" role="tabpanel" aria-labelledby="mdTabPrompt" class="md-pane" hidden>
+ <label for="mdPrompt" class="md-label">Describe one object</label>
+ <textarea id="mdPrompt" class="md-input" rows="3" maxlength="1000" placeholder="A weathered bronze robot owl, standing, full body"></textarea>
+ <div class="md-row">
+ <span class="md-hint">three.ws draws a concept image first, then Modly turns it into 3D on your GPU. <kbd>Ctrl</kbd> <kbd>Enter</kbd></span>
+ <button type="button" id="mdConcept" class="md-btn">
+ <span class="md-btn__label">Draw concept</span>
+ <span class="md-btn__spinner" aria-hidden="true"></span>
+ </button>
+ </div>
+ <div id="mdConceptError" class="md-alert md-alert--error" role="alert" hidden></div>
+ </div>
+
+ <div class="md-generate">
+ <button type="button" id="mdGenerate" class="md-btn md-btn--primary md-btn--wide" disabled>
+ <span class="md-btn__label">Generate on my GPU</span>
+ </button>
+ <p id="mdGenerateHint" class="md-hint" aria-live="polite">Pick a model and add an image.</p>
+ </div>
+ </section>
+
+ <!-- Open an existing workspace file -->
+ <details class="md-card md-details" id="mdOpenCard">
+ <summary class="md-h3">Open from your Modly workspace</summary>
+ <form id="mdOpenForm" class="md-form" autocomplete="off" novalidate>
+ <p class="md-hint" id="mdOpenHint">Bring in a GLB you already made in Modly. Paths are relative to Modly's workspace folder, for example <code>Default/model.glb</code>.</p>
+ <div class="md-row">
+ <label for="mdOpenPath" class="md-sr">Workspace path</label>
+ <input id="mdOpenPath" class="md-input md-input--mono" type="text" spellcheck="false" placeholder="Default/model.glb" />
+ <button type="submit" class="md-btn">Open</button>
+ </div>
+ <p id="mdOpenError" class="md-field-error" role="alert" hidden></p>
+ </form>
+ </details>
+ </div>
+
+ <div class="md-col md-col--stage">
+ <section class="md-stage" id="mdStage" data-stage="empty" aria-label="3D preview">
+ <div class="md-stage__view">
+ <div class="md-stage__empty" data-for="empty">
+ <svg width="56" height="56" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 2 3 7v10l9 5 9-5V7z"/><path d="m3 7 9 5 9-5M12 12v10"/></svg>
+ <p><strong>Your model appears here.</strong></p>
+ <p class="md-hint">Generate one on the left, or open a GLB from your Modly workspace.</p>
+ </div>
+ <div class="md-stage__progress" data-for="generating">
+ <p class="md-stage__step" id="mdStep">Sending your image to Modly</p>
+ <div class="md-progress" role="progressbar" aria-labelledby="mdStep" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" id="mdProgress">
+ <span class="md-progress__bar" id="mdProgressBar"></span>
+ </div>
+ <p class="md-muted"><span id="mdPct">0%</span> · <span id="mdElapsed">0:00</span></p>
+ <button type="button" id="mdCancel" class="md-btn">Cancel</button>
+ </div>
+ <div class="md-stage__loading" data-for="loading">
+ <div class="md-spinner" aria-hidden="true"></div>
+ <p id="mdLoadingText">Loading the model</p>
+ </div>
+ <div class="md-stage__error" data-for="error" role="alert">
+ <p class="md-panel__lead"><strong id="mdStageErrorTitle">Something went wrong</strong></p>
+ <p id="mdStageErrorText"></p>
+ <details class="md-details" id="mdStageErrorDetail" hidden>
+ <summary>Technical details</summary>
+ <pre class="md-pre" id="mdStageErrorPre"></pre>
+ </details>
+ <div class="md-row md-row--start">
+ <button type="button" id="mdStageRetry" class="md-btn md-btn--primary">Try again</button>
+ <button type="button" id="mdStageDismiss" class="md-btn md-btn--ghost">Dismiss</button>
+ </div>
+ </div>
+ <div class="md-stage__viewer" id="mdViewerHost" data-for="ready"></div>
+ </div>
+ <div class="md-stage__meta" id="mdMeta" hidden>
+ <span id="mdMetaPath" class="md-mono"></span>
+ <span id="mdMetaStats" class="md-muted"></span>
+ </div>
+ </section>
+
+ <div id="mdResult" class="md-result" hidden>
+ <!-- Mesh tools -->
+ <section class="md-card" aria-labelledby="mdToolsTitle">
+ <div class="md-card__head">
+ <h2 id="mdToolsTitle" class="md-h3">Clean up the mesh</h2>
+ <button type="button" id="mdUndo" class="md-btn md-btn--ghost md-btn--sm" disabled>Undo</button>
+ </div>
+ <p class="md-hint">Runs in Modly on your machine. Each step writes a new file, so Undo goes back to the previous one.</p>
+ <div id="mdOps" class="md-ops"></div>
+ <div id="mdOpsError" class="md-alert md-alert--error" role="alert" hidden></div>
+ </section>
+
+ <!-- Export + save -->
+ <section class="md-card" aria-labelledby="mdExportTitle">
+ <h2 id="mdExportTitle" class="md-h3">Download</h2>
+ <div class="md-export">
+ <button type="button" class="md-btn" id="mdDownload">Download GLB</button>
+ </div>
+ <p class="md-hint">The file is also in your Modly workspace, at the path shown under the preview.</p>
+ </section>
+
+ <section class="md-card" aria-labelledby="mdSaveTitle" id="mdSaveCard">
+ <h2 id="mdSaveTitle" class="md-h3">Save to my three.ws account</h2>
+ <form id="mdSaveForm" class="md-form" autocomplete="off" novalidate>
+ <div class="md-field">
+ <label for="mdSaveName" class="md-label">Name</label>
+ <input id="mdSaveName" class="md-input" type="text" maxlength="120" required />
+ </div>
+ <div class="md-field">
+ <label for="mdSaveVis" class="md-label">Visibility</label>
+ <select id="mdSaveVis" class="md-input">
+ <option value="private">Private: only you</option>
+ <option value="unlisted">Unlisted: anyone with the link</option>
+ <option value="public">Public: listed on three.ws</option>
+ </select>
+ </div>
+ <button type="submit" id="mdSave" class="md-btn md-btn--primary">
+ <span class="md-btn__label">Save to my account</span>
+ <span class="md-btn__spinner" aria-hidden="true"></span>
+ </button>
+ <div class="md-progress md-progress--thin" id="mdSaveProgress" role="progressbar" aria-label="Upload progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" hidden>
+ <span class="md-progress__bar" id="mdSaveProgressBar"></span>
+ </div>
+ </form>
+ <div id="mdSaveSignedOut" class="md-alert" hidden>
+ <p>Sign in to keep this model in your three.ws library. You will come straight back here and the save finishes on its own.</p>
+ <a id="mdSignIn" class="md-btn md-btn--primary" href="/login?next=%2Fmodly">Sign in to save</a>
+ </div>
+ <div id="mdSaveDone" class="md-alert md-alert--ok" role="status" hidden>
+ <p><strong>Saved.</strong> It is in your library now.</p>
+ <a id="mdSaveLink" class="md-btn md-btn--primary" href="/dashboard">Open the model page</a>
+ </div>
+ <p id="mdSaveError" class="md-field-error" role="alert" hidden></p>
+ </section>
+ </div>
+ </div>
+ </section>
+
+ <section id="md-ways" class="md-ways" aria-labelledby="mdWaysTitle">
+ <div class="md-ways__head">
+ <h2 id="mdWaysTitle" class="md-h2">Every way to use Modly with three.ws</h2>
+ <p>This page is the quickest route: a browser tab talking to Modly on your machine. When you want more, pick the surface that fits how you work.</p>
+ </div>
+ <ul class="md-ways__grid">
+ <li class="md-way" id="md-way-forge">
+ <span class="md-way__icon" aria-hidden="true"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="4" width="16" height="16" rx="2"/><path d="M9 9h6v6H9zM9 1v3M15 1v3M9 20v3M15 20v3M20 9h3M20 14h3M1 9h3M1 14h3"/></svg></span>
+ <p class="md-way__kind">In the browser</p>
+ <h3 class="md-h3">Forge, Your GPU lane</h3>
+ <p>Forge is the full three.ws generation studio. Its <strong>Your GPU (Modly)</strong> lane sits beside the cloud lanes, so you can pick your own card or three.ws servers job by job, with history and the rest of the Forge tools around it.</p>
+ <div class="md-way__actions"><a class="md-btn md-btn--primary" href="/forge">Open Forge</a></div>
+ </li>
+ <li class="md-way" id="md-way-desktop">
+ <span class="md-way__icon" aria-hidden="true"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="20" height="13" rx="2"/><path d="M8 21h8M12 17v4"/></svg></span>
+ <p class="md-way__kind">Desktop app</p>
+ <h3 class="md-h3">three.ws Forge for desktop</h3>
+ <p>A desktop studio built on Modly with three.ws inside it: local open-source generators and the three.ws cloud side by side, node-based mesh workflows, and your three.ws account signed in.</p>
+ <ul class="md-way__points">
+ <li>Windows, Linux and Apple Silicon macOS.</li>
+ <li>The Publish to three.ws node comes built in.</li>
+ <li>No browser permission prompts, works in every browser setup.</li>
+ </ul>
+ <div class="md-way__actions"><a class="md-btn" href="https://github.com/nirholas/three.ws/tree/main/apps/forge-desktop" rel="noopener" target="_blank">Source and build guide</a></div>
+ </li>
+ <li class="md-way" id="md-way-cloud">
+ <span class="md-way__icon" aria-hidden="true"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M17.5 19H8a5 5 0 1 1 1.4-9.8A6 6 0 0 1 21 11.5 3.8 3.8 0 0 1 17.5 19z"/></svg></span>
+ <p class="md-way__kind">Modly extension</p>
+ <h3 class="md-h3">three.ws Cloud generator</h3>
+ <p>Adds three.ws Forge to Modly's model list. No GPU, no weights, no setup: image, text and sketch to 3D on hosted lanes, plus a humanoid auto-rigger and a quad remesher, all as Modly nodes.</p>
+ <ul class="md-way__points">
+ <li>Install: clone the folder, then <em>Link local folder</em> on Modly's Models page.</li>
+ <li>Once linked it shows up here too, in the model list above.</li>
+ </ul>
+ <div class="md-way__actions"><a class="md-btn" href="https://github.com/nirholas/three.ws/tree/main/integrations/modly/three-ws" rel="noopener" target="_blank">Get the extension</a></div>
+ </li>
+ <li class="md-way" id="md-way-publish">
+ <span class="md-way__icon" aria-hidden="true"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 16V4M7 9l5-5 5 5"/><path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3"/></svg></span>
+ <p class="md-way__kind">Modly workflow node</p>
+ <h3 class="md-h3">Publish to three.ws</h3>
+ <p>A process node that saves any mesh flowing through a Modly workflow into your three.ws account, where it gets a shareable 3D page, an embed and an AI agent. Humanoid meshes are auto-rigged.</p>
+ <ul class="md-way__points">
+ <li>Needs an API key with the <code>avatars:write</code> scope from <a href="/dashboard/api">your API keys</a>.</li>
+ <li>Its output is the new model's page URL.</li>
+ </ul>
+ <div class="md-way__actions"><a class="md-btn" href="https://github.com/nirholas/three.ws/tree/main/integrations/modly/three-ws-publish" rel="noopener" target="_blank">Get the node</a></div>
+ </li>
+ </ul>
+ </section>
+
+ <footer class="md-foot">
+ <p>Prefer not to install anything? <a href="/forge">Forge</a> generates on three.ws servers right in the browser.</p>
+ <p class="md-credit">Based on <a href="https://github.com/lightningpixel/modly" rel="noopener" target="_blank">Modly by Lightning Pixel</a> (MIT license). three.ws is not affiliated with Lightning Pixel.</p>
+ </footer>
+ <div id="mdToast" class="md-toast" role="status" aria-live="polite" hidden></div>
+ </main>
+
+ <script type="module" src="/src/modly-page.js"></script>
+</body>
+</html>
diff --git a/public/forge-desktop/registry.json b/public/forge-desktop/registry.json
new file mode 100644
index 000000000..06abd60d9
--- /dev/null
+++ b/public/forge-desktop/registry.json
@@ -0,0 +1,8 @@
+{
+ "description": "Extension repositories three.ws Forge marks as trusted. The desktop app unions this list with the upstream Modly registry.",
+ "trusted_repos": [
+ "https://github.com/lightningpixel/modly-hunyuan3d-mini-extension",
+ "https://github.com/lightningpixel/modly-triposg-extension",
+ "https://github.com/lightningpixel/modly-trellis2-extension"
+ ]
+}
diff --git a/src/modly-page.css b/src/modly-page.css
new file mode 100644
index 000000000..e8a4b3e84
--- /dev/null
+++ b/src/modly-page.css
@@ -0,0 +1,1410 @@
+/* /modly: the hub for Modly on three.ws. Live connection to the visitor's local
+ Modly, quick generation, and links to every other Modly surface.
+ Tokens come from public/tokens.css (loaded through /style.css). */
+
+.md-body {
+ background: var(--bg-0);
+ color: var(--ink);
+ --md-accent: #7c9cff;
+ --md-accent-soft: color-mix(in srgb, var(--md-accent) 16%, transparent);
+ --md-ok: var(--success, #22c55e);
+ --md-warn: var(--warn, #e0a93e);
+ --md-danger: var(--danger, #e05a5a);
+}
+
+html[data-theme='light'] .md-body {
+ --md-accent: #3a5bd9;
+}
+
+.md {
+ width: 100%;
+ box-sizing: border-box;
+ max-width: 1320px;
+ margin: 0 auto;
+ padding: var(--space-lg, 24px) var(--space-md, 16px) var(--space-2xl, 64px);
+}
+
+.md-sr {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip: rect(0 0 0 0);
+ white-space: nowrap;
+}
+
+.md-muted {
+ color: var(--ink-dim);
+}
+
+.md-mono,
+.md-input--mono {
+ font-family: var(--font-mono);
+}
+
+.md-hint {
+ margin: 0;
+ font-size: var(--text-xs, 12px);
+ line-height: 1.5;
+ color: var(--ink-dim);
+}
+
+.md-hint code,
+.md-panel code,
+.md-alert code {
+ font-family: var(--font-mono);
+ font-size: 0.92em;
+ padding: 0.05em 0.35em;
+ border-radius: 4px;
+ background: var(--surface-2);
+}
+
+.md a:not(.md-btn) {
+ color: var(--md-accent);
+ text-underline-offset: 2px;
+}
+
+.md a:not(.md-btn):hover {
+ text-decoration-thickness: 2px;
+}
+
+.md a:focus-visible {
+ outline: 2px solid var(--md-accent);
+ outline-offset: 2px;
+ border-radius: 3px;
+}
+
+kbd {
+ font-family: var(--font-mono);
+ font-size: 0.85em;
+ padding: 0.05em 0.4em;
+ border: 1px solid var(--stroke-strong);
+ border-bottom-width: 2px;
+ border-radius: 4px;
+}
+
+/* ── hero ─────────────────────────────────────────────────────────────── */
+
+.md-hero {
+ max-width: 780px;
+ margin: var(--space-xl, 40px) auto var(--space-xl, 40px);
+ text-align: center;
+}
+
+.md-eyebrow {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ margin: 0 0 var(--space-sm, 12px);
+ font-family: var(--font-mono);
+ font-size: 12px;
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+ color: var(--ink-dim);
+}
+
+.md-eyebrow__mark {
+ width: 14px;
+ height: 14px;
+ border-radius: 3px;
+ border: 1.5px solid var(--md-accent);
+ background: repeating-linear-gradient(90deg, var(--md-accent) 0 2px, transparent 2px 5px);
+ opacity: 0.9;
+}
+
+.md-hero h1 {
+ margin: 0 0 var(--space-md, 16px);
+ font-family: var(--font-display);
+ font-size: clamp(30px, 5vw, 52px);
+ line-height: 1.06;
+ letter-spacing: -0.02em;
+ color: var(--ink-bright);
+}
+
+.md-lede {
+ margin: 0 auto var(--space-sm, 12px);
+ max-width: 640px;
+ font-size: clamp(15px, 1.6vw, 17px);
+ line-height: 1.6;
+ color: var(--ink-dim);
+}
+
+.md-credit {
+ margin: 0;
+ font-size: var(--text-xs, 12px);
+ color: var(--ink-faint);
+}
+
+/* ── shared controls ──────────────────────────────────────────────────── */
+
+.md-h2,
+.md-h3,
+.md-h4 {
+ margin: 0;
+ font-family: var(--font-display);
+ color: var(--ink-bright);
+ letter-spacing: -0.01em;
+}
+
+.md-h2 {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ font-size: 18px;
+}
+
+.md-h3 {
+ font-size: 15px;
+}
+
+.md-h4 {
+ font-size: 13px;
+ margin-bottom: var(--space-xs, 8px);
+}
+
+.md-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ min-height: 38px;
+ padding: 0 16px;
+ border-radius: var(--radius-md, 10px);
+ border: 1px solid var(--stroke-strong);
+ background: var(--surface-2);
+ color: var(--ink);
+ font: 600 14px var(--font-body);
+ text-decoration: none;
+ white-space: nowrap;
+ cursor: pointer;
+ transition: background 0.15s ease, border-color 0.15s ease, transform 0.12s ease, opacity 0.15s ease;
+}
+
+.md-btn:hover {
+ background: var(--surface-3);
+ border-color: var(--stroke-strong);
+}
+
+.md-btn:active {
+ transform: translateY(1px);
+}
+
+.md-btn:focus-visible,
+.md-tab:focus-visible,
+.md-model:focus-visible,
+.md-drop:focus-visible,
+.md-details > summary:focus-visible {
+ outline: 2px solid var(--md-accent);
+ outline-offset: 2px;
+}
+
+.md-btn:disabled,
+.md-btn[aria-disabled='true'] {
+ opacity: 0.5;
+ cursor: not-allowed;
+ transform: none;
+}
+
+.md-btn--primary {
+ background: var(--ink-bright, #fff);
+ color: var(--bg-0);
+ border-color: transparent;
+}
+
+.md-btn--primary:hover {
+ background: var(--ink);
+}
+
+.md-btn--ghost {
+ background: transparent;
+ border-color: transparent;
+ color: var(--ink-dim);
+}
+
+.md-btn--ghost:hover {
+ background: var(--surface-2);
+ color: var(--ink);
+}
+
+.md-btn--sm {
+ min-height: 30px;
+ padding: 0 10px;
+ font-size: 13px;
+}
+
+.md-btn--wide {
+ width: 100%;
+ min-height: 46px;
+ font-size: 15px;
+}
+
+.md-btn__spinner {
+ display: none;
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ border: 2px solid currentColor;
+ border-right-color: transparent;
+ animation: md-spin 0.7s linear infinite;
+}
+
+.md-btn.is-busy .md-btn__spinner {
+ display: inline-block;
+}
+
+.md-btn.is-busy {
+ cursor: progress;
+}
+
+@keyframes md-spin {
+ to {
+ transform: rotate(360deg);
+ }
+}
+
+.md-input {
+ width: 100%;
+ box-sizing: border-box;
+ min-height: 38px;
+ padding: 8px 12px;
+ border-radius: var(--radius-md, 10px);
+ border: 1px solid var(--stroke-strong);
+ background: var(--surface-1);
+ color: var(--ink);
+ font: 400 14px var(--font-body);
+ transition: border-color 0.15s ease, box-shadow 0.15s ease;
+}
+
+.md-input.md-input--mono {
+ font-family: var(--font-mono);
+ font-size: 13px;
+}
+
+textarea.md-input {
+ resize: vertical;
+ min-height: 84px;
+ line-height: 1.5;
+}
+
+.md-input:hover {
+ border-color: color-mix(in srgb, var(--md-accent) 40%, var(--stroke-strong));
+}
+
+.md-input:focus {
+ outline: none;
+ border-color: var(--md-accent);
+ box-shadow: 0 0 0 3px var(--md-accent-soft);
+}
+
+.md-input:disabled {
+ opacity: 0.55;
+ cursor: not-allowed;
+}
+
+.md-input[aria-invalid='true'] {
+ border-color: var(--md-danger);
+}
+
+.md-check {
+ width: 18px;
+ height: 18px;
+ margin: 0;
+ accent-color: var(--md-accent);
+ cursor: pointer;
+}
+
+.md-check:focus-visible,
+.md-range:focus-visible {
+ outline: 2px solid var(--md-accent);
+ outline-offset: 2px;
+}
+
+.md-range {
+ width: 100%;
+ accent-color: var(--md-accent);
+ cursor: pointer;
+}
+
+.md-range:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+
+.md-label {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 8px;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--ink);
+}
+
+.md-label output {
+ font-family: var(--font-mono);
+ font-weight: 500;
+ font-size: 12px;
+ color: var(--ink-dim);
+}
+
+.md-form {
+ display: grid;
+ gap: var(--space-md, 14px);
+}
+
+.md-field {
+ display: grid;
+ gap: 6px;
+}
+
+.md-field[hidden] {
+ display: none;
+}
+
+.md-field--inline {
+ grid-template-columns: auto 1fr;
+ align-items: center;
+ column-gap: 10px;
+}
+
+.md-field--inline .md-hint {
+ grid-column: 1 / -1;
+}
+
+.md-num-row {
+ display: grid;
+ grid-template-columns: 1fr 92px;
+ gap: 10px;
+ align-items: center;
+}
+
+.md-field-error {
+ margin: 0;
+ font-size: 13px;
+ color: var(--md-danger);
+}
+
+.md-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ flex-wrap: wrap;
+}
+
+.md-row--start {
+ justify-content: flex-start;
+}
+
+.md-row .md-input {
+ flex: 1 1 200px;
+ width: auto;
+}
+
+.md-alert {
+ margin: var(--space-sm, 12px) 0 0;
+ padding: 12px 14px;
+ border-radius: var(--radius-md, 10px);
+ border: 1px solid var(--stroke-strong);
+ background: var(--surface-1);
+ font-size: 13px;
+ line-height: 1.55;
+}
+
+.md-alert p {
+ margin: 0 0 10px;
+}
+
+.md-alert p:last-child {
+ margin-bottom: 0;
+}
+
+.md-alert--error {
+ border-color: color-mix(in srgb, var(--md-danger) 55%, transparent);
+ background: color-mix(in srgb, var(--md-danger) 9%, var(--surface-1));
+}
+
+.md-alert--warn {
+ border-color: color-mix(in srgb, var(--md-warn) 55%, transparent);
+ background: color-mix(in srgb, var(--md-warn) 9%, var(--surface-1));
+}
+
+.md-alert--ok {
+ border-color: color-mix(in srgb, var(--md-ok) 55%, transparent);
+ background: color-mix(in srgb, var(--md-ok) 9%, var(--surface-1));
+}
+
+.md-alert ul {
+ margin: 6px 0 0;
+ padding-left: 18px;
+}
+
+.md-details > summary {
+ cursor: pointer;
+ list-style: none;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-weight: 600;
+ font-size: 13px;
+ color: var(--ink);
+ border-radius: 6px;
+}
+
+.md-details > summary::-webkit-details-marker {
+ display: none;
+}
+
+.md-details > summary::before {
+ content: '';
+ width: 7px;
+ height: 7px;
+ border-right: 1.6px solid currentColor;
+ border-bottom: 1.6px solid currentColor;
+ transform: rotate(-45deg);
+ transition: transform 0.18s ease;
+}
+
+.md-details[open] > summary::before {
+ transform: rotate(45deg);
+}
+
+.md-details[open] > summary {
+ margin-bottom: var(--space-sm, 12px);
+}
+
+.md-pre {
+ max-height: 220px;
+ overflow: auto;
+ margin: 0;
+ padding: 10px;
+ border-radius: 8px;
+ background: var(--surface-2);
+ font: 12px/1.5 var(--font-mono);
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+
+/* ── connection ───────────────────────────────────────────────────────── */
+
+.md-conn {
+ max-width: 960px;
+ margin: 0 auto var(--space-xl, 32px);
+ padding: var(--space-lg, 20px);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg, 16px);
+ background: var(--surface-1);
+}
+
+.md-conn__head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-md, 16px);
+ flex-wrap: wrap;
+ margin-bottom: 8px;
+}
+
+.md-dot {
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+ background: var(--ink-faint);
+ flex: none;
+ transition: background 0.2s ease, box-shadow 0.2s ease;
+}
+
+.md-conn[data-state='connected'] .md-dot {
+ background: var(--md-ok);
+ box-shadow: 0 0 0 4px color-mix(in srgb, var(--md-ok) 22%, transparent);
+}
+
+.md-conn[data-state='probing'] .md-dot {
+ background: var(--md-accent);
+ animation: md-pulse 1.1s ease-in-out infinite;
+}
+
+.md-conn[data-state='not-running'] .md-dot {
+ background: var(--md-warn);
+}
+
+.md-conn[data-state='blocked'] .md-dot {
+ background: var(--md-danger);
+}
+
+@keyframes md-pulse {
+ 50% {
+ opacity: 0.35;
+ }
+}
+
+.md-base {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex: 1 1 360px;
+ max-width: 520px;
+}
+
+.md-base__label {
+ font-size: 12px;
+ color: var(--ink-dim);
+ white-space: nowrap;
+}
+
+.md-base .md-input {
+ flex: 1 1 auto;
+ min-width: 0;
+}
+
+.md-conn__body {
+ margin-top: var(--space-md, 16px);
+}
+
+.md-panel {
+ display: none;
+ font-size: 14px;
+ line-height: 1.6;
+ animation: md-fade 0.22s ease both;
+}
+
+.md-panel p {
+ margin: 0 0 10px;
+}
+
+.md-conn[data-state='idle'] .md-panel[data-for='idle'],
+.md-conn[data-state='probing'] .md-panel[data-for='probing'],
+.md-conn[data-state='not-running'] .md-panel[data-for='not-running'],
+.md-conn[data-state='blocked'] .md-panel[data-for='blocked'],
+.md-conn[data-state='connected'] .md-panel[data-for='connected'] {
+ display: block;
+}
+
+.md-panel [data-reason] {
+ display: none;
+}
+
+.md-panel[data-reason='lna-denied'] [data-reason='lna-denied'],
+.md-panel[data-reason='mixed-content'] [data-reason='mixed-content'] {
+ display: block;
+}
+
+.md-panel__lead {
+ color: var(--ink);
+}
+
+.md-panel--ok p {
+ margin: 0 0 4px;
+}
+
+@keyframes md-fade {
+ from {
+ opacity: 0;
+ transform: translateY(4px);
+ }
+}
+
+.md-steps {
+ list-style: none;
+ margin: 0 0 var(--space-md, 16px);
+ padding: 0;
+ display: grid;
+ gap: 10px;
+}
+
+.md-steps li {
+ display: grid;
+ grid-template-columns: 26px 1fr;
+ gap: 10px;
+ align-items: start;
+}
+
+.md-steps__n {
+ width: 24px;
+ height: 24px;
+ border-radius: 50%;
+ display: grid;
+ place-items: center;
+ font: 600 12px var(--font-mono);
+ color: var(--md-accent);
+ background: var(--md-accent-soft);
+}
+
+.md-steps--compact {
+ font-size: 13px;
+ gap: 8px;
+}
+
+.md-skel-line,
+.md-skel-card {
+ border-radius: 8px;
+ background: linear-gradient(90deg, var(--skeleton-base, var(--surface-2)) 0%, var(--skeleton-sheen, var(--surface-3)) 50%, var(--skeleton-base, var(--surface-2)) 100%);
+ background-size: 200% 100%;
+ animation: md-sheen 1.3s ease-in-out infinite;
+}
+
+.md-skel-line {
+ height: 14px;
+ margin-bottom: 10px;
+ width: 80%;
+}
+
+.md-skel-line--short {
+ width: 46%;
+}
+
+.md-skel-list {
+ display: grid;
+ gap: 8px;
+ margin-top: var(--space-sm, 12px);
+}
+
+.md-skel-card {
+ height: 58px;
+}
+
+@keyframes md-sheen {
+ from {
+ background-position: 100% 0;
+ }
+ to {
+ background-position: -100% 0;
+ }
+}
+
+/* ── studio layout ────────────────────────────────────────────────────── */
+
+.md-studio {
+ display: grid;
+ grid-template-columns: minmax(300px, 400px) minmax(0, 1fr);
+ gap: var(--space-lg, 24px);
+ align-items: start;
+ animation: md-fade 0.3s ease both;
+}
+
+.md-studio[hidden] {
+ display: none;
+}
+
+.md-col {
+ display: grid;
+ gap: var(--space-md, 16px);
+ min-width: 0;
+}
+
+.md-card {
+ padding: var(--space-md, 16px);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg, 16px);
+ background: var(--surface-1);
+ min-width: 0;
+}
+
+.md-card__head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ margin-bottom: var(--space-sm, 12px);
+}
+
+.md-card__actions {
+ display: flex;
+ gap: 4px;
+}
+
+.md-card > .md-hint {
+ margin-bottom: var(--space-sm, 12px);
+}
+
+.md-card > .md-h3 + .md-export,
+.md-card > .md-h3 + .md-form {
+ margin-top: var(--space-sm, 12px);
+}
+
+.md-card.md-details > summary {
+ font-size: 15px;
+ font-family: var(--font-display);
+ color: var(--ink-bright);
+}
+
+.md-empty {
+ font-size: 14px;
+ line-height: 1.6;
+}
+
+.md-empty p {
+ margin: 0 0 10px;
+}
+
+/* models */
+
+.md-model-list {
+ display: grid;
+ gap: 8px;
+}
+
+.md-model-list[hidden] {
+ display: none;
+}
+
+.md-model {
+ display: grid;
+ grid-template-columns: 18px 1fr;
+ gap: 4px 10px;
+ align-items: start;
+ width: 100%;
+ padding: 10px 12px;
+ text-align: left;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md, 10px);
+ background: transparent;
+ color: var(--ink);
+ font: inherit;
+ cursor: pointer;
+ transition: border-color 0.15s ease, background 0.15s ease;
+}
+
+.md-model:hover {
+ border-color: var(--stroke-strong);
+ background: var(--surface-2);
+}
+
+.md-model[aria-checked='true'] {
+ border-color: var(--md-accent);
+ background: var(--md-accent-soft);
+}
+
+.md-model__radio {
+ width: 16px;
+ height: 16px;
+ margin-top: 2px;
+ border-radius: 50%;
+ border: 1.6px solid var(--stroke-strong);
+ transition: border 0.15s ease;
+}
+
+.md-model[aria-checked='true'] .md-model__radio {
+ border: 5px solid var(--md-accent);
+}
+
+.md-model__name {
+ font-weight: 600;
+ font-size: 14px;
+}
+
+.md-model__desc {
+ grid-column: 2;
+ font-size: 12px;
+ color: var(--ink-dim);
+ line-height: 1.45;
+}
+
+.md-model__tags {
+ grid-column: 2;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+}
+
+.md-tag {
+ display: inline-flex;
+ align-items: center;
+ padding: 1px 7px;
+ border-radius: 999px;
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--ink-dim);
+ background: var(--surface-2);
+ border: 1px solid var(--stroke);
+}
+
+.md-tag--ok {
+ color: var(--md-ok);
+ border-color: color-mix(in srgb, var(--md-ok) 40%, transparent);
+ background: color-mix(in srgb, var(--md-ok) 10%, transparent);
+}
+
+.md-tag--warn {
+ color: var(--md-warn);
+ border-color: color-mix(in srgb, var(--md-warn) 40%, transparent);
+ background: color-mix(in srgb, var(--md-warn) 10%, transparent);
+}
+
+.md-params {
+ margin-top: var(--space-md, 16px);
+ padding-top: var(--space-md, 16px);
+ border-top: 1px solid var(--stroke);
+}
+
+.md-params[hidden] {
+ display: none;
+}
+
+#mdGenOptions {
+ margin-top: var(--space-md, 16px);
+ padding-top: var(--space-md, 16px);
+ border-top: 1px solid var(--stroke);
+}
+
+.md-ext-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: grid;
+ gap: 6px;
+}
+
+.md-ext {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ padding: 8px 10px;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md, 10px);
+ font-size: 13px;
+}
+
+.md-ext__name {
+ display: grid;
+ gap: 2px;
+ min-width: 0;
+}
+
+.md-ext__url {
+ font: 11px var(--font-mono);
+ color: var(--ink-faint);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+/* input */
+
+.md-tabs {
+ display: inline-flex;
+ padding: 3px;
+ border-radius: 999px;
+ background: var(--surface-2);
+}
+
+.md-tab {
+ padding: 5px 12px;
+ border: 0;
+ border-radius: 999px;
+ background: transparent;
+ color: var(--ink-dim);
+ font: 600 12px var(--font-body);
+ cursor: pointer;
+ transition: background 0.15s ease, color 0.15s ease;
+}
+
+.md-tab:hover {
+ color: var(--ink);
+}
+
+.md-tab[aria-selected='true'] {
+ background: var(--surface-1);
+ color: var(--ink-bright);
+ box-shadow: var(--shadow-1, 0 1px 2px rgba(0, 0, 0, 0.2));
+}
+
+.md-pane {
+ display: grid;
+ gap: 10px;
+}
+
+.md-pane[hidden] {
+ display: none;
+}
+
+.md-drop {
+ position: relative;
+ display: grid;
+ place-items: center;
+ min-height: 200px;
+ padding: 16px;
+ border: 1.5px dashed var(--stroke-strong);
+ border-radius: var(--radius-md, 12px);
+ background: var(--bg-0);
+ text-align: center;
+ cursor: pointer;
+ overflow: hidden;
+ transition: border-color 0.15s ease, background 0.15s ease;
+}
+
+.md-drop:hover,
+.md-drop.is-over {
+ border-color: var(--md-accent);
+ background: var(--md-accent-soft);
+}
+
+.md-drop__empty {
+ display: grid;
+ justify-items: center;
+ gap: 6px;
+ color: var(--ink-dim);
+ font-size: 14px;
+}
+
+.md-drop__empty strong {
+ color: var(--ink);
+}
+
+.md-drop__img {
+ max-width: 100%;
+ max-height: 260px;
+ object-fit: contain;
+ border-radius: 8px;
+}
+
+.md-drop.has-image .md-drop__empty {
+ display: none;
+}
+
+.md-drop__meta {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ font-size: 12px;
+}
+
+.md-drop__meta[hidden] {
+ display: none;
+}
+
+.md-drop__meta .md-muted {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.md-generate {
+ display: grid;
+ gap: 8px;
+ margin-top: var(--space-md, 16px);
+}
+
+/* ── stage ────────────────────────────────────────────────────────────── */
+
+.md-stage {
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg, 16px);
+ background: radial-gradient(120% 90% at 50% 10%, var(--surface-2) 0%, var(--bg-0) 70%);
+ overflow: hidden;
+}
+
+.md-stage__view {
+ position: relative;
+ aspect-ratio: 4 / 3;
+ min-height: 320px;
+}
+
+.md-stage__view > [data-for] {
+ position: absolute;
+ inset: 0;
+ display: none;
+ padding: var(--space-lg, 24px);
+ box-sizing: border-box;
+}
+
+.md-stage[data-stage='empty'] [data-for='empty'],
+.md-stage[data-stage='generating'] [data-for='generating'],
+.md-stage[data-stage='loading'] [data-for='loading'],
+.md-stage[data-stage='error'] [data-for='error'],
+.md-stage[data-stage='ready'] [data-for='ready'] {
+ display: grid;
+ animation: md-fade 0.25s ease both;
+}
+
+.md-stage__empty,
+.md-stage__progress,
+.md-stage__loading {
+ place-content: center;
+ justify-items: center;
+ gap: 10px;
+ text-align: center;
+ color: var(--ink-dim);
+}
+
+.md-stage__empty p,
+.md-stage__progress p,
+.md-stage__loading p {
+ margin: 0;
+}
+
+.md-stage__empty svg {
+ color: var(--ink-faint);
+ margin-bottom: 4px;
+}
+
+.md-stage__empty strong {
+ color: var(--ink);
+}
+
+.md-stage__progress {
+ gap: 14px;
+}
+
+.md-stage__step {
+ font-weight: 600;
+ color: var(--ink) !important;
+ min-height: 1.5em;
+}
+
+.md-stage__error {
+ align-content: center;
+ max-width: 560px;
+ margin: 0 auto;
+ font-size: 14px;
+ line-height: 1.6;
+}
+
+.md-stage__error p {
+ margin: 0 0 10px;
+}
+
+.md-stage__viewer {
+ padding: 0 !important;
+}
+
+.md-stage__viewer model-viewer {
+ width: 100%;
+ height: 100%;
+ background: transparent;
+ --poster-color: transparent;
+}
+
+.md-progress {
+ position: relative;
+ width: min(360px, 80%);
+ height: 8px;
+ border-radius: 999px;
+ background: var(--surface-3);
+ overflow: hidden;
+}
+
+.md-progress--thin {
+ width: 100%;
+ height: 4px;
+}
+
+.md-progress[hidden] {
+ display: none;
+}
+
+.md-progress__bar {
+ position: absolute;
+ inset: 0 auto 0 0;
+ width: 100%;
+ transform-origin: left center;
+ transform: scaleX(0);
+ background: linear-gradient(90deg, var(--md-accent), color-mix(in srgb, var(--md-accent) 60%, #fff));
+ transition: transform 0.4s ease;
+ will-change: transform;
+}
+
+.md-progress.is-indeterminate .md-progress__bar {
+ width: 35%;
+ transform: none;
+ animation: md-indeterminate 1.2s ease-in-out infinite;
+}
+
+@keyframes md-indeterminate {
+ from {
+ left: -35%;
+ }
+ to {
+ left: 100%;
+ }
+}
+
+.md-spinner {
+ width: 28px;
+ height: 28px;
+ border-radius: 50%;
+ border: 3px solid var(--surface-3);
+ border-top-color: var(--md-accent);
+ animation: md-spin 0.8s linear infinite;
+}
+
+.md-stage__meta {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ flex-wrap: wrap;
+ padding: 10px 14px;
+ border-top: 1px solid var(--stroke);
+ font-size: 12px;
+ background: var(--surface-1);
+}
+
+.md-stage__meta[hidden] {
+ display: none;
+}
+
+.md-stage__meta .md-mono {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ min-width: 0;
+}
+
+.md-result {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
+ gap: var(--space-md, 16px);
+ animation: md-fade 0.3s ease both;
+}
+
+.md-result[hidden] {
+ display: none;
+}
+
+.md-result > .md-card:first-child {
+ grid-column: 1 / -1;
+}
+
+.md-ops {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
+ gap: 10px;
+}
+
+.md-op {
+ display: grid;
+ gap: 10px;
+ align-content: start;
+ padding: 12px;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md, 10px);
+}
+
+.md-op__head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+}
+
+.md-op__title {
+ font-weight: 600;
+ font-size: 14px;
+}
+
+.md-op .md-form {
+ gap: 10px;
+}
+
+.md-export {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+}
+
+.md-export .md-btn {
+ flex: 1 1 64px;
+ font-family: var(--font-mono);
+}
+
+/* ── footer + toast ───────────────────────────────────────────────────── */
+
+.md-foot {
+ margin-top: var(--space-2xl, 56px);
+ text-align: center;
+ font-size: 13px;
+ color: var(--ink-dim);
+}
+
+.md-foot p {
+ margin: 0 0 6px;
+}
+
+.md-toast {
+ position: fixed;
+ left: 50%;
+ bottom: 24px;
+ z-index: 50;
+ max-width: calc(100vw - 32px);
+ padding: 10px 16px;
+ border-radius: 999px;
+ background: var(--ink-bright);
+ color: var(--bg-0);
+ font-size: 13px;
+ font-weight: 600;
+ box-shadow: var(--shadow-2, 0 8px 24px rgba(0, 0, 0, 0.3));
+ transform: translateX(-50%);
+ animation: md-toast-in 0.22s ease both;
+}
+
+@keyframes md-toast-in {
+ from {
+ opacity: 0;
+ transform: translate(-50%, 8px);
+ }
+}
+
+/* ── the integration hub: every way to use Modly with three.ws ────────── */
+
+.md-ways {
+ margin-top: var(--space-2xl, 56px);
+ scroll-margin-top: 80px;
+}
+
+.md-ways__head {
+ max-width: 720px;
+ margin: 0 0 var(--space-md, 16px);
+}
+
+.md-ways__head .md-h2 {
+ font-size: clamp(20px, 2.4vw, 26px);
+ margin-bottom: 6px;
+}
+
+.md-ways__head p {
+ margin: 0;
+ font-size: 14px;
+ line-height: 1.6;
+ color: var(--ink-dim);
+}
+
+.md-ways__grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
+ gap: var(--space-md, 16px);
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.md-way {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ padding: var(--space-md, 16px) var(--space-md, 16px) var(--space-md, 16px);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg, 16px);
+ background: var(--surface-1);
+ transition: border-color 0.18s ease, transform 0.18s ease, box-shadow 0.18s ease;
+}
+
+.md-way:hover,
+.md-way:focus-within {
+ border-color: color-mix(in srgb, var(--md-accent) 45%, var(--stroke));
+ transform: translateY(-2px);
+ box-shadow: 0 10px 28px color-mix(in srgb, var(--md-accent) 10%, transparent);
+}
+
+.md-way__icon {
+ display: grid;
+ place-items: center;
+ width: 36px;
+ height: 36px;
+ border-radius: 10px;
+ background: var(--md-accent-soft);
+ color: var(--md-accent);
+}
+
+.md-way__kind {
+ margin: 0;
+ font-family: var(--font-mono);
+ font-size: 11px;
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+ color: var(--ink-faint);
+}
+
+.md-way .md-h3 {
+ font-size: 16px;
+}
+
+.md-way p {
+ margin: 0;
+ font-size: 14px;
+ line-height: 1.55;
+ color: var(--ink-dim);
+}
+
+.md-way__points {
+ margin: 0;
+ padding-left: 18px;
+ font-size: 13px;
+ line-height: 1.55;
+ color: var(--ink-dim);
+}
+
+.md-way__points li + li {
+ margin-top: 2px;
+}
+
+.md-way__actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-top: auto;
+ padding-top: 6px;
+}
+
+.md-way--here {
+ border-style: dashed;
+}
+
+/* ── responsive ───────────────────────────────────────────────────────── */
+
+@media (max-width: 900px) {
+ .md-studio {
+ grid-template-columns: minmax(0, 1fr);
+ }
+
+ .md-col--stage {
+ order: -1;
+ }
+
+ .md-stage__view {
+ aspect-ratio: 1 / 1;
+ min-height: 280px;
+ }
+}
+
+@media (max-width: 560px) {
+ .md-conn {
+ padding: var(--space-md, 16px);
+ }
+
+ .md-base {
+ flex-wrap: wrap;
+ }
+
+ .md-base__label {
+ width: 100%;
+ }
+
+ .md-card__head {
+ flex-wrap: wrap;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .md-way:hover,
+ .md-way:focus-within {
+ transform: none;
+ }
+
+ .md-panel,
+ .md-studio,
+ .md-result,
+ .md-stage [data-for],
+ .md-toast {
+ animation: none !important;
+ }
+
+ .md-skel-line,
+ .md-skel-card,
+ .md-progress.is-indeterminate .md-progress__bar {
+ animation-duration: 3s;
+ }
+}
diff --git a/src/modly-page.js b/src/modly-page.js
new file mode 100644
index 000000000..41e40b81c
--- /dev/null
+++ b/src/modly-page.js
@@ -0,0 +1,1253 @@
+// /modly: the three.ws hub for Modly, the open-source image-to-3D app that runs
+// on the visitor's own GPU.
+//
+// All talk with the local Modly server goes through src/modly-local.js, the
+// same client the Forge "Your GPU (Modly)" lane uses. This page adds the UI on
+// top: detection with every failure explained, the live model list, quick
+// generation with real progress, Modly's mesh tools with undo, the three.ws
+// concept-image lane for text prompts, and saving the result to the account.
+// Based on Modly by Lightning Pixel (MIT): https://github.com/lightningpixel/modly
+
+import {
+ MODLY_DEFAULT_ORIGINS,
+ MODLY_INSTALL_URL,
+ ModlyError,
+ defaultModlyParams,
+ downloadModlyGlb,
+ generateWithModly,
+ getModlyOriginOverride,
+ listModlyMeshOps,
+ listModlyModels,
+ modlyMeshOp,
+ normalizeModlyOrigin,
+ probeModly,
+ setModlyOriginOverride,
+ validateModlyWorkspacePath,
+} from './modly-local.js';
+import { ensureModelViewer } from './shared/model-viewer-loader.js';
+import { getMe, saveRemoteGlbToAccount } from './account.js';
+
+const CONNECTED_KEY = 'tws:modly-connected';
+const RESUME_KEY = 'tws:modly-resume';
+const MAX_IMAGE_BYTES = 20 * 1024 * 1024;
+
+// The official local generators, as listed in Modly's README. Shown when Modly
+// has none installed; each one is added from Modly's Models page.
+const OFFICIAL_EXTENSIONS = [
+ { name: 'Hunyuan3D 2 Mini', repo: 'https://github.com/lightningpixel/modly-hunyuan3d-mini-extension' },
+ { name: 'Hunyuan3D 2 Mini Turbo', repo: 'https://github.com/lightningpixel/modly-hunyuan3d-mini-turbo-extension' },
+ { name: 'Hunyuan3D 2 Mini Fast', repo: 'https://github.com/lightningpixel/modly-hunyuan3d-mini-fast-extension' },
+ { name: 'TripoSG', repo: 'https://github.com/lightningpixel/modly-triposg-extension' },
+ { name: 'Trellis2 GGUF', repo: 'https://github.com/lightningpixel/modly-trellis2-gguf-extension' },
+];
+
+const $ = (id) => document.getElementById(id);
+
+const el = {
+ conn: $('mdConn'),
+ connStatus: $('mdConnStatus'),
+ baseForm: $('mdBaseForm'),
+ base: $('mdBase'),
+ connect: $('mdConnect'),
+ baseError: $('mdBaseError'),
+ probingText: $('mdProbingText'),
+ installLink: $('mdInstallLink'),
+ connOrigin: $('mdConnOrigin'),
+ connSummary: $('mdConnSummary'),
+ studio: $('mdStudio'),
+ refreshModels: $('mdRefreshModels'),
+ modelsLoading: $('mdModelsLoading'),
+ modelsEmpty: $('mdModelsEmpty'),
+ extList: $('mdExtList'),
+ modelsError: $('mdModelsError'),
+ modelList: $('mdModelList'),
+ params: $('mdParams'),
+ paramsForm: $('mdParamsForm'),
+ tabImage: $('mdTabImage'),
+ tabPrompt: $('mdTabPrompt'),
+ paneImage: $('mdPaneImage'),
+ panePrompt: $('mdPanePrompt'),
+ drop: $('mdDrop'),
+ file: $('mdFile'),
+ dropImg: $('mdDropImg'),
+ dropMeta: $('mdDropMeta'),
+ dropName: $('mdDropName'),
+ clearImage: $('mdClearImage'),
+ prompt: $('mdPrompt'),
+ concept: $('mdConcept'),
+ conceptError: $('mdConceptError'),
+ generate: $('mdGenerate'),
+ generateHint: $('mdGenerateHint'),
+ openForm: $('mdOpenForm'),
+ openPath: $('mdOpenPath'),
+ openError: $('mdOpenError'),
+ stage: $('mdStage'),
+ step: $('mdStep'),
+ progress: $('mdProgress'),
+ progressBar: $('mdProgressBar'),
+ pct: $('mdPct'),
+ elapsed: $('mdElapsed'),
+ cancel: $('mdCancel'),
+ loadingText: $('mdLoadingText'),
+ stageErrorTitle: $('mdStageErrorTitle'),
+ stageErrorText: $('mdStageErrorText'),
+ stageErrorDetail: $('mdStageErrorDetail'),
+ stageErrorPre: $('mdStageErrorPre'),
+ stageRetry: $('mdStageRetry'),
+ stageDismiss: $('mdStageDismiss'),
+ viewerHost: $('mdViewerHost'),
+ meta: $('mdMeta'),
+ metaPath: $('mdMetaPath'),
+ metaStats: $('mdMetaStats'),
+ result: $('mdResult'),
+ undo: $('mdUndo'),
+ ops: $('mdOps'),
+ opsError: $('mdOpsError'),
+ download: $('mdDownload'),
+ saveForm: $('mdSaveForm'),
+ saveName: $('mdSaveName'),
+ saveVis: $('mdSaveVis'),
+ save: $('mdSave'),
+ saveProgress: $('mdSaveProgress'),
+ saveProgressBar: $('mdSaveProgressBar'),
+ saveSignedOut: $('mdSaveSignedOut'),
+ signIn: $('mdSignIn'),
+ saveDone: $('mdSaveDone'),
+ saveLink: $('mdSaveLink'),
+ saveError: $('mdSaveError'),
+ toast: $('mdToast'),
+};
+
+const state = {
+ origin: null,
+ probeController: null,
+ models: [],
+ modelId: null,
+ paramsSchema: [],
+ paramValues: {},
+ ops: [],
+ opValues: {},
+ image: null,
+ imageName: '',
+ imageUrl: null,
+ job: null,
+ /** { workspacePath, blob, modelId, faceCount } of the model on the stage. */
+ current: null,
+ history: [],
+ viewer: null,
+ busy: false,
+ retryAction: null,
+ saveController: null,
+};
+
+// ── small helpers ──────────────────────────────────────────────────────────
+
+function readStore(store, key) {
+ try {
+ return globalThis[store]?.getItem(key) ?? null;
+ } catch {
+ return null;
+ }
+}
+
+function writeStore(store, key, value) {
+ try {
+ if (value === null) globalThis[store]?.removeItem(key);
+ else globalThis[store]?.setItem(key, value);
+ } catch {
+ // Storage blocked (private mode): the feature still works for this visit.
+ }
+}
+
+function show(node, visible) {
+ node.hidden = !visible;
+}
+
+function setBusy(button, busy) {
+ button.classList.toggle('is-busy', busy);
+ button.disabled = busy;
+ button.setAttribute('aria-busy', busy ? 'true' : 'false');
+}
+
+let toastTimer = null;
+function toast(message) {
+ el.toast.textContent = message;
+ el.toast.hidden = false;
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => {
+ el.toast.hidden = true;
+ }, 3200);
+}
+
+function formatBytes(n) {
+ if (!Number.isFinite(n)) return '';
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`;
+ return `${(n / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+function formatElapsed(ms) {
+ const s = Math.max(0, Math.floor(ms / 1000));
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
+}
+
+function fileBaseName(path) {
+ const name = String(path).split('/').pop() || 'model';
+ return name.replace(/\.[a-z0-9]+$/i, '');
+}
+
+function humanName(path) {
+ const base = fileBaseName(path).replace(/[_-]+/g, ' ').trim();
+ return (base.charAt(0).toUpperCase() + base.slice(1)).slice(0, 120) || 'Local model';
+}
+
+function errorText(err) {
+ return err?.message || 'Something went wrong.';
+}
+
+/** A title and a next step for every ModlyError code a page action can hit. */
+function modlyErrorCopy(err) {
+ const message = errorText(err);
+ switch (err?.code) {
+ case 'NOT_RUNNING':
+ case 'BLOCKED':
+ return { title: 'Lost the connection to Modly', text: `${message} Make sure the Modly app is still open, then try again.` };
+ case 'TIMEOUT':
+ return { title: 'Modly took too long', text: `${message} Large models on small GPUs can be slow; a lighter model or a smaller image helps.` };
+ case 'UNAVAILABLE':
+ return { title: 'Modly could not run that step', text: `${message} The mesh tools need Modly's optional geometry packages; updating Modly restores them.` };
+ case 'GENERATION_FAILED':
+ return { title: 'The model failed inside Modly', text: `${message}. A clear photo of a single object on a plain background often helps; out-of-memory errors mean the model needs more GPU memory than is free.` };
+ case 'RUN_LOST':
+ return { title: 'Modly lost track of the generation', text: message };
+ case 'NOT_GLB':
+ return { title: 'This output is not a mesh', text: `${message} Models that make Gaussian splats write PLY files; open those in Modly itself.` };
+ case 'NOT_FOUND':
+ return { title: 'Modly could not find that', text: message };
+ case 'UNKNOWN_MODEL':
+ return { title: 'That model is no longer installed', text: `${message} Press Refresh to reload the model list.` };
+ case 'BAD_REQUEST':
+ case 'BAD_INPUT':
+ return { title: 'Modly rejected the request', text: message };
+ case 'BAD_PATH':
+ return { title: 'Modly reported an unusable file location', text: message };
+ default:
+ return { title: 'Something went wrong', text: message };
+ }
+}
+
+// ── connection ─────────────────────────────────────────────────────────────
+
+const CONN_LABEL = {
+ idle: 'Not connected',
+ probing: 'Looking for Modly',
+ 'not-running': 'Modly not found',
+ blocked: 'Connection blocked by the browser',
+ connected: 'Connected',
+};
+
+function setConnState(next, { reason = '' } = {}) {
+ el.conn.dataset.state = next;
+ el.connStatus.textContent = CONN_LABEL[next] || next;
+ el.conn.querySelector('.md-panel[data-for="blocked"]').dataset.reason = reason;
+ setBusy(el.connect, next === 'probing');
+ el.connect.querySelector('.md-btn__label').textContent = next === 'connected' ? 'Reconnect' : 'Connect';
+ show(el.studio, next === 'connected');
+}
+
+/** Read the address field: '' means "Modly's default port". Throws BAD_ORIGIN. */
+function readOriginField() {
+ const typed = el.base.value.trim();
+ if (!typed) return '';
+ const origin = normalizeModlyOrigin(typed);
+ return MODLY_DEFAULT_ORIGINS.includes(origin) ? '' : origin;
+}
+
+async function connect() {
+ show(el.baseError, false);
+ el.base.removeAttribute('aria-invalid');
+ let override;
+ try {
+ override = readOriginField();
+ } catch (err) {
+ el.baseError.textContent = errorText(err);
+ show(el.baseError, true);
+ el.base.setAttribute('aria-invalid', 'true');
+ el.base.focus();
+ return;
+ }
+ setModlyOriginOverride(override);
+ el.base.value = override;
+
+ state.probeController?.abort();
+ const controller = new AbortController();
+ state.probeController = controller;
+ el.probingText.textContent = `Looking for Modly at ${override || MODLY_DEFAULT_ORIGINS[0]}.`;
+ setConnState('probing');
+
+ const probe = await probeModly({ signal: controller.signal });
+ if (controller.signal.aborted) return;
+ state.probeController = null;
+
+ if (probe.status !== 'connected') {
+ state.origin = null;
+ setConnState(probe.status, { reason: probe.reason });
+ return;
+ }
+ state.origin = probe.origin;
+ writeStore('localStorage', CONNECTED_KEY, '1');
+ el.connOrigin.textContent = `at ${probe.origin}`;
+ setConnState('connected');
+ applyModels(probe.models, probe.error);
+ await loadOps();
+ await resumeAfterSignIn();
+}
+
+function summarizeConnection() {
+ const n = state.models.length;
+ const ready = state.models.filter((m) => m.downloaded).length;
+ if (!n) {
+ el.connSummary.textContent = 'No models installed in Modly yet. Add one below to start generating.';
+ return;
+ }
+ const models = n === 1 ? '1 model installed' : `${n} models installed`;
+ el.connSummary.textContent = ready === n ? `${models}, all downloaded and ready.` : `${models}, ${ready} downloaded. The others fetch their weights on first use.`;
+}
+
+// ── models ─────────────────────────────────────────────────────────────────
+
+function applyModels(models, error) {
+ state.models = models;
+ show(el.modelsLoading, false);
+ show(el.modelsEmpty, false);
+ show(el.modelList, false);
+ if (error) {
+ el.modelsError.textContent = `Modly is running, but its model list failed to load. ${modlyErrorCopy(error).text}`;
+ show(el.modelsError, true);
+ } else {
+ show(el.modelsError, false);
+ }
+ summarizeConnection();
+ if (!models.length) {
+ state.modelId = null;
+ renderParams([]);
+ if (!error) renderEmptyModels();
+ } else {
+ const keep = models.find((m) => m.id === state.modelId);
+ const pick = keep || models.find((m) => m.active) || models.find((m) => m.loaded) || models.find((m) => m.downloaded) || models[0];
+ state.modelId = pick.id;
+ renderModelList();
+ // A refresh that keeps the same model keeps the settings already chosen.
+ if (!keep) renderParams(pick.paramsSchema);
+ }
+ updateGenerateState();
+}
+
+async function refreshModels() {
+ if (!state.origin) return;
+ setBusy(el.refreshModels, true);
+ show(el.modelsLoading, true);
+ show(el.modelList, false);
+ show(el.modelsEmpty, false);
+ try {
+ applyModels(await listModlyModels(state.origin));
+ } catch (err) {
+ applyModels([], err);
+ } finally {
+ show(el.modelsLoading, false);
+ setBusy(el.refreshModels, false);
+ }
+}
+
+function renderEmptyModels() {
+ el.extList.replaceChildren(
+ ...OFFICIAL_EXTENSIONS.map((ext) => {
+ const li = document.createElement('li');
+ li.className = 'md-ext';
+ const name = document.createElement('span');
+ name.className = 'md-ext__name';
+ const strong = document.createElement('strong');
+ strong.textContent = ext.name;
+ const url = document.createElement('span');
+ url.className = 'md-ext__url';
+ url.textContent = ext.repo.replace('https://', '');
+ name.append(strong, url);
+ const copy = document.createElement('button');
+ copy.type = 'button';
+ copy.className = 'md-btn md-btn--sm';
+ copy.textContent = 'Copy link';
+ copy.setAttribute('aria-label', `Copy the ${ext.name} repository link`);
+ copy.addEventListener('click', () => copyText(ext.repo, `${ext.name} link copied. Paste it into Modly.`));
+ li.append(name, copy);
+ return li;
+ }),
+ );
+ show(el.modelsEmpty, true);
+}
+
+async function copyText(text, message) {
+ try {
+ await navigator.clipboard.writeText(text);
+ toast(message);
+ } catch {
+ toast(`Copy this link: ${text}`);
+ }
+}
+
+function renderModelList() {
+ const buttons = state.models.map((m) => {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'md-model';
+ btn.setAttribute('role', 'radio');
+ btn.dataset.id = m.id;
+ const checked = m.id === state.modelId;
+ btn.setAttribute('aria-checked', checked ? 'true' : 'false');
+ btn.tabIndex = checked ? 0 : -1;
+
+ const radio = document.createElement('span');
+ radio.className = 'md-model__radio';
+ radio.setAttribute('aria-hidden', 'true');
+ const name = document.createElement('span');
+ name.className = 'md-model__name';
+ name.textContent = m.name;
+ btn.append(radio, name);
+
+ if (m.description) {
+ const desc = document.createElement('span');
+ desc.className = 'md-model__desc';
+ desc.textContent = m.description;
+ btn.append(desc);
+ }
+ const tags = document.createElement('span');
+ tags.className = 'md-model__tags';
+ tags.append(tag(m.downloaded ? 'Downloaded' : 'Downloads on first run', m.downloaded ? 'ok' : 'warn'));
+ if (m.loaded) tags.append(tag('In GPU memory', 'ok'));
+ if (m.vramGb > 0) tags.append(tag(`${m.vramGb} GB VRAM`));
+ btn.append(tags);
+ btn.addEventListener('click', () => selectModel(m.id));
+ return btn;
+ });
+ el.modelList.replaceChildren(...buttons);
+ show(el.modelList, true);
+}
+
+function tag(text, tone) {
+ const span = document.createElement('span');
+ span.className = `md-tag${tone ? ` md-tag--${tone}` : ''}`;
+ span.textContent = text;
+ return span;
+}
+
+el.modelList.addEventListener('keydown', (e) => {
+ if (!['ArrowDown', 'ArrowUp', 'ArrowLeft', 'ArrowRight'].includes(e.key)) return;
+ e.preventDefault();
+ const ids = state.models.map((m) => m.id);
+ const idx = ids.indexOf(state.modelId);
+ const step = e.key === 'ArrowDown' || e.key === 'ArrowRight' ? 1 : -1;
+ const next = ids[(idx + step + ids.length) % ids.length];
+ selectModel(next);
+ el.modelList.querySelector(`[data-id="${CSS.escape(next)}"]`)?.focus();
+});
+
+function selectModel(id) {
+ if (id === state.modelId) return;
+ state.modelId = id;
+ renderModelList();
+ renderParams(state.models.find((m) => m.id === id)?.paramsSchema || []);
+ updateGenerateState();
+}
+
+function renderParams(schema) {
+ state.paramsSchema = schema;
+ state.paramValues = defaultValues(schema);
+ renderSchemaForm(el.paramsForm, schema, state.paramValues, 'mdp');
+ show(el.params, schema.length > 0);
+}
+
+// ── schema-driven forms (model params and mesh ops share them) ─────────────
+
+// Modly's own defaults, plus a value for every control a schema leaves
+// without one, so what the form shows is exactly what gets sent.
+function defaultValues(schema) {
+ const values = defaultModlyParams(schema);
+ for (const p of schema) {
+ if (values[p.id] !== undefined && values[p.id] !== null) continue;
+ if (p.type === 'boolean') values[p.id] = false;
+ else if (p.type === 'select' && p.options?.length) values[p.id] = p.options[0].value;
+ }
+ return values;
+}
+
+function isVisible(param, values) {
+ if (!param.show_if) return true;
+ return Object.entries(param.show_if).every(([key, expected]) => {
+ const actual = values[key];
+ return Array.isArray(expected) ? expected.some((v) => String(v) === String(actual)) : String(expected) === String(actual);
+ });
+}
+
+function applyVisibility(container, schema, values) {
+ for (const p of schema) {
+ const field = container.querySelector(`[data-param="${CSS.escape(p.id)}"]`);
+ if (field) field.hidden = !isVisible(p, values);
+ }
+}
+
+function clampNumber(raw, p) {
+ let n = p.type === 'int' ? Math.round(Number(raw)) : Number(raw);
+ if (!Number.isFinite(n)) n = Number(p.default ?? p.min ?? 0);
+ if (Number.isFinite(p.min)) n = Math.max(p.min, n);
+ if (Number.isFinite(p.max)) n = Math.min(p.max, n);
+ return n;
+}
+
+function renderSchemaForm(container, schema, values, prefix) {
+ const fields = schema.map((p) => {
+ const id = `${prefix}-${p.id}`;
+ const field = document.createElement('div');
+ field.className = 'md-field';
+ field.dataset.param = p.id;
+
+ const label = document.createElement('label');
+ label.className = 'md-label';
+ label.htmlFor = id;
+ label.textContent = p.label || p.id;
+
+ let hint = null;
+ if (p.tooltip) {
+ hint = document.createElement('p');
+ hint.className = 'md-hint';
+ hint.id = `${id}-hint`;
+ hint.textContent = p.tooltip;
+ }
+ const update = (v) => {
+ values[p.id] = v;
+ applyVisibility(container, schema, values);
+ };
+
+ if (p.type === 'boolean') {
+ field.classList.add('md-field--inline');
+ const input = document.createElement('input');
+ input.type = 'checkbox';
+ input.className = 'md-check';
+ input.id = id;
+ input.checked = Boolean(values[p.id]);
+ input.addEventListener('change', () => update(input.checked));
+ field.append(input, label);
+ } else if (p.type === 'select') {
+ const select = document.createElement('select');
+ select.className = 'md-input';
+ select.id = id;
+ (p.options || []).forEach((opt, i) => {
+ const o = document.createElement('option');
+ o.value = String(i);
+ o.textContent = opt.label ?? String(opt.value);
+ if (String(opt.value) === String(values[p.id])) o.selected = true;
+ select.append(o);
+ });
+ select.addEventListener('change', () => update(p.options[Number(select.value)]?.value));
+ field.append(label, select);
+ } else if (p.type === 'int' || p.type === 'float') {
+ const bounded = Number.isFinite(p.min) && Number.isFinite(p.max);
+ const step = p.step ?? (p.type === 'int' ? 1 : 0.01);
+ const number = document.createElement('input');
+ number.type = 'number';
+ number.className = 'md-input md-input--mono';
+ number.id = id;
+ number.step = String(step);
+ if (Number.isFinite(p.min)) number.min = String(p.min);
+ if (Number.isFinite(p.max)) number.max = String(p.max);
+ number.value = String(values[p.id] ?? '');
+ if (bounded) {
+ const row = document.createElement('div');
+ row.className = 'md-num-row';
+ const range = document.createElement('input');
+ range.type = 'range';
+ range.className = 'md-range';
+ range.min = String(p.min);
+ range.max = String(p.max);
+ range.step = String(step);
+ range.value = number.value;
+ range.setAttribute('aria-label', `${p.label || p.id} slider`);
+ range.addEventListener('input', () => {
+ number.value = range.value;
+ update(clampNumber(range.value, p));
+ });
+ number.addEventListener('change', () => {
+ const v = clampNumber(number.value, p);
+ number.value = String(v);
+ range.value = String(v);
+ update(v);
+ });
+ row.append(range, number);
+ field.append(label, row);
+ } else {
+ number.addEventListener('change', () => {
+ const v = clampNumber(number.value, p);
+ number.value = String(v);
+ update(v);
+ });
+ field.append(label, number);
+ }
+ } else {
+ // 'string' and 'file-select' (a path on the visitor's disk; the
+ // browser cannot browse it, so it is typed).
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.className = 'md-input';
+ input.id = id;
+ input.spellcheck = false;
+ input.value = String(values[p.id] ?? '');
+ if (p.type === 'file-select') {
+ input.classList.add('md-input--mono');
+ input.placeholder = 'Full path on this computer';
+ }
+ input.addEventListener('input', () => update(input.value));
+ field.append(label, input);
+ }
+ if (hint) {
+ field.querySelector('input, select')?.setAttribute('aria-describedby', hint.id);
+ field.append(hint);
+ }
+ return field;
+ });
+ container.replaceChildren(...fields);
+ applyVisibility(container, schema, values);
+}
+
+// Only send the params the visitor can see; hidden ones belong to other modes.
+function visibleValues(schema, values) {
+ const out = {};
+ for (const p of schema) if (isVisible(p, values) && values[p.id] !== undefined) out[p.id] = values[p.id];
+ return out;
+}
+
+// ── input: image ───────────────────────────────────────────────────────────
+
+function setImage(blob, name) {
+ if (!blob) return;
+ if (!/^image\/(png|jpeg|webp)$/.test(blob.type)) {
+ toast('Use a PNG, JPEG or WebP image.');
+ return;
+ }
+ if (blob.size > MAX_IMAGE_BYTES) {
+ toast('That image is over 20 MB. Use a smaller one.');
+ return;
+ }
+ if (state.imageUrl) URL.revokeObjectURL(state.imageUrl);
+ state.image = blob;
+ state.imageName = name || 'image';
+ state.imageUrl = URL.createObjectURL(blob);
+ el.dropImg.src = state.imageUrl;
+ el.dropImg.alt = `Input image: ${state.imageName}`;
+ el.dropImg.hidden = false;
+ el.drop.classList.add('has-image');
+ el.dropName.textContent = `${state.imageName} · ${formatBytes(blob.size)}`;
+ show(el.dropMeta, true);
+ if (!el.saveName.value || el.saveName.dataset.auto === '1') {
+ el.saveName.value = humanName(state.imageName);
+ el.saveName.dataset.auto = '1';
+ }
+ updateGenerateState();
+}
+
+function clearImage() {
+ if (state.imageUrl) URL.revokeObjectURL(state.imageUrl);
+ state.image = null;
+ state.imageUrl = null;
+ el.dropImg.hidden = true;
+ el.dropImg.removeAttribute('src');
+ el.drop.classList.remove('has-image');
+ show(el.dropMeta, false);
+ el.file.value = '';
+ updateGenerateState();
+}
+
+el.drop.addEventListener('click', () => el.file.click());
+el.drop.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ el.file.click();
+ }
+});
+el.file.addEventListener('change', () => {
+ const f = el.file.files?.[0];
+ if (f) setImage(f, f.name);
+});
+for (const type of ['dragenter', 'dragover']) {
+ el.drop.addEventListener(type, (e) => {
+ e.preventDefault();
+ el.drop.classList.add('is-over');
+ });
+}
+for (const type of ['dragleave', 'drop']) {
+ el.drop.addEventListener(type, () => el.drop.classList.remove('is-over'));
+}
+el.drop.addEventListener('drop', (e) => {
+ e.preventDefault();
+ const f = [...(e.dataTransfer?.files || [])].find((x) => x.type.startsWith('image/'));
+ if (f) setImage(f, f.name);
+ else toast('Drop an image file (PNG, JPEG or WebP).');
+});
+el.clearImage.addEventListener('click', clearImage);
+
+document.addEventListener('paste', (e) => {
+ if (el.studio.hidden) return;
+ const target = e.target;
+ if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) return;
+ const item = [...(e.clipboardData?.items || [])].find((i) => i.kind === 'file' && i.type.startsWith('image/'));
+ const f = item?.getAsFile();
+ if (!f) return;
+ e.preventDefault();
+ selectTab('image');
+ setImage(f, f.name && f.name !== 'image.png' ? f.name : `pasted.${f.type.split('/')[1] || 'png'}`);
+ toast('Image pasted.');
+});
+
+// ── input: text prompt via the three.ws concept-image lane ─────────────────
+
+function selectTab(which) {
+ const image = which === 'image';
+ el.tabImage.setAttribute('aria-selected', String(image));
+ el.tabPrompt.setAttribute('aria-selected', String(!image));
+ el.tabImage.tabIndex = image ? 0 : -1;
+ el.tabPrompt.tabIndex = image ? -1 : 0;
+ el.paneImage.hidden = !image;
+ el.panePrompt.hidden = image;
+}
+
+el.tabImage.addEventListener('click', () => selectTab('image'));
+el.tabPrompt.addEventListener('click', () => {
+ selectTab('prompt');
+ el.prompt.focus();
+});
+for (const tab of [el.tabImage, el.tabPrompt]) {
+ tab.addEventListener('keydown', (e) => {
+ if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
+ const next = tab === el.tabImage ? el.tabPrompt : el.tabImage;
+ next.click();
+ next.focus();
+ });
+}
+
+function conceptErrorMessage(status, data) {
+ if (status === 402) return 'You have used today\'s free concept images on this network. Upload your own image instead, or come back tomorrow.';
+ if (status === 422) return data?.error_description || data?.message || 'That prompt was refused by the image model. Try describing it differently.';
+ if (status === 429) return 'The image lane is busy. Try again in a few seconds.';
+ if (status === 400) return data?.error_description || data?.message || 'That prompt could not be used. Keep it under 1000 characters.';
+ return 'The concept image could not be drawn right now. Try again shortly, or upload an image instead.';
+}
+
+async function drawConcept() {
+ const text = el.prompt.value.trim();
+ show(el.conceptError, false);
+ if (text.length < 3) {
+ el.conceptError.textContent = 'Describe the object in a few words first.';
+ show(el.conceptError, true);
+ el.prompt.focus();
+ return;
+ }
+ setBusy(el.concept, true);
+ try {
+ const prompt = `${text}. Single object, centered, full view, plain light grey background, soft even studio lighting, no text`;
+ const res = await fetch('/api/v1/ai/image', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ prompt, aspect_ratio: '1:1' }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok || !data?.url) throw Object.assign(new Error(conceptErrorMessage(res.status, data)), { status: res.status });
+ const imgRes = await fetch(data.url, { mode: 'cors' });
+ if (!imgRes.ok) throw new Error('The concept image was drawn but could not be downloaded. Try again.');
+ const blob = await imgRes.blob();
+ const typed = /^image\/(png|jpeg|webp)$/.test(blob.type) ? blob : new Blob([blob], { type: 'image/jpeg' });
+ setImage(typed, `${text.slice(0, 40).replace(/[^\w -]+/g, '').trim() || 'concept'}.${typed.type.split('/')[1].replace('jpeg', 'jpg')}`);
+ el.saveName.value = text.slice(0, 120);
+ el.saveName.dataset.auto = '1';
+ selectTab('image');
+ toast(data.free && data.quota?.remaining !== undefined ? `Concept ready. ${data.quota.remaining} free left today.` : 'Concept ready. Check it, then generate.');
+ } catch (err) {
+ el.conceptError.textContent = err?.message || 'The concept image could not be drawn.';
+ show(el.conceptError, true);
+ } finally {
+ setBusy(el.concept, false);
+ }
+}
+
+el.concept.addEventListener('click', drawConcept);
+el.prompt.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
+ e.preventDefault();
+ drawConcept();
+ }
+});
+
+// ── generate ───────────────────────────────────────────────────────────────
+
+function updateGenerateState() {
+ const running = Boolean(state.job);
+ el.generate.disabled = !(state.modelId && state.image && !running && !state.busy);
+ let hint;
+ if (running) hint = 'Generating on your GPU.';
+ else if (!state.models.length) hint = 'Install a model in Modly to start.';
+ else if (!state.image) hint = 'Add an image, or draw one from a text prompt.';
+ else {
+ const m = state.models.find((x) => x.id === state.modelId);
+ hint = m && !m.downloaded ? `${m.name} downloads its weights on the first run, which can take a while.` : 'Runs entirely on this computer.';
+ }
+ el.generateHint.textContent = hint;
+}
+
+function setStage(name) {
+ el.stage.dataset.stage = name;
+}
+
+function restStage() {
+ setStage(state.current ? 'ready' : 'empty');
+}
+
+function showStageError(err, retry) {
+ const copy = modlyErrorCopy(err);
+ el.stageErrorTitle.textContent = copy.title;
+ el.stageErrorText.textContent = copy.text;
+ const detail = err instanceof ModlyError ? err.detail : '';
+ el.stageErrorPre.textContent = detail;
+ show(el.stageErrorDetail, Boolean(detail));
+ state.retryAction = retry || null;
+ show(el.stageRetry, Boolean(retry));
+ setStage('error');
+}
+
+el.stageRetry.addEventListener('click', () => state.retryAction?.());
+el.stageDismiss.addEventListener('click', restStage);
+
+const STATE_STEP = { pending: 'Queued in Modly', running: 'Generating', done: 'Fetching the mesh from Modly' };
+
+function renderProgress(pct, step, runState) {
+ el.progressBar.style.transform = `scaleX(${pct / 100})`;
+ el.progress.setAttribute('aria-valuenow', String(pct));
+ el.pct.textContent = `${pct}%`;
+ el.step.textContent = step || STATE_STEP[runState] || 'Generating';
+}
+
+let elapsedTimer = null;
+
+async function generate() {
+ if (!state.origin || !state.image || !state.modelId || state.job) return;
+ const controller = new AbortController();
+ const started = Date.now();
+ state.job = { controller };
+ updateGenerateState();
+ renderProgress(0, 'Sending your image to Modly', 'pending');
+ el.elapsed.textContent = '0:00';
+ clearInterval(elapsedTimer);
+ elapsedTimer = setInterval(() => {
+ el.elapsed.textContent = formatElapsed(Date.now() - started);
+ }, 1000);
+ setStage('generating');
+ el.cancel.disabled = false;
+ el.cancel.focus();
+
+ const model = state.models.find((m) => m.id === state.modelId);
+ try {
+ const result = await generateWithModly(state.origin, {
+ image: state.image,
+ modelId: state.modelId,
+ params: visibleValues(state.paramsSchema, state.paramValues),
+ onProgress: renderProgress,
+ signal: controller.signal,
+ });
+ state.history = [];
+ await showResult({ workspacePath: result.workspacePath, blob: result.blob, modelId: result.modelId });
+ if (model && !model.downloaded) refreshModels();
+ } catch (err) {
+ if (err?.code === 'CANCELLED') {
+ restStage();
+ toast('Generation cancelled. Modly stopped the run.');
+ } else {
+ showStageError(err, generate);
+ }
+ } finally {
+ clearInterval(elapsedTimer);
+ state.job = null;
+ updateGenerateState();
+ }
+}
+
+el.generate.addEventListener('click', generate);
+el.cancel.addEventListener('click', () => {
+ el.cancel.disabled = true;
+ el.step.textContent = 'Cancelling';
+ state.job?.controller.abort();
+});
+
+// ── result: preview, mesh tools, download, save ────────────────────────────
+
+/** Put a GLB on the stage. `pushHistory` keeps the previous one for Undo. */
+async function showResult(next, { pushHistory = false } = {}) {
+ await ensureModelViewer();
+ if (pushHistory && state.current) state.history.push(state.current);
+ setCurrent(next);
+ await showInViewer(next.blob);
+ setStage('ready');
+}
+
+function setCurrent(next) {
+ state.current = { faceCount: null, modelId: null, ...next };
+ el.metaPath.textContent = next.workspacePath;
+ el.metaPath.title = `Modly workspace: ${next.workspacePath}`;
+ renderMetaStats();
+ show(el.meta, true);
+ show(el.result, true);
+ el.undo.disabled = state.history.length === 0;
+ for (const btn of el.ops.querySelectorAll('button')) btn.disabled = false;
+ el.save.disabled = false;
+ if (!el.saveName.value) el.saveName.value = humanName(next.workspacePath);
+ show(el.saveDone, false);
+ show(el.saveError, false);
+}
+
+function renderMetaStats() {
+ const c = state.current;
+ const stats = [formatBytes(c.blob.size)];
+ if (c.faceCount) stats.push(`${Number(c.faceCount).toLocaleString()} faces`);
+ const model = c.modelId ? state.models.find((m) => m.id === c.modelId) : null;
+ if (model) stats.push(model.name);
+ el.metaStats.textContent = stats.join(' · ');
+}
+
+function showInViewer(blob) {
+ return new Promise((resolve) => {
+ if (!state.viewer) {
+ const mv = document.createElement('model-viewer');
+ mv.setAttribute('camera-controls', '');
+ mv.setAttribute('auto-rotate', '');
+ mv.setAttribute('shadow-intensity', '0.8');
+ mv.setAttribute('exposure', '1');
+ mv.setAttribute('interaction-prompt', 'none');
+ // The stage keeps the viewer hidden until the model has loaded, and
+ // model-viewer's default lazy loading waits for visibility.
+ mv.setAttribute('loading', 'eager');
+ mv.setAttribute('alt', 'Generated 3D model preview');
+ el.viewerHost.append(mv);
+ state.viewer = mv;
+ }
+ const mv = state.viewer;
+ const previousUrl = mv.dataset.objectUrl;
+ const url = URL.createObjectURL(blob);
+ mv.dataset.objectUrl = url;
+ const done = () => {
+ mv.removeEventListener('load', done);
+ mv.removeEventListener('error', done);
+ if (previousUrl) URL.revokeObjectURL(previousUrl);
+ resolve();
+ };
+ mv.addEventListener('load', done);
+ mv.addEventListener('error', done);
+ mv.src = url;
+ });
+}
+
+el.stage.addEventListener(
+ 'error',
+ (e) => {
+ if (e.target === state.viewer) toast('The preview could not render this file. Download and save still work.');
+ },
+ true,
+);
+
+async function openWorkspaceFile(path) {
+ el.loadingText.textContent = 'Loading the model from Modly';
+ setStage('loading');
+ const { blob } = await downloadModlyGlb(state.origin, path);
+ state.history = [];
+ await showResult({ workspacePath: path, blob });
+}
+
+async function openFromWorkspace(e) {
+ e.preventDefault();
+ show(el.openError, false);
+ el.openPath.removeAttribute('aria-invalid');
+ let path;
+ try {
+ path = validateModlyWorkspacePath(el.openPath.value.trim());
+ } catch {
+ el.openError.textContent = 'Use a path inside the Modly workspace, like Default/model.glb (no leading slash, no "..").';
+ show(el.openError, true);
+ el.openPath.setAttribute('aria-invalid', 'true');
+ el.openPath.focus();
+ return;
+ }
+ try {
+ await openWorkspaceFile(path);
+ el.saveName.value = humanName(path);
+ el.saveName.dataset.auto = '0';
+ } catch (err) {
+ if (err?.code === 'NOT_FOUND') {
+ el.openError.textContent = `There is no file at ${path} in the Modly workspace. Check the folder and the file name.`;
+ show(el.openError, true);
+ restStage();
+ return;
+ }
+ showStageError(err, () => el.openForm.requestSubmit());
+ }
+}
+
+el.openForm.addEventListener('submit', openFromWorkspace);
+
+// mesh tools (Modly's /optimize ops, run on the visitor's machine)
+
+async function loadOps() {
+ try {
+ state.ops = await listModlyMeshOps(state.origin);
+ } catch {
+ state.ops = [];
+ }
+ renderOps();
+}
+
+function renderOps() {
+ if (!state.ops.length) {
+ el.ops.replaceChildren();
+ el.opsError.textContent = 'This Modly install does not offer mesh tools. Updating Modly adds repair, decimate and smooth.';
+ show(el.opsError, true);
+ return;
+ }
+ show(el.opsError, false);
+ const cards = state.ops.map((op) => {
+ const card = document.createElement('div');
+ card.className = 'md-op';
+ const head = document.createElement('div');
+ head.className = 'md-op__head';
+ const title = document.createElement('span');
+ title.className = 'md-op__title';
+ title.textContent = op.label;
+ const run = document.createElement('button');
+ run.type = 'button';
+ run.className = 'md-btn md-btn--sm';
+ const label = document.createElement('span');
+ label.className = 'md-btn__label';
+ label.textContent = 'Run';
+ const spinner = document.createElement('span');
+ spinner.className = 'md-btn__spinner';
+ spinner.setAttribute('aria-hidden', 'true');
+ run.append(label, spinner);
+ run.setAttribute('aria-label', `Run ${op.label}`);
+ run.disabled = !state.current;
+ head.append(title, run);
+ const form = document.createElement('div');
+ form.className = 'md-form';
+ state.opValues[op.id] = defaultValues(op.paramsSchema);
+ renderSchemaForm(form, op.paramsSchema, state.opValues[op.id], `mdo-${op.id}`);
+ card.append(head, form);
+ run.addEventListener('click', () => runOp(op, run));
+ return card;
+ });
+ el.ops.replaceChildren(...cards);
+}
+
+function setToolsBusy(busy) {
+ state.busy = busy;
+ for (const b of el.ops.querySelectorAll('button')) b.disabled = busy || !state.current;
+ el.undo.disabled = busy || state.history.length === 0;
+ el.save.disabled = busy || !state.current;
+ el.download.disabled = busy || !state.current;
+ updateGenerateState();
+}
+
+async function runOp(op, button) {
+ if (!state.current || state.busy) return;
+ show(el.opsError, false);
+ setToolsBusy(true);
+ setBusy(button, true);
+ try {
+ const result = await modlyMeshOp(state.origin, {
+ glb: state.current.workspacePath,
+ op: op.id,
+ params: visibleValues(op.paramsSchema, state.opValues[op.id]),
+ });
+ await showResult(
+ { workspacePath: result.workspacePath, blob: result.blob, modelId: state.current.modelId, faceCount: result.details?.face_count ?? null },
+ { pushHistory: true },
+ );
+ toast(`${op.label} done.`);
+ } catch (err) {
+ const copy = modlyErrorCopy(err);
+ el.opsError.textContent = `${copy.title}. ${copy.text}`;
+ show(el.opsError, true);
+ } finally {
+ setBusy(button, false);
+ setToolsBusy(false);
+ }
+}
+
+el.undo.addEventListener('click', async () => {
+ const prev = state.history.pop();
+ if (!prev) return;
+ setCurrent(prev);
+ await showInViewer(prev.blob);
+ setStage('ready');
+ toast('Back to the previous version.');
+});
+
+// download
+
+function downloadBlob(blob, filename) {
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = filename;
+ document.body.append(a);
+ a.click();
+ a.remove();
+ // Release the object URL once the download manager has surely read it.
+ setTimeout(() => URL.revokeObjectURL(url), 60000);
+}
+
+el.download.addEventListener('click', () => {
+ if (state.current) downloadBlob(state.current.blob, `${fileBaseName(state.current.workspacePath)}.glb`);
+});
+
+// save to account
+
+async function saveToAccount(e) {
+ e?.preventDefault();
+ if (!state.current) return;
+ show(el.saveError, false);
+ show(el.saveDone, false);
+ const name = el.saveName.value.trim() || humanName(state.current.workspacePath);
+ el.saveName.value = name;
+
+ let me;
+ try {
+ me = await getMe();
+ } catch {
+ // The session check itself failed (network); let the upload decide.
+ me = { unknown: true };
+ }
+ if (!me) {
+ writeStore(
+ 'sessionStorage',
+ RESUME_KEY,
+ JSON.stringify({ path: state.current.workspacePath, modelId: state.current.modelId, name, visibility: el.saveVis.value, at: Date.now() }),
+ );
+ show(el.saveSignedOut, true);
+ el.signIn.focus();
+ return;
+ }
+ show(el.saveSignedOut, false);
+
+ const controller = new AbortController();
+ state.saveController = controller;
+ setBusy(el.save, true);
+ show(el.saveProgress, true);
+ el.saveProgressBar.style.transform = 'scaleX(0)';
+ try {
+ const model = state.models.find((m) => m.id === state.current.modelId);
+ const avatar = await saveRemoteGlbToAccount(
+ state.current.blob,
+ {
+ name,
+ visibility: el.saveVis.value,
+ source: 'reconstruct',
+ tags: ['modly', 'local-gpu'],
+ source_meta: {
+ generator: 'modly',
+ model_id: state.current.modelId || null,
+ model_name: model?.name || null,
+ modly_path: state.current.workspacePath,
+ },
+ },
+ {
+ signal: controller.signal,
+ onProgress: (pct) => {
+ el.saveProgressBar.style.transform = `scaleX(${Math.max(0, Math.min(100, pct)) / 100})`;
+ el.saveProgress.setAttribute('aria-valuenow', String(Math.round(pct)));
+ },
+ },
+ );
+ writeStore('sessionStorage', RESUME_KEY, null);
+ el.saveLink.href = `/avatars/${encodeURIComponent(avatar.id)}`;
+ show(el.saveDone, true);
+ el.saveLink.focus();
+ } catch (err) {
+ if (err?.code === 'not_signed_in' || err?.status === 401) {
+ show(el.saveSignedOut, true);
+ } else {
+ el.saveError.textContent = `Could not save to your account${err?.stage ? ` (${err.stage} step)` : ''}. ${err?.message || ''} Try again; the model is still in your Modly workspace.`;
+ show(el.saveError, true);
+ }
+ } finally {
+ state.saveController = null;
+ setBusy(el.save, false);
+ show(el.saveProgress, false);
+ }
+}
+
+el.saveForm.addEventListener('submit', saveToAccount);
+el.saveName.addEventListener('input', () => {
+ el.saveName.dataset.auto = '0';
+});
+el.signIn.href = `/login?next=${encodeURIComponent('/modly')}`;
+
+// After signing in, the visitor lands back here: reload the same workspace file
+// from Modly and finish the save they asked for.
+async function resumeAfterSignIn() {
+ const raw = readStore('sessionStorage', RESUME_KEY);
+ if (!raw) return;
+ let stash;
+ try {
+ stash = JSON.parse(raw);
+ } catch {
+ writeStore('sessionStorage', RESUME_KEY, null);
+ return;
+ }
+ if (!stash?.path || Date.now() - Number(stash.at || 0) > 60 * 60 * 1000) {
+ writeStore('sessionStorage', RESUME_KEY, null);
+ return;
+ }
+ const me = await getMe().catch(() => null);
+ if (!me) return;
+ try {
+ el.loadingText.textContent = 'Loading the model from Modly';
+ setStage('loading');
+ const { blob } = await downloadModlyGlb(state.origin, stash.path);
+ state.history = [];
+ await showResult({ workspacePath: stash.path, blob, modelId: stash.modelId || null });
+ if (stash.name) el.saveName.value = stash.name;
+ if (stash.visibility) el.saveVis.value = stash.visibility;
+ toast('Welcome back. Finishing your save.');
+ await saveToAccount();
+ } catch (err) {
+ writeStore('sessionStorage', RESUME_KEY, null);
+ showStageError(err, null);
+ }
+}
+
+// ── boot ───────────────────────────────────────────────────────────────────
+
+el.installLink.href = MODLY_INSTALL_URL;
+el.refreshModels.addEventListener('click', refreshModels);
+el.base.value = getModlyOriginOverride();
+el.baseForm.addEventListener('submit', (e) => {
+ e.preventDefault();
+ connect();
+});
+for (const btn of el.conn.querySelectorAll('[data-action="retry"]')) btn.addEventListener('click', connect);
+
+window.addEventListener('pagehide', () => {
+ // Leaving mid-run cancels it inside Modly instead of leaving the GPU busy.
+ state.job?.controller.abort();
+ state.saveController?.abort();
+});
+
+// Probing loopback can raise the browser's local-access prompt, so a first
+// visit waits for the Connect click, after the page has explained why. A
+// returning visitor (connected before, or mid sign-in round trip) has seen
+// that prompt already, so the page probes straight away.
+if (readStore('localStorage', CONNECTED_KEY) || readStore('sessionStorage', RESUME_KEY)) {
+ connect();
+} else {
+ setConnState('idle');
+}
diff --git a/workers/modly/gltf_meshopt.py b/workers/modly/gltf_meshopt.py
new file mode 100644
index 000000000..10f7ba4ad
--- /dev/null
+++ b/workers/modly/gltf_meshopt.py
@@ -0,0 +1,107 @@
+"""EXT_meshopt_compression decoding for caller-supplied glTF input.
+
+Vendored byte-identical into every worker that loads a mesh a caller handed it,
+exactly like worker_security.py: each worker's Docker build context is its own
+directory, so `../` is unreachable. `npm run check:vendored` fails if the copies
+drift apart.
+
+Why it exists: trimesh has no decoder for EXT_meshopt_compression. A compressed
+asset stores its geometry in compressed buffer views and declares a second,
+empty "fallback" buffer that only exists once something decodes into it, so
+trimesh dies on the bufferView lookup with a bare `IndexError: list index out of
+range`. Meshopt is what gltfpack emits and what most three.ws avatars ship as,
+so this was a hard failure on our own assets (verified 2026-08-13:
+/avatars/michelle.glb failed every stylize filter in production). gltfpack is
+the same project's CLI and decodes what it encoded, so the fix is to transcode
+the asset to plain glTF before any reader touches it.
+
+The binary is pinned by release tag and checksum in each worker's Dockerfile.
+Set GLTFPACK_BIN to run the path against your own copy locally.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import subprocess
+import tempfile
+from pathlib import Path
+from typing import Optional
+
+log = logging.getLogger("gltf-meshopt")
+
+MESHOPT_EXTENSION = "EXT_meshopt_compression"
+GLTFPACK_BIN = os.environ.get("GLTFPACK_BIN", "gltfpack")
+GLTFPACK_TIMEOUT_S = int(os.environ.get("GLTFPACK_TIMEOUT_S", "120"))
+
+
+def gltf_document(data: bytes, suffix: str = ".glb") -> Optional[dict]:
+ """The glTF JSON of a .glb/.gltf payload, or None when it is neither."""
+ if suffix == ".gltf":
+ try:
+ return json.loads(data)
+ except ValueError:
+ return None
+ if suffix != ".glb" or len(data) < 20 or data[:4] != b"glTF":
+ return None
+ chunk_length = int.from_bytes(data[12:16], "little")
+ if data[16:20] != b"JSON":
+ return None
+ try:
+ return json.loads(data[20:20 + chunk_length])
+ except ValueError:
+ return None
+
+
+def uses_meshopt(document: Optional[dict]) -> bool:
+ """True when the asset needs a meshopt decode before any reader can use it.
+
+ Checked against both extension lists: an asset that only *uses* the
+ extension still stores its geometry in the compressed views, and its
+ fallback buffer stays empty until something decodes into it.
+ """
+ if not document:
+ return False
+ declared = set(document.get("extensionsRequired") or []) | set(document.get("extensionsUsed") or [])
+ return MESHOPT_EXTENSION in declared
+
+
+def transcode_meshopt(data: bytes, suffix: str = ".glb") -> bytes:
+ """Rewrite a meshopt-compressed asset as a plain GLB with gltfpack.
+
+ `-noq` keeps the source quantization instead of re-quantizing on the way
+ out, so downstream geometry is derived from what the author shipped.
+ """
+ with tempfile.TemporaryDirectory() as tmpdir:
+ src = Path(tmpdir) / f"input{suffix}"
+ dst = Path(tmpdir) / "decoded.glb"
+ src.write_bytes(data)
+ try:
+ proc = subprocess.run(
+ [GLTFPACK_BIN, "-i", str(src), "-o", str(dst), "-noq"],
+ capture_output=True,
+ timeout=GLTFPACK_TIMEOUT_S,
+ )
+ except FileNotFoundError as exc:
+ raise ValueError(
+ f"input uses {MESHOPT_EXTENSION} and the gltfpack decoder is not installed"
+ ) from exc
+ except subprocess.TimeoutExpired as exc:
+ raise ValueError(f"{MESHOPT_EXTENSION} decode timed out") from exc
+ if proc.returncode != 0 or not dst.exists():
+ detail = (proc.stderr or b"").decode("utf-8", "replace").strip().splitlines()
+ raise ValueError(f"{MESHOPT_EXTENSION} decode failed: {detail[-1][:200] if detail else 'no output'}")
+ return dst.read_bytes()
+
+
+def decode_if_meshopt(data: bytes, suffix: str = ".glb") -> tuple[bytes, str]:
+ """Return (data, suffix) ready for trimesh, decoding meshopt when present.
+
+ A payload that is not compressed glTF is handed back untouched, so this is
+ safe to call on every input path.
+ """
+ if not uses_meshopt(gltf_document(data, suffix)):
+ return data, suffix
+ log.info("input declares %s; decoding with gltfpack before load", MESHOPT_EXTENSION)
+ return transcode_meshopt(data, suffix), ".glb"
diff --git a/workers/modly/instance_health.py b/workers/modly/instance_health.py
new file mode 100644
index 000000000..124dbc40a
--- /dev/null
+++ b/workers/modly/instance_health.py
@@ -0,0 +1,219 @@
+"""Instance self-care for the TRELLIS worker: host memory and task liveness.
+
+Pure stdlib, no torch and no CUDA, so every decision here is unit tested on any
+machine (see test_instance_health.py) and main.py only wires it in.
+
+Why this module exists (production, 2026-10-03 to 2026-10-08):
+
+ * The single warm L4 instance was OOM-killed twelve times in five days
+ ("Container terminated on signal 9"). Cloud Run's memory utilization for
+ the revision climbed in steps after each heavy job (0.46 -> 0.56 -> 0.71 ->
+ 0.81 -> 0.88 -> 0.91) and never came back down, then a mesh postprocess
+ (decimate, invisible-face removal, UV unwrap, texture bake) pushed it past
+ the 32 GiB ceiling, which is the most memory Cloud Run gives an L4 instance.
+ That is glibc keeping freed heap in per-thread arenas: the pipeline runs in
+ executor threads, each of which grows its own arena, and nothing hands the
+ freed pages back to the kernel.
+ * Every kill took the in-flight job with it, and the queued job behind it.
+ Their durable GCS records stayed "running" until a 30 minute orphan window
+ expired, long after the caller's poll budget, so the forge's lane failover
+ never saw a failure to act on and the user just watched a spinner.
+
+The fixes are split by what they guard against:
+
+ trim_heap() returns freed heap to the kernel after every job.
+ read_memory() reports what the instance actually holds, so each job
+ logs its footprint and the recycle guard has a number.
+ should_recycle() decides when an instance has ratcheted far enough that
+ it should restart BETWEEN jobs rather than die inside one.
+ task_is_orphaned() lets a heartbeat-refreshed record expire in minutes, not
+ half an hour, once its runner is gone.
+"""
+
+from __future__ import annotations
+
+import ctypes
+import ctypes.util
+import os
+from dataclasses import dataclass
+from typing import Optional
+
+# How often a live task refreshes its durable record, and how long a queued or
+# running record may go without a refresh before it is declared orphaned. Six
+# missed beats is far beyond any scheduling hiccup on a healthy instance, and
+# still well inside the forge client's ~300 s poll budget, so the failure lands
+# while a client is still listening and the lane failover can redispatch.
+HEARTBEAT_SECS = 30.0
+ORPHAN_AFTER_SECS = 180.0
+
+# Recycle once the instance holds this share of its memory limit after a job...
+RECYCLE_FRACTION = float(os.environ.get("MEMORY_RECYCLE_FRACTION", "0.80"))
+# ...and only if it has grown at least this much past its post-load baseline. The
+# growth floor is what stops a mismeasured or simply large baseline from turning
+# into a restart after every single job.
+RECYCLE_MIN_GROWTH = float(os.environ.get("MEMORY_RECYCLE_MIN_GROWTH", "0.15"))
+
+_CGROUP_V2 = "/sys/fs/cgroup"
+_CGROUP_V1 = "/sys/fs/cgroup/memory"
+_MEMINFO = "/proc/meminfo"
+
+
+@dataclass(frozen=True)
+class MemorySample:
+ used_bytes: int
+ limit_bytes: int
+ source: str
+
+ @property
+ def fraction(self) -> float:
+ return self.used_bytes / self.limit_bytes if self.limit_bytes else 0.0
+
+ def describe(self) -> str:
+ gib = 1024 ** 3
+ return (
+ f"{self.used_bytes / gib:.1f}/{self.limit_bytes / gib:.1f} GiB "
+ f"({self.fraction:.0%}, {self.source})"
+ )
+
+
+def _read(path: str) -> Optional[str]:
+ try:
+ with open(path, encoding="ascii") as fh:
+ return fh.read()
+ except OSError:
+ return None
+
+
+def _stat_fields(text: str) -> dict[str, int]:
+ fields: dict[str, int] = {}
+ for line in text.splitlines():
+ parts = line.split()
+ if len(parts) >= 2 and parts[1].isdigit():
+ fields[parts[0].rstrip(":")] = int(parts[1])
+ return fields
+
+
+def _from_cgroup_v2(root: str) -> Optional[MemorySample]:
+ stat, limit = _read(os.path.join(root, "memory.stat")), _read(os.path.join(root, "memory.max"))
+ if stat is None or limit is None or not limit.strip().isdigit():
+ return None
+ fields = _stat_fields(stat)
+ if "anon" not in fields:
+ return None
+ # anon is the process heap; shmem is tmpfs, which is where Cloud Run's
+ # in-memory filesystem (and so the staged weights in /tmp) is charged.
+ # Page cache is left out on purpose: the kernel reclaims it before it OOMs.
+ return MemorySample(fields["anon"] + fields.get("shmem", 0), int(limit.strip()), "cgroup2")
+
+
+def _from_cgroup_v1(root: str) -> Optional[MemorySample]:
+ stat = _read(os.path.join(root, "memory.stat"))
+ limit = _read(os.path.join(root, "memory.limit_in_bytes"))
+ if stat is None or limit is None or not limit.strip().isdigit():
+ return None
+ fields = _stat_fields(stat)
+ if "total_rss" not in fields:
+ return None
+ limit_bytes = int(limit.strip())
+ # An unlimited v1 group reports a sentinel near 2**63; it says nothing about
+ # this instance's ceiling, so defer to /proc/meminfo instead.
+ if limit_bytes >= 1 << 60:
+ return None
+ return MemorySample(fields["total_rss"] + fields.get("total_shmem", 0), limit_bytes, "cgroup1")
+
+
+def _from_meminfo(path: str) -> Optional[MemorySample]:
+ text = _read(path)
+ if text is None:
+ return None
+ fields = _stat_fields(text)
+ total, available = fields.get("MemTotal"), fields.get("MemAvailable")
+ if not total or available is None:
+ return None
+ # /proc/meminfo is in KiB. MemAvailable already discounts reclaimable cache.
+ return MemorySample((total - available) * 1024, total * 1024, "meminfo")
+
+
+def read_memory(
+ cgroup_v2_root: str = _CGROUP_V2,
+ cgroup_v1_root: str = _CGROUP_V1,
+ meminfo_path: str = _MEMINFO,
+) -> Optional[MemorySample]:
+ """Best available view of the memory this instance holds against its limit.
+
+ Never raises. Returns None when no source is readable, and every caller
+ treats None as "unknown", which never triggers a recycle.
+ """
+ for reader, arg in (
+ (_from_cgroup_v2, cgroup_v2_root),
+ (_from_cgroup_v1, cgroup_v1_root),
+ (_from_meminfo, meminfo_path),
+ ):
+ try:
+ sample = reader(arg)
+ except (ValueError, ZeroDivisionError):
+ sample = None
+ if sample is not None and sample.limit_bytes > 0:
+ return sample
+ return None
+
+
+def should_recycle(
+ current: Optional[MemorySample],
+ baseline: Optional[MemorySample],
+ threshold: float = RECYCLE_FRACTION,
+ min_growth: float = RECYCLE_MIN_GROWTH,
+) -> bool:
+ """True when the instance should restart between jobs.
+
+ Both conditions must hold: the instance is near its ceiling, AND it got
+ there by growing since the model finished loading. Without a baseline (the
+ load has not completed, or memory is unreadable) the answer is always no.
+ """
+ if current is None or baseline is None:
+ return False
+ return current.fraction >= threshold and current.fraction - baseline.fraction >= min_growth
+
+
+_libc = None
+
+
+def trim_heap() -> bool:
+ """Hand freed heap pages back to the kernel (glibc malloc_trim).
+
+ Returns False on a libc without malloc_trim (musl, macOS), where there is
+ nothing to do. Never raises.
+ """
+ global _libc
+ try:
+ if _libc is None:
+ _libc = ctypes.CDLL(ctypes.util.find_library("c") or "libc.so.6")
+ trim = getattr(_libc, "malloc_trim", None)
+ if trim is None:
+ return False
+ trim.argtypes = [ctypes.c_size_t]
+ trim.restype = ctypes.c_int
+ trim(0)
+ return True
+ except OSError:
+ return False
+
+
+def task_is_orphaned(
+ status: Optional[str],
+ updated_at: object,
+ now: float,
+ orphan_after: float = ORPHAN_AFTER_SECS,
+) -> bool:
+ """True when a queued or running record has gone stale.
+
+ A live runner refreshes updated_at every HEARTBEAT_SECS, so a record that
+ has not moved for orphan_after seconds belongs to an instance that died.
+ A record with no usable timestamp cannot prove it is alive, so it counts as
+ orphaned too. Terminal and unknown statuses never are.
+ """
+ if status not in ("queued", "running"):
+ return False
+ if isinstance(updated_at, bool) or not isinstance(updated_at, (int, float)):
+ return True
+ return now - updated_at > orphan_after
diff --git a/workers/modly/postprocess.py b/workers/modly/postprocess.py
new file mode 100644
index 000000000..ea5aad73e
--- /dev/null
+++ b/workers/modly/postprocess.py
@@ -0,0 +1,387 @@
+"""Local mesh post-process for the Modly worker: UV unwrap, texture bake, packing.
+
+Modly's own repair, decimate and smooth operations run inside Modly (see
+main.py). The two steps here are deliberately NOT Modly's:
+
+ * Modly's `api/uv_unwrapper` and `api/texture_baker` are vendored from
+ Stability AI's stable-fast-3d, which ships under the Stability AI Community
+ License rather than MIT. Shipping them in a commercial worker would take on
+ those terms, so this module re-implements both on MIT/BSD code: xatlas
+ (MIT) for the atlas, numpy and scipy (BSD) for the bake.
+ * Both run on the CPU in the front's own process, so they need no GPU and are
+ exercised by the build-time unit tests.
+
+The bake transfers colour from a SOURCE mesh (the mesh as it was before
+repair/decimate/smooth, which drop materials) onto the TARGET mesh's new atlas:
+each texel's 3D position is found by rasterizing the target in UV space, and its
+colour is the source surface colour nearest to that position. Sources with no
+colour (vertex, face or texture) are reported, never baked as a flat grey.
+"""
+
+from __future__ import annotations
+
+import io
+import logging
+import os
+import subprocess
+import tempfile
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Optional
+
+import numpy as np
+import trimesh
+from PIL import Image
+from scipy.spatial import cKDTree
+
+log = logging.getLogger("modly.postprocess")
+
+GLTFPACK_BIN = os.environ.get("GLTFPACK_BIN", "gltfpack")
+GLTFPACK_TIMEOUT_S = int(os.environ.get("GLTFPACK_TIMEOUT_S", "120"))
+# Texels rasterized per chunk: bounds peak memory on large atlases.
+_RASTER_CHUNK_TEXELS = 4_000_000
+# Seam dilation: texels grown outward from every chart so bilinear filtering
+# and mip levels never sample the empty gutter.
+DILATE_PASSES = 8
+# Source surface samples for the nearest-colour lookup.
+MIN_SOURCE_SAMPLES = 200_000
+MAX_SOURCE_SAMPLES = 2_000_000
+
+
+class MeshError(ValueError):
+ """The mesh itself cannot be processed. Safe to report to the caller."""
+
+
+@dataclass
+class BakeOutcome:
+ mesh: trimesh.Trimesh
+ baked: bool
+ reason: Optional[str] = None
+ coverage: float = 0.0
+
+
+# ── Load / export ─────────────────────────────────────────────────────────────
+
+def load_mesh(data: bytes, suffix: str = ".glb") -> trimesh.Trimesh:
+ """Load a GLB/glTF/OBJ/PLY into one Trimesh with scene transforms applied.
+
+ Visuals survive when the scene holds a single geometry. A multi-geometry
+ scene is concatenated, which keeps per-geometry vertex colours and textures
+ only when trimesh can merge them; geometry is never lost either way.
+ """
+ file_type = suffix.lstrip(".").lower() or "glb"
+ try:
+ loaded = trimesh.load(io.BytesIO(data), file_type=file_type, process=False)
+ except Exception as exc: # noqa: BLE001 - undecodable caller/model output
+ raise MeshError(f"mesh is not a readable {file_type} file ({type(exc).__name__})") from exc
+ if isinstance(loaded, trimesh.Scene):
+ meshes = [g for g in loaded.dump() if isinstance(g, trimesh.Trimesh)]
+ if not meshes:
+ raise MeshError("mesh file contains no triangle geometry")
+ mesh = meshes[0] if len(meshes) == 1 else trimesh.util.concatenate(meshes)
+ elif isinstance(loaded, trimesh.Trimesh):
+ mesh = loaded
+ else:
+ raise MeshError("mesh file contains no triangle geometry")
+ if len(mesh.faces) == 0:
+ raise MeshError("mesh has no faces")
+ return mesh
+
+
+def export_glb(mesh: trimesh.Trimesh) -> bytes:
+ return mesh.export(file_type="glb")
+
+
+def pack_glb(glb: bytes, gltfpack_bin: Optional[str] = None) -> tuple[bytes, bool]:
+ """Meshopt-compress a GLB with gltfpack. Returns (bytes, packed).
+
+ A missing or failing gltfpack serves the uncompressed GLB rather than
+ failing a finished job: the platform viewers read both.
+ """
+ binary = gltfpack_bin or GLTFPACK_BIN
+ with tempfile.TemporaryDirectory() as tmp:
+ src = Path(tmp) / "in.glb"
+ dst = Path(tmp) / "out.glb"
+ src.write_bytes(glb)
+ try:
+ subprocess.run(
+ [binary, "-i", str(src), "-o", str(dst), "-cc"],
+ check=True,
+ capture_output=True,
+ timeout=GLTFPACK_TIMEOUT_S,
+ )
+ packed = dst.read_bytes()
+ except FileNotFoundError:
+ log.warning("gltfpack not found at %s; serving the uncompressed GLB", binary)
+ return glb, False
+ except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
+ detail = getattr(exc, "stderr", b"") or b""
+ log.warning("gltfpack failed (%s %s); serving the uncompressed GLB", type(exc).__name__, detail[-300:])
+ return glb, False
+ if packed[:4] != b"glTF":
+ log.warning("gltfpack produced a non-GLB output; serving the uncompressed GLB")
+ return glb, False
+ return packed, True
+
+
+# ── UV unwrap ─────────────────────────────────────────────────────────────────
+
+def uv_unwrap(mesh: trimesh.Trimesh, texture_size: int = 1024) -> tuple[trimesh.Trimesh, dict]:
+ """Return a copy of `mesh` re-parameterized onto a fresh xatlas atlas.
+
+ Vertices along chart seams are split (xatlas's vmapping), so the vertex count
+ grows while the surface is unchanged. The result carries the new UVs and an
+ untextured PBR material; `bake` fills the texture.
+ """
+ import xatlas
+
+ vertices = np.asarray(mesh.vertices, dtype=np.float32)
+ faces = np.asarray(mesh.faces, dtype=np.uint32)
+ atlas = xatlas.Atlas()
+ atlas.add_mesh(vertices, faces)
+ pack = xatlas.PackOptions()
+ pack.resolution = int(texture_size)
+ pack.padding = 2
+ pack.bilinear = True
+ atlas.generate(pack_options=pack)
+ vmapping, indices, uvs = atlas[0]
+ material = trimesh.visual.material.PBRMaterial(
+ baseColorFactor=[255, 255, 255, 255], metallicFactor=0.0, roughnessFactor=0.9
+ )
+ unwrapped = trimesh.Trimesh(
+ vertices=np.asarray(mesh.vertices)[vmapping],
+ faces=np.asarray(indices, dtype=np.int64),
+ visual=trimesh.visual.TextureVisuals(uv=np.asarray(uvs, dtype=np.float64), material=material),
+ process=False,
+ )
+ info = {
+ "charts": int(atlas.chart_count),
+ "utilization": round(float(atlas.utilization), 4),
+ "vertices": int(len(unwrapped.vertices)),
+ }
+ return unwrapped, info
+
+
+# ── Colour sources ────────────────────────────────────────────────────────────
+
+def _rgba_float(colors: np.ndarray) -> np.ndarray:
+ arr = np.asarray(colors, dtype=np.float64)
+ if arr.shape[-1] == 3:
+ arr = np.concatenate([arr, np.full(arr.shape[:-1] + (1,), 255.0)], axis=-1)
+ return arr[..., :4]
+
+
+def _material_image_and_factor(material) -> tuple[Optional[Image.Image], np.ndarray]:
+ factor = np.array([255.0, 255.0, 255.0, 255.0])
+ image = None
+ base_factor = getattr(material, "baseColorFactor", None)
+ if base_factor is not None:
+ factor = _rgba_float(np.asarray(base_factor, dtype=np.float64).reshape(-1)[:4])
+ if factor.max() <= 1.0:
+ factor = factor * 255.0
+ image = getattr(material, "baseColorTexture", None)
+ if image is None:
+ image = getattr(material, "image", None)
+ return image, factor
+
+
+def has_colour(mesh: trimesh.Trimesh) -> Optional[str]:
+ """Which colour source `mesh` carries: "texture", "vertex", "face", "material" or None."""
+ visual = mesh.visual
+ kind = getattr(visual, "kind", None)
+ if kind == "texture":
+ image, factor = _material_image_and_factor(visual.material)
+ if image is not None and getattr(visual, "uv", None) is not None and len(visual.uv) == len(mesh.vertices):
+ return "texture"
+ if not np.allclose(factor[:3], 255.0):
+ return "material"
+ return None
+ if kind == "vertex":
+ return "vertex"
+ if kind == "face":
+ return "face"
+ return None
+
+
+def _sample_colours(mesh: trimesh.Trimesh, points: np.ndarray, face_index: np.ndarray, source: str) -> np.ndarray:
+ """RGBA (0..255 float) of `mesh` at surface `points` lying on `face_index`."""
+ faces = np.asarray(mesh.faces)[face_index]
+ if source == "face":
+ return _rgba_float(np.asarray(mesh.visual.face_colors)[face_index])
+ if source == "material":
+ _, factor = _material_image_and_factor(mesh.visual.material)
+ return np.tile(factor, (len(points), 1))
+ triangles = np.asarray(mesh.vertices)[faces]
+ bary = trimesh.triangles.points_to_barycentric(triangles, points)
+ bary = np.clip(np.nan_to_num(bary, nan=1.0 / 3.0), 0.0, 1.0)
+ bary = bary / np.maximum(bary.sum(axis=1, keepdims=True), 1e-12)
+ if source == "vertex":
+ colors = _rgba_float(np.asarray(mesh.visual.vertex_colors))
+ return np.einsum("ij,ijk->ik", bary, colors[faces])
+ image, factor = _material_image_and_factor(mesh.visual.material)
+ uv = np.einsum("ij,ijk->ik", bary, np.asarray(mesh.visual.uv, dtype=np.float64)[faces])
+ texel = _rgba_float(trimesh.visual.color.uv_to_color(uv % 1.0, image.convert("RGBA")))
+ return texel * (factor / 255.0)
+
+
+# ── Rasterization in UV space ─────────────────────────────────────────────────
+
+def rasterize_uv(uv: np.ndarray, faces: np.ndarray, size: int):
+ """Every texel centre covered by a face of the UV layout.
+
+ `uv` follows trimesh's convention (origin bottom-left), so image row is
+ (1 - v) * size. Returns (rows, cols, face_ids, barycentrics). A texel on a
+ shared edge belongs to whichever face is rasterized last, which is harmless:
+ both faces map it to the same surface point.
+ """
+ px = np.empty((len(faces), 3, 2), dtype=np.float64)
+ corners = np.asarray(uv, dtype=np.float64)[faces]
+ px[..., 0] = corners[..., 0] * size
+ px[..., 1] = (1.0 - corners[..., 1]) * size
+
+ a, b, c = px[:, 0], px[:, 1], px[:, 2]
+ area = (b[:, 0] - a[:, 0]) * (c[:, 1] - a[:, 1]) - (b[:, 1] - a[:, 1]) * (c[:, 0] - a[:, 0])
+ usable = np.abs(area) > 1e-12
+
+ lo = np.floor(px.min(axis=1) - 0.5).astype(np.int64)
+ hi = np.ceil(px.max(axis=1) - 0.5).astype(np.int64)
+ lo = np.clip(lo, 0, size - 1)
+ hi = np.clip(hi, 0, size - 1)
+ widths = hi[:, 0] - lo[:, 0] + 1
+ heights = hi[:, 1] - lo[:, 1] + 1
+ counts = np.where(usable, widths * heights, 0)
+
+ rows_out, cols_out, faces_out, bary_out = [], [], [], []
+ order = np.flatnonzero(counts)
+ start = 0
+ cumulative = np.cumsum(counts[order])
+ while start < len(order):
+ base = cumulative[start - 1] if start else 0
+ end = int(np.searchsorted(cumulative, base + _RASTER_CHUNK_TEXELS, side="right"))
+ end = max(end, start + 1)
+ chunk = order[start:end]
+ start = end
+
+ n = counts[chunk]
+ face_rep = np.repeat(chunk, n)
+ offsets = np.repeat(np.cumsum(n) - n, n)
+ local = np.arange(int(n.sum())) - offsets
+ w = widths[face_rep]
+ col = lo[face_rep, 0] + local % w
+ row = lo[face_rep, 1] + local // w
+ cx = col + 0.5
+ cy = row + 0.5
+
+ fa, fb, fc = a[face_rep], b[face_rep], c[face_rep]
+ ar = area[face_rep]
+ w0 = ((fb[:, 0] - cx) * (fc[:, 1] - cy) - (fb[:, 1] - cy) * (fc[:, 0] - cx)) / ar
+ w1 = ((fc[:, 0] - cx) * (fa[:, 1] - cy) - (fc[:, 1] - cy) * (fa[:, 0] - cx)) / ar
+ w2 = 1.0 - w0 - w1
+ inside = (w0 >= -1e-6) & (w1 >= -1e-6) & (w2 >= -1e-6)
+ rows_out.append(row[inside])
+ cols_out.append(col[inside])
+ faces_out.append(face_rep[inside])
+ bary_out.append(np.stack([w0[inside], w1[inside], w2[inside]], axis=1))
+
+ if not rows_out:
+ empty = np.empty(0, dtype=np.int64)
+ return empty, empty, empty, np.empty((0, 3))
+ return (
+ np.concatenate(rows_out),
+ np.concatenate(cols_out),
+ np.concatenate(faces_out),
+ np.concatenate(bary_out),
+ )
+
+
+def dilate(image: np.ndarray, mask: np.ndarray, passes: int = DILATE_PASSES) -> tuple[np.ndarray, np.ndarray]:
+ """Grow covered texels into the empty gutter by averaging covered neighbours.
+
+ Returns the grown image and the mask of texels that now hold a colour.
+ """
+ img = image.astype(np.float64).copy()
+ filled = mask.copy()
+ for _ in range(passes):
+ if filled.all():
+ break
+ padded = np.pad(img, ((1, 1), (1, 1), (0, 0)))
+ padded_mask = np.pad(filled, 1)
+ total = np.zeros_like(img)
+ weight = np.zeros(filled.shape, dtype=np.float64)
+ for dy in (-1, 0, 1):
+ for dx in (-1, 0, 1):
+ if dy == 0 and dx == 0:
+ continue
+ m = padded_mask[1 + dy : 1 + dy + filled.shape[0], 1 + dx : 1 + dx + filled.shape[1]]
+ total += padded[1 + dy : 1 + dy + img.shape[0], 1 + dx : 1 + dx + img.shape[1]] * m[..., None]
+ weight += m
+ grow = (~filled) & (weight > 0)
+ if not grow.any():
+ break
+ img[grow] = total[grow] / weight[grow][:, None]
+ filled = filled | grow
+ return img, filled
+
+
+# ── Bake ──────────────────────────────────────────────────────────────────────
+
+def bake(
+ source: trimesh.Trimesh,
+ target: trimesh.Trimesh,
+ texture_size: int = 1024,
+ rng_seed: int = 0,
+) -> BakeOutcome:
+ """Bake `source`'s surface colour into a baseColor texture on `target`'s UVs.
+
+ `target` must already carry UVs (run `uv_unwrap` first). Returns the target
+ with the baked texture attached, or the unchanged target with a reason when
+ the source has no colour to transfer.
+ """
+ source_kind = has_colour(source)
+ if source_kind is None:
+ return BakeOutcome(mesh=target, baked=False, reason="source mesh carries no colour to bake")
+ uv = getattr(target.visual, "uv", None)
+ if uv is None or len(uv) != len(target.vertices):
+ raise MeshError("bake needs a UV-unwrapped target mesh")
+
+ size = int(texture_size)
+ count = int(np.clip(size * size // 4, MIN_SOURCE_SAMPLES, MAX_SOURCE_SAMPLES))
+ points, face_index = trimesh.sample.sample_surface(source, count, seed=rng_seed)
+ colours = _sample_colours(source, points, face_index, source_kind)
+ tree = cKDTree(points)
+
+ rows, cols, face_ids, bary = rasterize_uv(np.asarray(uv), np.asarray(target.faces), size)
+ if len(rows) == 0:
+ return BakeOutcome(mesh=target, baked=False, reason="target UV layout covers no texels")
+ tri = np.asarray(target.vertices, dtype=np.float64)[np.asarray(target.faces)[face_ids]]
+ positions = np.einsum("ij,ijk->ik", bary, tri)
+ _, nearest = tree.query(positions, k=1, workers=-1)
+
+ image = np.zeros((size, size, 4), dtype=np.float64)
+ mask = np.zeros((size, size), dtype=bool)
+ image[rows, cols] = colours[nearest]
+ mask[rows, cols] = True
+ coverage = float(mask.mean())
+ image, filled = dilate(image, mask)
+ # Gutter texels beyond the dilation reach get the mean colour, so a mip level
+ # that averages across the gutter never pulls black into a chart edge.
+ if not filled.all():
+ image[~filled] = image[mask].mean(axis=0)
+ rgba = np.clip(np.rint(image), 0, 255).astype(np.uint8)
+ opaque = bool((rgba[..., 3][mask] >= 255).all())
+ texture = Image.fromarray(rgba if not opaque else rgba[..., :3], mode="RGBA" if not opaque else "RGB")
+
+ material = trimesh.visual.material.PBRMaterial(
+ baseColorTexture=texture,
+ baseColorFactor=[255, 255, 255, 255],
+ metallicFactor=0.0,
+ roughnessFactor=0.9,
+ alphaMode=None if opaque else "BLEND",
+ )
+ baked = trimesh.Trimesh(
+ vertices=np.asarray(target.vertices),
+ faces=np.asarray(target.faces),
+ visual=trimesh.visual.TextureVisuals(uv=np.asarray(uv), material=material),
+ process=False,
+ )
+ return BakeOutcome(mesh=baked, baked=True, coverage=round(coverage, 4))
diff --git a/workers/modly/request_policy.py b/workers/modly/request_policy.py
new file mode 100644
index 000000000..574f41196
--- /dev/null
+++ b/workers/modly/request_policy.py
@@ -0,0 +1,474 @@
+"""Pure request policy for the Modly worker: no GPU, no network, no Modly import.
+
+Everything the front decides about a request before it reaches Modly lives here,
+so the build-time gate can prove it without a GPU:
+
+ * which Modly model a request runs (`resolve_model`), from a short alias or a
+ full `<extension>/<node>` id, restricted to the models this deployment ships;
+ * the generation params Modly receives (`build_generation_params`): tier
+ presets, caller overrides clamped to each extension's own params_schema,
+ unknown keys dropped, and a concrete seed always chosen so the task record
+ can report the exact seed that produced the mesh;
+ * the post-process plan (`parse_postprocess`): repair, decimate, smooth, UV
+ unwrap and texture bake, validated and returned in the one order they run;
+ * how a Modly job status maps to a three.ws task status (`interpret_job`);
+ * where a Modly output path may point (`workspace_relative`);
+ * transient-fetch retry, shared verbatim with the other image-to-3D workers.
+"""
+
+from __future__ import annotations
+
+import math
+import random
+from typing import Any, Callable, Optional
+
+import httpx
+
+# ── Models ────────────────────────────────────────────────────────────────────
+# The extension manifests pinned in the Dockerfile define these params_schema
+# bounds; the copies below are what the front clamps to before Modly sees them.
+# A Modly id is `<extension id>/<node id>`.
+TRIPOSG = "triposg/generate"
+HUNYUAN_MINI_TURBO = "hunyuan3d-mini-turbo/generate"
+
+MODEL_ALIASES = {
+ "triposg": TRIPOSG,
+ "tripo": TRIPOSG,
+ "hunyuan3d-mini-turbo": HUNYUAN_MINI_TURBO,
+ "hunyuan-mini-turbo": HUNYUAN_MINI_TURBO,
+ "hunyuan": HUNYUAN_MINI_TURBO,
+}
+
+# Each entry: param id -> spec. `int`/`float` carry inclusive bounds, `choice`
+# carries the allowed values. `seed` is handled separately (always concrete).
+PARAM_SCHEMAS: dict[str, dict[str, dict[str, Any]]] = {
+ TRIPOSG: {
+ "num_inference_steps": {"type": "int", "min": 8, "max": 50, "default": 50},
+ "guidance_scale": {"type": "float", "min": 0.0, "max": 20.0, "default": 7.0},
+ "foreground_ratio": {"type": "float", "min": 0.5, "max": 1.0, "default": 0.85},
+ "faces": {"type": "int", "min": -1, "max": 500_000, "default": -1},
+ "use_flash_decoder": {
+ "type": "choice",
+ "options": ("DiffDMC", "Marching Cubes"),
+ "default": "DiffDMC",
+ },
+ },
+ HUNYUAN_MINI_TURBO: {
+ "num_inference_steps": {"type": "choice", "options": (5, 10, 20), "default": 10},
+ "octree_resolution": {"type": "choice", "options": (256, 380, 512), "default": 380},
+ "guidance_scale": {"type": "float", "min": 1.0, "max": 10.0, "default": 5.5},
+ },
+}
+
+# Tiers mirror the other image-to-3D lanes (draft | standard | high | max). Each
+# maps to the extension's own quality knobs; caller params still override.
+TIER_PRESETS: dict[str, dict[str, dict[str, Any]]] = {
+ TRIPOSG: {
+ "draft": {"num_inference_steps": 20},
+ "standard": {"num_inference_steps": 30},
+ "high": {"num_inference_steps": 50},
+ "max": {"num_inference_steps": 50},
+ },
+ HUNYUAN_MINI_TURBO: {
+ "draft": {"num_inference_steps": 5, "octree_resolution": 256},
+ "standard": {"num_inference_steps": 10, "octree_resolution": 380},
+ "high": {"num_inference_steps": 20, "octree_resolution": 512},
+ "max": {"num_inference_steps": 20, "octree_resolution": 512},
+ },
+}
+TIERS = ("draft", "standard", "high", "max")
+TIER_ALIASES = {"fast": "draft", "balanced": "standard", "quality": "high", "ultra": "max"}
+
+SEED_MAX = 2**32 - 1
+
+
+class PolicyError(ValueError):
+ """A request field is invalid. The message is safe to return to the caller."""
+
+
+def parse_model_list(raw: str) -> list[str]:
+ """MODLY_MODELS env value -> ordered, de-duplicated list of known model ids."""
+ out: list[str] = []
+ for part in (raw or "").split(","):
+ name = part.strip()
+ if not name:
+ continue
+ model = MODEL_ALIASES.get(name.lower(), name)
+ if model not in PARAM_SCHEMAS:
+ raise PolicyError(f"MODLY_MODELS names an unsupported model: {name}")
+ if model not in out:
+ out.append(model)
+ if not out:
+ raise PolicyError("MODLY_MODELS is empty")
+ return out
+
+
+def resolve_model(requested: Optional[str], enabled: list[str], default: str) -> str:
+ """Map a caller's `model` field to an enabled Modly model id."""
+ if requested is None or not str(requested).strip():
+ return default
+ name = str(requested).strip()
+ model = MODEL_ALIASES.get(name.lower(), name)
+ if model not in enabled:
+ allowed = ", ".join(sorted({a for a, m in MODEL_ALIASES.items() if m in enabled} | set(enabled)))
+ raise PolicyError(f"model '{name}' is not served by this worker (choose one of: {allowed})")
+ return model
+
+
+def normalize_tier(tier: Optional[str]) -> Optional[str]:
+ if tier is None:
+ return None
+ key = str(tier).strip().lower()
+ key = TIER_ALIASES.get(key, key)
+ return key if key in TIERS else None
+
+
+def _clamp_param(spec: dict[str, Any], value: Any, name: str) -> Any:
+ kind = spec["type"]
+ if kind == "choice":
+ options = spec["options"]
+ if value in options:
+ return value
+ # Numeric choices accept the nearest option (a caller asking for 12 steps
+ # on a 5/10/20 model gets 10, not an error).
+ if all(isinstance(o, (int, float)) for o in options):
+ try:
+ number = float(value)
+ except (TypeError, ValueError) as exc:
+ raise PolicyError(f"params.{name} must be one of {list(options)}") from exc
+ if not math.isfinite(number):
+ raise PolicyError(f"params.{name} must be one of {list(options)}")
+ return min(options, key=lambda o: (abs(o - number), o))
+ raise PolicyError(f"params.{name} must be one of {list(options)}")
+ try:
+ number = float(value)
+ except (TypeError, ValueError) as exc:
+ raise PolicyError(f"params.{name} must be a number") from exc
+ if not math.isfinite(number):
+ raise PolicyError(f"params.{name} must be a finite number")
+ number = max(spec["min"], min(spec["max"], number))
+ return int(round(number)) if kind == "int" else float(number)
+
+
+def resolve_seed(seed: Any, rng: Optional[random.Random] = None) -> int:
+ """A concrete seed in [0, 2^32-1]. None or -1 draws one, so it can be recorded."""
+ if seed is None:
+ return (rng or random).randint(0, SEED_MAX)
+ try:
+ value = int(seed)
+ except (TypeError, ValueError) as exc:
+ raise PolicyError("seed must be an integer") from exc
+ if value == -1:
+ return (rng or random).randint(0, SEED_MAX)
+ if value < 0 or value > SEED_MAX:
+ raise PolicyError(f"seed must be between 0 and {SEED_MAX}")
+ return value
+
+
+def build_generation_params(
+ model: str,
+ tier: Optional[str],
+ params: Optional[dict],
+ seed: Any,
+ rng: Optional[random.Random] = None,
+) -> tuple[dict, list[str]]:
+ """Params Modly receives for one job, plus the caller keys that were dropped.
+
+ Order: schema defaults, then the tier preset, then caller params (clamped).
+ Unknown keys are dropped rather than forwarded: an extension reads its own
+ params dict directly, so forwarding an unvalidated key is forwarding
+ unvalidated input into a GPU job.
+ """
+ schema = PARAM_SCHEMAS[model]
+ out = {name: spec["default"] for name, spec in schema.items()}
+ preset_tier = normalize_tier(tier)
+ if preset_tier:
+ out.update(TIER_PRESETS[model][preset_tier])
+ dropped: list[str] = []
+ for name, value in (params or {}).items():
+ if name == "seed":
+ if seed is None:
+ seed = value
+ continue
+ spec = schema.get(name)
+ if spec is None:
+ dropped.append(str(name))
+ continue
+ out[name] = _clamp_param(spec, value, name)
+ out["seed"] = resolve_seed(seed, rng)
+ return out, sorted(dropped)
+
+
+# ── Post-process plan ─────────────────────────────────────────────────────────
+POSTPROCESS_ORDER = ("repair", "decimate", "smooth", "uv_unwrap", "bake")
+REPAIR_FLAGS = ("remove_duplicates", "remove_degenerate", "fix_non_manifold", "fill_holes")
+MAX_HOLE_SIZE_MIN, MAX_HOLE_SIZE_MAX = 10, 10_000
+DECIMATE_MIN, DECIMATE_MAX = 100, 1_000_000
+SMOOTH_ITER_MIN, SMOOTH_ITER_MAX = 1, 50
+SMOOTH_LAMBDA_MIN, SMOOTH_LAMBDA_MAX = 0.1, 1.0
+SMOOTH_MODES = ("taubin", "laplacian")
+BAKE_SIZES = (256, 512, 1024, 2048, 4096)
+DEFAULT_BAKE_SIZE = 1024
+
+
+def _as_bool(value: Any, field: str) -> bool:
+ if isinstance(value, bool):
+ return value
+ raise PolicyError(f"{field} must be true or false")
+
+
+def _bounded_int(value: Any, field: str, low: int, high: int) -> int:
+ if isinstance(value, bool):
+ raise PolicyError(f"{field} must be an integer")
+ try:
+ number = int(value)
+ except (TypeError, ValueError) as exc:
+ raise PolicyError(f"{field} must be an integer") from exc
+ if number != value and not (isinstance(value, float) and value.is_integer()):
+ raise PolicyError(f"{field} must be an integer")
+ if number < low or number > high:
+ raise PolicyError(f"{field} must be between {low} and {high}")
+ return number
+
+
+def _parse_repair(value: Any) -> Optional[dict]:
+ if value is None or value is False:
+ return None
+ if value is True:
+ return {}
+ if not isinstance(value, dict):
+ raise PolicyError("postprocess.repair must be true, false or an object")
+ out: dict[str, Any] = {}
+ for key, raw in value.items():
+ if key in REPAIR_FLAGS:
+ out[key] = _as_bool(raw, f"postprocess.repair.{key}")
+ elif key == "max_hole_size":
+ out[key] = _bounded_int(raw, "postprocess.repair.max_hole_size", MAX_HOLE_SIZE_MIN, MAX_HOLE_SIZE_MAX)
+ else:
+ raise PolicyError(f"postprocess.repair.{key} is not a repair option")
+ return out
+
+
+def _parse_decimate(value: Any) -> Optional[dict]:
+ if value is None or value is False:
+ return None
+ if isinstance(value, dict):
+ unknown = set(value) - {"target_faces"}
+ if unknown:
+ raise PolicyError(f"postprocess.decimate.{sorted(unknown)[0]} is not a decimate option")
+ target = value.get("target_faces")
+ else:
+ target = value
+ if target is None:
+ raise PolicyError("postprocess.decimate needs target_faces")
+ return {"target_faces": _bounded_int(target, "postprocess.decimate.target_faces", DECIMATE_MIN, DECIMATE_MAX)}
+
+
+def _parse_smooth(value: Any) -> Optional[dict]:
+ if value is None or value is False:
+ return None
+ if value is True:
+ return {}
+ if not isinstance(value, dict):
+ raise PolicyError("postprocess.smooth must be true, false or an object")
+ out: dict[str, Any] = {}
+ for key, raw in value.items():
+ if key == "iterations":
+ out[key] = _bounded_int(raw, "postprocess.smooth.iterations", SMOOTH_ITER_MIN, SMOOTH_ITER_MAX)
+ elif key in ("lambda_", "lambda", "strength"):
+ try:
+ number = float(raw)
+ except (TypeError, ValueError) as exc:
+ raise PolicyError("postprocess.smooth.lambda_ must be a number") from exc
+ if not math.isfinite(number) or number < SMOOTH_LAMBDA_MIN or number > SMOOTH_LAMBDA_MAX:
+ raise PolicyError(
+ f"postprocess.smooth.lambda_ must be between {SMOOTH_LAMBDA_MIN} and {SMOOTH_LAMBDA_MAX}"
+ )
+ out["lambda_"] = number
+ elif key == "mode":
+ if raw not in SMOOTH_MODES:
+ raise PolicyError(f"postprocess.smooth.mode must be one of {list(SMOOTH_MODES)}")
+ out[key] = raw
+ else:
+ raise PolicyError(f"postprocess.smooth.{key} is not a smooth option")
+ return out
+
+
+def _parse_bake(value: Any) -> Optional[dict]:
+ if value is None or value is False:
+ return None
+ if value is True:
+ return {"texture_size": DEFAULT_BAKE_SIZE}
+ if not isinstance(value, dict):
+ raise PolicyError("postprocess.bake must be true, false or an object")
+ unknown = set(value) - {"texture_size"}
+ if unknown:
+ raise PolicyError(f"postprocess.bake.{sorted(unknown)[0]} is not a bake option")
+ size = value.get("texture_size", DEFAULT_BAKE_SIZE)
+ size = _bounded_int(size, "postprocess.bake.texture_size", BAKE_SIZES[0], BAKE_SIZES[-1])
+ if size not in BAKE_SIZES:
+ raise PolicyError(f"postprocess.bake.texture_size must be one of {list(BAKE_SIZES)}")
+ return {"texture_size": size}
+
+
+def parse_postprocess(raw: Optional[dict]) -> list[tuple[str, dict]]:
+ """Validate the `postprocess` object into an ordered plan of (step, params).
+
+ The order is fixed (repair, decimate, smooth, uv_unwrap, bake) whatever the
+ caller's key order: each step assumes the one before it ran. A bake needs UVs,
+ so asking for a bake schedules the unwrap too.
+ """
+ if raw is None:
+ return []
+ if not isinstance(raw, dict):
+ raise PolicyError("postprocess must be an object")
+ unknown = set(raw) - set(POSTPROCESS_ORDER)
+ if unknown:
+ raise PolicyError(f"postprocess.{sorted(unknown)[0]} is not a post-process step")
+ steps: dict[str, dict] = {}
+ repair = _parse_repair(raw.get("repair"))
+ if repair is not None:
+ steps["repair"] = repair
+ decimate = _parse_decimate(raw.get("decimate"))
+ if decimate is not None:
+ steps["decimate"] = decimate
+ smooth = _parse_smooth(raw.get("smooth"))
+ if smooth is not None:
+ steps["smooth"] = smooth
+ unwrap = raw.get("uv_unwrap")
+ if unwrap is not None and _as_bool(unwrap, "postprocess.uv_unwrap"):
+ steps["uv_unwrap"] = {}
+ bake = _parse_bake(raw.get("bake"))
+ if bake is not None:
+ steps["uv_unwrap"] = {}
+ steps["bake"] = bake
+ return [(name, steps[name]) for name in POSTPROCESS_ORDER if name in steps]
+
+
+# ── Modly job status ──────────────────────────────────────────────────────────
+MODLY_ACTIVE = frozenset({"pending", "running"})
+
+
+def interpret_job(job: dict) -> tuple[str, Optional[str]]:
+ """Map a Modly JobStatus to ("running" | "done" | "failed", detail).
+
+ For done, detail is the output_url. For failed, detail is a short reason:
+ Modly reports a full traceback, which is an internal artefact, so only its
+ final line (the exception itself) is kept, bounded in length.
+ """
+ status = job.get("status")
+ if status in MODLY_ACTIVE:
+ return "running", job.get("step")
+ if status == "done":
+ url = job.get("output_url")
+ if not url:
+ return "failed", "Modly reported success without an output file"
+ return "done", url
+ if status == "cancelled":
+ return "failed", "generation was cancelled"
+ if status == "error":
+ return "failed", summarize_traceback(job.get("error"))
+ return "failed", f"Modly returned an unknown job status: {status!r}"
+
+
+def summarize_traceback(text: Optional[str], limit: int = 300) -> str:
+ lines = [ln.strip() for ln in (text or "").strip().splitlines() if ln.strip()]
+ if not lines:
+ return "generation failed without an error message"
+ last = lines[-1]
+ return last if len(last) <= limit else last[: limit - 3] + "..."
+
+
+def workspace_relative(output_url: str) -> str:
+ """`/workspace/<rel>` from Modly -> `<rel>`, refusing anything that escapes."""
+ prefix = "/workspace/"
+ if not isinstance(output_url, str) or not output_url.startswith(prefix):
+ raise PolicyError("Modly output is not a workspace path")
+ rel = output_url[len(prefix):]
+ parts = rel.split("/")
+ if not rel or any(p in ("", ".", "..") for p in parts) or "\\" in rel or "\x00" in rel:
+ raise PolicyError("Modly output path is not a plain workspace-relative path")
+ return rel
+
+
+def readiness_problems(models: list[str], all_status: list, errors: dict) -> list[str]:
+ """Why Modly cannot serve `models` yet, from /model/all and /extensions/errors.
+
+ Empty list means ready: every configured model is registered, its weights are
+ on disk, and its extension loaded without an error.
+ """
+ problems: list[str] = []
+ by_id = {entry.get("id"): entry for entry in all_status if isinstance(entry, dict)}
+ for model in models:
+ ext = model.split("/", 1)[0]
+ err = (errors or {}).get(model) or (errors or {}).get(ext)
+ if err:
+ problems.append(f"{model}: extension error: {summarize_traceback(str(err))}")
+ continue
+ entry = by_id.get(model)
+ if entry is None:
+ problems.append(f"{model}: not registered by Modly")
+ elif not entry.get("downloaded"):
+ problems.append(f"{model}: weights missing from MODELS_DIR")
+ return problems
+
+
+# ── Transient fetch retry (shared shape with workers/model-trellis2) ─────────
+FETCH_ATTEMPTS = 3
+FETCH_RETRY_BASE_SECONDS = 1.0
+
+# Upstream status codes worth a second try. Everything else (404, 403, 400) is a
+# statement about the URL itself and will fail identically on every attempt.
+_RETRYABLE_STATUS = frozenset({408, 425, 429, 500, 502, 503, 504})
+
+
+def retry_delays(
+ attempts: int = FETCH_ATTEMPTS, base: float = FETCH_RETRY_BASE_SECONDS
+) -> list[float]:
+ """Exponential backoff gaps between attempts (one fewer than `attempts`)."""
+ return [base * (2 ** i) for i in range(max(0, attempts - 1))]
+
+
+def is_transient_fetch_error(exc: BaseException) -> bool:
+ """True when re-fetching the same URL could plausibly succeed.
+
+ Timeouts and connection-level failures are the blips this exists for. An
+ HTTP error is transient only for the status codes above; a 404 is not going
+ to become a 200 on the next attempt.
+ """
+ if isinstance(exc, httpx.HTTPStatusError):
+ return exc.response.status_code in _RETRYABLE_STATUS
+ return isinstance(
+ exc, (httpx.TimeoutException, httpx.NetworkError, httpx.RemoteProtocolError)
+ )
+
+
+def call_with_retry(
+ fn: Callable[[], object],
+ *,
+ attempts: int = FETCH_ATTEMPTS,
+ should_retry: Callable[[BaseException], bool] = is_transient_fetch_error,
+ sleep: Callable[[float], None],
+ on_retry: Optional[Callable[[int, float, BaseException], None]] = None,
+):
+ """Call `fn`, retrying with exponential backoff while `should_retry` holds.
+
+ Re-raises the last exception once the attempts are spent or the error is not
+ retryable. `sleep` is injected so the policy stays testable without wall
+ clock time; `on_retry` receives (attempt_number, delay, exception) for
+ logging.
+ """
+ delays = retry_delays(attempts)
+ last: BaseException
+ for index in range(max(1, attempts)):
+ try:
+ return fn()
+ except BaseException as exc: # noqa: BLE001 - re-raised below after the budget
+ last = exc
+ if index >= len(delays) or not should_retry(exc):
+ raise
+ delay = delays[index]
+ if on_retry:
+ on_retry(index + 1, delay, exc)
+ sleep(delay)
+ raise last
diff --git a/workers/modly/requirements-host.txt b/workers/modly/requirements-host.txt
new file mode 100644
index 000000000..4d1b8a56b
--- /dev/null
+++ b/workers/modly/requirements-host.txt
@@ -0,0 +1,30 @@
+# Host environment: Modly's FastAPI backend AND the three.ws front share it
+# (system python3.10 in the image). Every line is pinned so a rebuild resolves
+# the same tree. Modly's own api/requirements.txt lists these packages with
+# lower bounds only; the versions below satisfy every bound it declares.
+
+# ── Modly backend (api/requirements.txt at the pinned Modly commit) ──────────
+fastapi==0.115.6
+uvicorn[standard]==0.34.0
+python-multipart==0.0.20
+httpx==0.28.1
+mcp==1.9.4
+trimesh==4.5.3
+pymeshlab==2023.12.post2
+huggingface_hub==0.36.2
+hf_xet==1.1.10
+cryptography==45.0.7
+certifi==2025.8.3
+
+# ── Shared numeric stack (pymeshlab 2023.12 needs numpy 1.x) ─────────────────
+numpy==1.26.4
+pydantic==2.11.7
+
+# ── three.ws front: UV unwrap + bake (postprocess.py), storage, tests ────────
+# xatlas is MIT and replaces Modly's stable-fast-3d derived unwrapper; scipy
+# (BSD) provides the KD-tree for the colour transfer.
+xatlas==0.0.11
+scipy==1.13.1
+Pillow==10.4.0
+google-cloud-storage==2.18.0
+pytest==8.3.5
diff --git a/workers/modly/requirements-hunyuan.txt b/workers/modly/requirements-hunyuan.txt
new file mode 100644
index 000000000..6e3aafd09
--- /dev/null
+++ b/workers/modly/requirements-hunyuan.txt
@@ -0,0 +1,27 @@
+# Hunyuan3D-2mini Turbo extension venv
+# (/opt/modly-extensions/hunyuan3d-mini-turbo/venv). Mirrors the package set of
+# modly-hunyuan3d-mini-turbo-extension's setup.py, pinned. torch 2.6.0 +
+# torchvision 0.21.0 (cu124) install first in the Dockerfile; hy3dgen installs
+# from a pinned Tencent/Hunyuan3D-2 commit with --no-deps (shape pipeline only:
+# the paint pipeline is never invoked, see README.md).
+diffusers==0.31.0
+transformers==4.57.6
+accelerate==1.15.0
+huggingface_hub==0.36.2
+safetensors==0.5.3
+einops==0.8.0
+omegaconf==2.3.0
+PyYAML==6.0.2
+numpy==1.26.4
+scipy==1.13.1
+Pillow==10.4.0
+trimesh==4.5.3
+pymeshlab==2023.12.post2
+scikit-image==0.24.0
+opencv-python-headless==4.10.0.84
+rembg==2.0.59
+onnxruntime-gpu==1.20.1
+pybind11==2.13.6
+ninja==1.11.1.1
+setuptools==75.8.0
+wheel==0.45.1
diff --git a/workers/modly/requirements-triposg.txt b/workers/modly/requirements-triposg.txt
new file mode 100644
index 000000000..d8d818e38
--- /dev/null
+++ b/workers/modly/requirements-triposg.txt
@@ -0,0 +1,32 @@
+# TripoSG extension venv (/opt/modly-extensions/triposg/venv). Mirrors the
+# package set of modly-triposg-extension's setup.py, pinned. torch 2.6.0 +
+# torchvision 0.21.0 (cu124) install first in the Dockerfile; diso compiles
+# from a pinned commit and the `triposg` source package is copied from a pinned
+# TripoSG commit, neither of which comes from this file.
+# diffusers/transformers/accelerate/peft/huggingface_hub are the versions proven
+# on workers/model-triposg and workers/model-hunyuan3d.
+diffusers==0.31.0
+transformers==4.57.6
+accelerate==1.15.0
+peft==0.19.1
+huggingface_hub==0.36.2
+safetensors==0.5.3
+einops==0.8.0
+omegaconf==2.3.0
+antlr4-python3-runtime==4.9.3
+PyYAML==6.0.2
+jaxtyping==0.2.36
+typeguard==4.4.2
+numpy==1.26.4
+Pillow==10.4.0
+trimesh==4.5.3
+pymeshlab==2023.12.post2
+scikit-image==0.24.0
+opencv-python-headless==4.10.0.84
+rembg==2.0.59
+onnxruntime-gpu==1.20.1
+# diso builds with --no-build-isolation, so its build-time imports live here.
+pybind11==2.13.6
+ninja==1.11.1.1
+setuptools==75.8.0
+wheel==0.45.1
diff --git a/workers/modly/storage_backend.py b/workers/modly/storage_backend.py
new file mode 100644
index 000000000..fcf7fc1a1
--- /dev/null
+++ b/workers/modly/storage_backend.py
@@ -0,0 +1,63 @@
+"""Storage primitives for the standalone TRELLIS container.
+
+Production persists tasks and results in GCS because requests can move between
+Cloud Run instances. An NGC user runs one container with a mounted output
+volume, so the same service needs a local backend with atomic writes and strict
+task-id validation.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import uuid
+from pathlib import Path
+
+
+def normalize_task_id(task_id: str) -> str:
+ """Return a canonical UUID or reject a value that could escape the volume."""
+ parsed = uuid.UUID(task_id)
+ canonical = str(parsed)
+ if task_id.lower() != canonical:
+ raise ValueError("task_id must be a canonical UUID")
+ return canonical
+
+
+class LocalStorage:
+ """Durable task metadata and GLB results on a mounted local volume."""
+
+ def __init__(self, output_dir: str | os.PathLike[str]):
+ self.output_dir = Path(output_dir).expanduser().resolve()
+ self.tasks_dir = self.output_dir / "tasks"
+ self.results_dir = self.output_dir / "results"
+ self.tasks_dir.mkdir(parents=True, exist_ok=True)
+ self.results_dir.mkdir(parents=True, exist_ok=True)
+
+ def task_path(self, task_id: str) -> Path:
+ return self.tasks_dir / f"{normalize_task_id(task_id)}.json"
+
+ def result_path(self, task_id: str) -> Path:
+ return self.results_dir / f"{normalize_task_id(task_id)}.glb"
+
+ @staticmethod
+ def _atomic_write(path: Path, data: bytes) -> None:
+ temporary = path.with_suffix(path.suffix + ".tmp")
+ with temporary.open("wb") as handle:
+ handle.write(data)
+ handle.flush()
+ os.fsync(handle.fileno())
+ temporary.replace(path)
+
+ def write_task(self, task: dict) -> Path:
+ path = self.task_path(str(task["task_id"]))
+ payload = json.dumps(task, separators=(",", ":"), sort_keys=True).encode("utf-8")
+ self._atomic_write(path, payload)
+ return path
+
+ def read_task(self, task_id: str) -> dict:
+ return json.loads(self.task_path(task_id).read_text(encoding="utf-8"))
+
+ def write_result(self, task_id: str, glb_bytes: bytes) -> Path:
+ path = self.result_path(task_id)
+ self._atomic_write(path, glb_bytes)
+ return path
diff --git a/workers/modly/test_gltf_meshopt.py b/workers/modly/test_gltf_meshopt.py
new file mode 100644
index 000000000..2d2e9d502
--- /dev/null
+++ b/workers/modly/test_gltf_meshopt.py
@@ -0,0 +1,141 @@
+"""Tests for gltf_meshopt.py, the shared EXT_meshopt_compression decoder.
+
+Vendored byte-identical into every worker that ships gltf_meshopt.py, exactly
+like the module itself, and run as a Docker build gate in each of them:
+
+ python3 test_gltf_meshopt.py
+
+The round-trip section needs the `gltfpack` binary (present in every worker
+image, pinned in the Dockerfile). Without it the suite still runs and pins the
+readable failure a caller gets instead, so a laptop run stays green.
+"""
+
+from __future__ import annotations
+
+import io
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+import trimesh # noqa: E402
+
+import gltf_meshopt # noqa: E402
+
+PASS = 0
+
+
+def check(name: str, condition: bool, detail: str = "") -> None:
+ global PASS
+ if not condition:
+ print(f"FAIL {name} {detail}")
+ sys.exit(1)
+ PASS += 1
+ print(f"ok {name}")
+
+
+plain_glb = trimesh.Scene({"a": trimesh.creation.icosphere(subdivisions=2)}).export(file_type="glb")
+
+# ── document parsing ────────────────────────────────────────────────────────────
+
+doc = gltf_meshopt.gltf_document(plain_glb, ".glb")
+check("a glb's json chunk parses", isinstance(doc, dict) and "asset" in doc, str(type(doc)))
+check(
+ "a gltf json payload parses",
+ isinstance(gltf_meshopt.gltf_document(b'{"asset":{"version":"2.0"}}', ".gltf"), dict),
+)
+for payload, suffix, label in (
+ (b"ply\nformat ascii 1.0\n", ".ply", "a ply"),
+ (b"not json at all", ".gltf", "malformed gltf json"),
+ (b"glTF" + b"\x00" * 4, ".glb", "a truncated glb"),
+ (b"solid mesh\n", ".stl", "an stl"),
+):
+ check(f"{label} yields no gltf document", gltf_meshopt.gltf_document(payload, suffix) is None)
+
+# ── extension detection ─────────────────────────────────────────────────────────
+
+check("a plain glb needs no decode", not gltf_meshopt.uses_meshopt(doc))
+check("an empty document needs no decode", not gltf_meshopt.uses_meshopt(None))
+for declared in ("extensionsRequired", "extensionsUsed"):
+ check(
+ f"{declared} announcing {gltf_meshopt.MESHOPT_EXTENSION} needs a decode",
+ gltf_meshopt.uses_meshopt({declared: [gltf_meshopt.MESHOPT_EXTENSION]}),
+ )
+check(
+ "an unrelated extension needs no decode",
+ not gltf_meshopt.uses_meshopt({"extensionsUsed": ["KHR_materials_unlit"]}),
+)
+check(
+ "an uncompressed payload passes through decode_if_meshopt untouched",
+ gltf_meshopt.decode_if_meshopt(plain_glb, ".glb") == (plain_glb, ".glb"),
+)
+
+# ── the real decode ─────────────────────────────────────────────────────────────
+
+if shutil.which(gltf_meshopt.GLTFPACK_BIN):
+ with tempfile.TemporaryDirectory() as packdir:
+ raw = Path(packdir) / "raw.glb"
+ packed = Path(packdir) / "packed.glb"
+ raw.write_bytes(plain_glb)
+ subprocess.run(
+ [gltf_meshopt.GLTFPACK_BIN, "-i", str(raw), "-o", str(packed), "-cc"],
+ capture_output=True,
+ check=True,
+ timeout=gltf_meshopt.GLTFPACK_TIMEOUT_S,
+ )
+ packed_bytes = packed.read_bytes()
+
+ check(
+ "a gltfpack-compressed glb is detected",
+ gltf_meshopt.uses_meshopt(gltf_meshopt.gltf_document(packed_bytes, ".glb")),
+ )
+
+ # The bug this module exists for: trimesh dies on the compressed asset's
+ # fallback buffer, which is why every worker loading one failed.
+ try:
+ trimesh.load(io.BytesIO(packed_bytes), file_type="glb", force="mesh", process=False)
+ raw_load_failed = False
+ except Exception: # noqa: BLE001: the exact trimesh error is not the contract
+ raw_load_failed = True
+ check("trimesh alone cannot read a meshopt glb", raw_load_failed)
+
+ decoded, suffix = gltf_meshopt.decode_if_meshopt(packed_bytes, ".glb")
+ check("the decode returns a glb", suffix == ".glb" and decoded[:4] == b"glTF", suffix)
+ check("the decode is not a passthrough", decoded != packed_bytes)
+ check(
+ "the decoded asset no longer declares the extension",
+ not gltf_meshopt.uses_meshopt(gltf_meshopt.gltf_document(decoded, ".glb")),
+ )
+
+ mesh = trimesh.load(io.BytesIO(decoded), file_type="glb", force="mesh", process=False)
+ check(
+ "the decoded asset loads as real geometry",
+ len(mesh.faces) > 0 and len(mesh.vertices) > 0,
+ f"faces={len(mesh.faces)}",
+ )
+ source = trimesh.load(io.BytesIO(plain_glb), file_type="glb", force="mesh", process=False)
+ check(
+ "the decoded geometry matches the source face count",
+ len(mesh.faces) == len(source.faces),
+ f"{len(mesh.faces)} vs {len(source.faces)}",
+ )
+else:
+ original_bin = gltf_meshopt.GLTFPACK_BIN
+ try:
+ gltf_meshopt.GLTFPACK_BIN = "gltfpack-not-installed"
+ gltf_meshopt.transcode_meshopt(plain_glb, ".glb")
+ check("a missing gltfpack is a readable error", False, "no ValueError raised")
+ except ValueError as exc:
+ check(
+ "a missing gltfpack is a readable error",
+ gltf_meshopt.MESHOPT_EXTENSION in str(exc),
+ str(exc),
+ )
+ finally:
+ gltf_meshopt.GLTFPACK_BIN = original_bin
+
+print(f"\n{PASS} checks passed")
diff --git a/workers/modly/test_instance_health.py b/workers/modly/test_instance_health.py
new file mode 100644
index 000000000..261a66c29
--- /dev/null
+++ b/workers/modly/test_instance_health.py
@@ -0,0 +1,142 @@
+"""Unit tests for instance self-care: memory reading, recycle, orphan expiry.
+
+Pure stdlib, no torch and no CUDA, so this runs anywhere:
+
+ cd workers/model-trellis2 && python3 -m pytest test_instance_health.py -q
+
+These decisions run after every generation on the production instance. A wrong
+memory reading either restarts a healthy instance after every job or never
+restarts a bloated one, and a wrong orphan rule either fails live jobs or leaves
+dead ones polling for half an hour, which is the outage this module fixed.
+"""
+
+from pathlib import Path
+
+from instance_health import (
+ HEARTBEAT_SECS,
+ ORPHAN_AFTER_SECS,
+ MemorySample,
+ read_memory,
+ should_recycle,
+ task_is_orphaned,
+ trim_heap,
+)
+
+GIB = 1024 ** 3
+
+
+def _write(path: Path, text: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="ascii")
+
+
+# ---------------------------------------------------------------- read_memory
+
+
+def test_cgroup_v2_counts_heap_and_tmpfs_but_not_page_cache(tmp_path):
+ v2 = tmp_path / "v2"
+ _write(v2 / "memory.stat", f"anon {20 * GIB}\nfile {9 * GIB}\nshmem {3 * GIB}\n")
+ _write(v2 / "memory.max", f"{32 * GIB}\n")
+ sample = read_memory(str(v2), str(tmp_path / "none"), str(tmp_path / "none"))
+ assert sample == MemorySample(23 * GIB, 32 * GIB, "cgroup2")
+ assert abs(sample.fraction - 23 / 32) < 1e-9
+
+
+def test_cgroup_v2_without_a_limit_falls_through_to_meminfo(tmp_path):
+ v2 = tmp_path / "v2"
+ _write(v2 / "memory.stat", f"anon {GIB}\n")
+ _write(v2 / "memory.max", "max\n")
+ meminfo = tmp_path / "meminfo"
+ _write(meminfo, "MemTotal: 33554432 kB\nMemAvailable: 8388608 kB\n")
+ sample = read_memory(str(v2), str(tmp_path / "none"), str(meminfo))
+ assert sample.source == "meminfo"
+ assert sample.used_bytes == 24 * GIB
+ assert sample.limit_bytes == 32 * GIB
+
+
+def test_cgroup_v1_reads_rss_plus_shmem(tmp_path):
+ v1 = tmp_path / "v1"
+ _write(v1 / "memory.stat", f"total_rss {10 * GIB}\ntotal_cache {5 * GIB}\ntotal_shmem {2 * GIB}\n")
+ _write(v1 / "memory.limit_in_bytes", f"{16 * GIB}\n")
+ sample = read_memory(str(tmp_path / "none"), str(v1), str(tmp_path / "none"))
+ assert sample == MemorySample(12 * GIB, 16 * GIB, "cgroup1")
+
+
+def test_unlimited_cgroup_v1_is_not_a_ceiling(tmp_path):
+ v1 = tmp_path / "v1"
+ _write(v1 / "memory.stat", f"total_rss {GIB}\n")
+ _write(v1 / "memory.limit_in_bytes", "9223372036854771712\n")
+ assert read_memory(str(tmp_path / "none"), str(v1), str(tmp_path / "none")) is None
+
+
+def test_nothing_readable_is_unknown_not_an_error(tmp_path):
+ missing = str(tmp_path / "missing")
+ assert read_memory(missing, missing, missing) is None
+
+
+def test_describe_is_human_readable():
+ text = MemorySample(24 * GIB, 32 * GIB, "cgroup2").describe()
+ assert text == "24.0/32.0 GiB (75%, cgroup2)"
+
+
+# ---------------------------------------------------------------- should_recycle
+
+
+def _at(fraction: float) -> MemorySample:
+ return MemorySample(int(fraction * 32 * GIB), 32 * GIB, "cgroup2")
+
+
+def test_recycles_a_ratcheted_instance():
+ assert should_recycle(_at(0.88), _at(0.46))
+
+
+def test_leaves_a_healthy_instance_alone():
+ assert not should_recycle(_at(0.60), _at(0.46))
+
+
+def test_high_baseline_alone_never_recycles():
+ # A baseline that already reads high (a big model, or a reading that counts
+ # more than it should) must not restart the instance after every job.
+ assert not should_recycle(_at(0.84), _at(0.80))
+
+
+def test_unknown_memory_never_recycles():
+ assert not should_recycle(None, _at(0.40))
+ assert not should_recycle(_at(0.95), None)
+
+
+# ---------------------------------------------------------------- task_is_orphaned
+
+
+NOW = 1_800_000_000.0
+
+
+def test_a_beating_task_is_alive():
+ assert not task_is_orphaned("running", NOW - HEARTBEAT_SECS, NOW)
+ assert not task_is_orphaned("queued", NOW - ORPHAN_AFTER_SECS + 1, NOW)
+
+
+def test_a_silent_task_is_orphaned_within_minutes():
+ assert task_is_orphaned("running", NOW - ORPHAN_AFTER_SECS - 1, NOW)
+ # The old rule waited 1800 s; the whole point is that a client still polls.
+ assert ORPHAN_AFTER_SECS <= 300
+ # Several missed beats, never one, decide it.
+ assert ORPHAN_AFTER_SECS >= 4 * HEARTBEAT_SECS
+
+
+def test_a_record_without_a_timestamp_cannot_prove_it_is_alive():
+ assert task_is_orphaned("queued", None, NOW)
+ assert task_is_orphaned("running", "yesterday", NOW)
+ assert task_is_orphaned("running", True, NOW)
+
+
+def test_terminal_and_unknown_records_are_never_orphaned():
+ for status in ("done", "failed", None, "weird"):
+ assert not task_is_orphaned(status, NOW - 10 * ORPHAN_AFTER_SECS, NOW)
+
+
+# ---------------------------------------------------------------- trim_heap
+
+
+def test_trim_heap_never_raises():
+ assert trim_heap() in (True, False)
diff --git a/workers/modly/test_postprocess.py b/workers/modly/test_postprocess.py
new file mode 100644
index 000000000..63844fad3
--- /dev/null
+++ b/workers/modly/test_postprocess.py
@@ -0,0 +1,150 @@
+"""Unit tests for postprocess.py (CPU only: xatlas, numpy, scipy, trimesh)."""
+
+import numpy as np
+import pytest
+import trimesh
+from PIL import Image
+
+import postprocess
+from postprocess import MeshError, bake, dilate, has_colour, load_mesh, pack_glb, rasterize_uv, uv_unwrap
+
+
+def _sphere(subdivisions: int = 3) -> trimesh.Trimesh:
+ return trimesh.creation.icosphere(subdivisions=subdivisions)
+
+
+def _two_tone_sphere() -> trimesh.Trimesh:
+ mesh = _sphere()
+ colours = np.where(
+ (mesh.vertices[:, 2] > 0)[:, None],
+ np.array([255, 0, 0, 255]),
+ np.array([0, 0, 255, 255]),
+ ).astype(np.uint8)
+ mesh.visual = trimesh.visual.ColorVisuals(mesh=mesh, vertex_colors=colours)
+ return mesh
+
+
+def _texel_at(mesh: trimesh.Trimesh, vertex: int) -> np.ndarray:
+ image = np.asarray(mesh.visual.material.baseColorTexture.convert("RGBA"))
+ size = image.shape[0]
+ u, v = mesh.visual.uv[vertex]
+ col = min(size - 1, int(u * size))
+ row = min(size - 1, int((1.0 - v) * size))
+ return image[row, col]
+
+
+def test_load_mesh_round_trips_a_glb():
+ glb = _sphere().export(file_type="glb")
+ mesh = load_mesh(glb, ".glb")
+ assert len(mesh.faces) == len(_sphere().faces)
+
+
+def test_load_mesh_refuses_garbage():
+ with pytest.raises(MeshError):
+ load_mesh(b"not a mesh at all", ".glb")
+
+
+def test_load_mesh_concatenates_a_multi_geometry_scene():
+ scene = trimesh.Scene([trimesh.creation.box(), trimesh.creation.icosphere(subdivisions=1)])
+ mesh = load_mesh(scene.export(file_type="glb"), ".glb")
+ assert len(mesh.faces) == 12 + 80
+
+
+def test_uv_unwrap_keeps_the_surface_and_bounds_the_uvs():
+ source = _sphere()
+ unwrapped, info = uv_unwrap(source, 512)
+ assert len(unwrapped.faces) == len(source.faces)
+ assert len(unwrapped.vertices) >= len(source.vertices)
+ assert unwrapped.area == pytest.approx(source.area, rel=1e-5)
+ uv = unwrapped.visual.uv
+ assert uv.min() >= 0.0 and uv.max() <= 1.0
+ assert info["charts"] >= 1
+ assert info["vertices"] == len(unwrapped.vertices)
+
+
+def test_rasterize_uv_covers_half_the_square_for_one_diagonal_triangle():
+ uv = np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]])
+ faces = np.array([[0, 1, 2]])
+ rows, cols, face_ids, bary = rasterize_uv(uv, faces, 64)
+ assert abs(len(rows) - 64 * 64 / 2) <= 64
+ assert (face_ids == 0).all()
+ assert np.allclose(bary.sum(axis=1), 1.0)
+ assert (bary >= -1e-6).all()
+ # Bottom-left origin in UV means the covered half sits at the bottom rows.
+ assert rows.max() == 63 and rows.min() <= 1
+
+
+def test_rasterize_uv_skips_degenerate_faces():
+ uv = np.array([[0.1, 0.1], [0.1, 0.1], [0.1, 0.1]])
+ rows, *_ = rasterize_uv(uv, np.array([[0, 1, 2]]), 32)
+ assert len(rows) == 0
+
+
+def test_dilate_grows_into_empty_neighbours():
+ image = np.zeros((5, 5, 4))
+ mask = np.zeros((5, 5), dtype=bool)
+ image[2, 2] = [10, 20, 30, 255]
+ mask[2, 2] = True
+ grown, filled = dilate(image, mask, passes=1)
+ assert filled[1:4, 1:4].all()
+ assert not filled[0, 0]
+ assert np.allclose(grown[1, 1], [10, 20, 30, 255])
+
+
+def test_has_colour_detects_each_source():
+ assert has_colour(_sphere()) is None
+ assert has_colour(_two_tone_sphere()) == "vertex"
+ faces = _sphere()
+ faces.visual = trimesh.visual.ColorVisuals(mesh=faces, face_colors=[0, 255, 0, 255])
+ assert has_colour(faces) == "face"
+
+
+def test_bake_transfers_vertex_colour_onto_the_new_atlas():
+ source = _two_tone_sphere()
+ target, _ = uv_unwrap(source, 256)
+ outcome = bake(source, target, texture_size=256)
+ assert outcome.baked
+ assert outcome.coverage > 0.2
+ top = int(np.argmax(outcome.mesh.vertices[:, 2]))
+ bottom = int(np.argmin(outcome.mesh.vertices[:, 2]))
+ assert _texel_at(outcome.mesh, top)[:3].tolist() == [255, 0, 0]
+ assert _texel_at(outcome.mesh, bottom)[:3].tolist() == [0, 0, 255]
+
+
+def test_bake_transfers_a_texture_onto_a_decimated_target():
+ textured, _ = uv_unwrap(_sphere(4), 256)
+ green = Image.new("RGB", (64, 64), (0, 200, 0))
+ textured.visual.material = trimesh.visual.material.PBRMaterial(baseColorTexture=green)
+ assert has_colour(textured) == "texture"
+ target, _ = uv_unwrap(_sphere(2), 256)
+ outcome = bake(textured, target, texture_size=256)
+ assert outcome.baked
+ assert _texel_at(outcome.mesh, 0)[:3].tolist() == [0, 200, 0]
+
+
+def test_bake_reports_a_colourless_source_instead_of_baking_grey():
+ source = _sphere()
+ target, _ = uv_unwrap(source, 256)
+ outcome = bake(source, target, texture_size=256)
+ assert not outcome.baked
+ assert "no colour" in outcome.reason
+ assert outcome.mesh is target
+
+
+def test_bake_refuses_a_target_without_uvs():
+ with pytest.raises(MeshError):
+ bake(_two_tone_sphere(), _sphere(), texture_size=256)
+
+
+def test_baked_mesh_exports_a_textured_glb():
+ source = _two_tone_sphere()
+ target, _ = uv_unwrap(source, 256)
+ outcome = bake(source, target, texture_size=256)
+ reloaded = load_mesh(postprocess.export_glb(outcome.mesh), ".glb")
+ assert has_colour(reloaded) == "texture"
+
+
+def test_pack_glb_serves_the_original_when_gltfpack_is_missing():
+ glb = _sphere().export(file_type="glb")
+ packed, ok = pack_glb(glb, gltfpack_bin="/nonexistent/gltfpack")
+ assert packed == glb and ok is False
diff --git a/workers/modly/test_request_policy.py b/workers/modly/test_request_policy.py
new file mode 100644
index 000000000..e9d918a95
--- /dev/null
+++ b/workers/modly/test_request_policy.py
@@ -0,0 +1,258 @@
+"""Unit tests for request_policy.py (pure: no GPU, no network, no Modly)."""
+
+import random
+
+import httpx
+import pytest
+
+from request_policy import (
+ HUNYUAN_MINI_TURBO,
+ SEED_MAX,
+ TRIPOSG,
+ PolicyError,
+ build_generation_params,
+ call_with_retry,
+ interpret_job,
+ is_transient_fetch_error,
+ normalize_tier,
+ parse_model_list,
+ parse_postprocess,
+ readiness_problems,
+ resolve_model,
+ resolve_seed,
+ retry_delays,
+ summarize_traceback,
+ workspace_relative,
+)
+
+ENABLED = [TRIPOSG, HUNYUAN_MINI_TURBO]
+
+
+# ── Models ────────────────────────────────────────────────────────────────────
+
+def test_parse_model_list_accepts_aliases_and_dedupes():
+ assert parse_model_list("triposg, hunyuan3d-mini-turbo/generate,tripo") == ENABLED
+
+
[email protected]("raw", ["", " , ", "sf3d/generate"])
+def test_parse_model_list_refuses_empty_or_unknown(raw):
+ with pytest.raises(PolicyError):
+ parse_model_list(raw)
+
+
+def test_resolve_model_defaults_and_aliases():
+ assert resolve_model(None, ENABLED, TRIPOSG) == TRIPOSG
+ assert resolve_model(" ", ENABLED, TRIPOSG) == TRIPOSG
+ assert resolve_model("Hunyuan", ENABLED, TRIPOSG) == HUNYUAN_MINI_TURBO
+ assert resolve_model(TRIPOSG, ENABLED, TRIPOSG) == TRIPOSG
+
+
+def test_resolve_model_refuses_a_model_this_deployment_does_not_serve():
+ with pytest.raises(PolicyError, match="not served"):
+ resolve_model("hunyuan", [TRIPOSG], TRIPOSG)
+ with pytest.raises(PolicyError):
+ resolve_model("../../etc/passwd", ENABLED, TRIPOSG)
+
+
+def test_normalize_tier():
+ assert normalize_tier("HIGH") == "high"
+ assert normalize_tier("fast") == "draft"
+ assert normalize_tier("nonsense") is None
+ assert normalize_tier(None) is None
+
+
+# ── Generation params ─────────────────────────────────────────────────────────
+
+def test_defaults_match_the_extension_schema_and_seed_is_concrete():
+ params, dropped = build_generation_params(TRIPOSG, None, None, None, random.Random(1))
+ assert params["num_inference_steps"] == 50
+ assert params["guidance_scale"] == 7.0
+ assert params["use_flash_decoder"] == "DiffDMC"
+ assert 0 <= params["seed"] <= SEED_MAX
+ assert dropped == []
+
+
+def test_tier_preset_then_caller_override():
+ params, _ = build_generation_params(TRIPOSG, "draft", None, 7)
+ assert params["num_inference_steps"] == 20
+ params, _ = build_generation_params(TRIPOSG, "draft", {"num_inference_steps": 40}, 7)
+ assert params["num_inference_steps"] == 40
+ assert params["seed"] == 7
+
+
+def test_caller_values_are_clamped_and_unknown_keys_dropped():
+ params, dropped = build_generation_params(
+ TRIPOSG,
+ None,
+ {"num_inference_steps": 999, "guidance_scale": -4, "faces": 10_000_000, "enable_texture": True, "remesh": "quad"},
+ 1,
+ )
+ assert params["num_inference_steps"] == 50
+ assert params["guidance_scale"] == 0.0
+ assert params["faces"] == 500_000
+ assert "enable_texture" not in params and "remesh" not in params
+ assert dropped == ["enable_texture", "remesh"]
+
+
+def test_numeric_choice_snaps_to_the_nearest_option():
+ params, _ = build_generation_params(HUNYUAN_MINI_TURBO, None, {"num_inference_steps": 12, "octree_resolution": 500}, 3)
+ assert params["num_inference_steps"] == 10
+ assert params["octree_resolution"] == 512
+
+
+def test_hunyuan_tiers_map_steps_and_octree():
+ params, _ = build_generation_params(HUNYUAN_MINI_TURBO, "max", None, 3)
+ assert params["num_inference_steps"] == 20 and params["octree_resolution"] == 512
+
+
[email protected]("bad", [{"guidance_scale": "loud"}, {"guidance_scale": float("nan")}, {"use_flash_decoder": "Voxels"}])
+def test_invalid_param_values_are_policy_errors(bad):
+ with pytest.raises(PolicyError):
+ build_generation_params(TRIPOSG, None, bad, 1)
+
+
+def test_seed_in_params_is_honoured_when_no_top_level_seed():
+ params, dropped = build_generation_params(TRIPOSG, None, {"seed": 99}, None)
+ assert params["seed"] == 99 and dropped == []
+
+
+def test_resolve_seed_bounds():
+ assert resolve_seed(0) == 0
+ assert resolve_seed(SEED_MAX) == SEED_MAX
+ assert 0 <= resolve_seed(-1, random.Random(5)) <= SEED_MAX
+ for bad in (-2, SEED_MAX + 1, "x"):
+ with pytest.raises(PolicyError):
+ resolve_seed(bad)
+
+
+# ── Post-process plan ─────────────────────────────────────────────────────────
+
+def test_postprocess_empty_means_no_steps():
+ assert parse_postprocess(None) == []
+ assert parse_postprocess({}) == []
+ assert parse_postprocess({"repair": False, "smooth": None}) == []
+
+
+def test_postprocess_runs_in_fixed_order_whatever_the_key_order():
+ plan = parse_postprocess({"smooth": True, "bake": {"texture_size": 2048}, "decimate": 5000, "repair": True})
+ assert [name for name, _ in plan] == ["repair", "decimate", "smooth", "uv_unwrap", "bake"]
+ assert dict(plan)["decimate"] == {"target_faces": 5000}
+ assert dict(plan)["bake"] == {"texture_size": 2048}
+
+
+def test_bake_true_uses_the_default_size_and_implies_unwrap():
+ plan = dict(parse_postprocess({"bake": True}))
+ assert plan == {"uv_unwrap": {}, "bake": {"texture_size": 1024}}
+
+
+def test_repair_and_smooth_options_are_validated():
+ plan = dict(parse_postprocess({
+ "repair": {"fill_holes": False, "max_hole_size": 500},
+ "smooth": {"iterations": 10, "lambda": 0.3, "mode": "laplacian"},
+ }))
+ assert plan["repair"] == {"fill_holes": False, "max_hole_size": 500}
+ assert plan["smooth"] == {"iterations": 10, "lambda_": 0.3, "mode": "laplacian"}
+
+
+ "raw",
+ [
+ "repair",
+ {"explode": True},
+ {"repair": {"weld": True}},
+ {"repair": {"fill_holes": "yes"}},
+ {"decimate": 50},
+ {"decimate": 2_000_000},
+ {"decimate": {}},
+ {"decimate": 1000.5},
+ {"decimate": True},
+ {"smooth": {"iterations": 0}},
+ {"smooth": {"lambda_": 2.0}},
+ {"smooth": {"mode": "bilateral"}},
+ {"bake": {"texture_size": 1000}},
+ {"bake": {"texture_size": 8192}},
+ {"uv_unwrap": "please"},
+ ],
+)
+def test_postprocess_refuses_bad_input(raw):
+ with pytest.raises(PolicyError):
+ parse_postprocess(raw)
+
+
+# ── Modly job status ──────────────────────────────────────────────────────────
+
+def test_interpret_job_states():
+ assert interpret_job({"status": "pending"}) == ("running", None)
+ assert interpret_job({"status": "running", "step": "Loading"}) == ("running", "Loading")
+ assert interpret_job({"status": "done", "output_url": "/workspace/a/b.glb"}) == ("done", "/workspace/a/b.glb")
+ assert interpret_job({"status": "done"})[0] == "failed"
+ assert interpret_job({"status": "cancelled"}) == ("failed", "generation was cancelled")
+ assert interpret_job({"status": "weird"})[0] == "failed"
+
+
+def test_interpret_job_keeps_only_the_exception_line_of_a_traceback():
+ tb = 'Traceback (most recent call last):\n File "/opt/x.py", line 3, in f\nRuntimeError: CUDA out of memory'
+ assert interpret_job({"status": "error", "error": tb}) == ("failed", "RuntimeError: CUDA out of memory")
+ assert summarize_traceback("") == "generation failed without an error message"
+ assert len(summarize_traceback("E" * 1000)) == 300
+
+
[email protected]("url", ["/workspace/three-ws/x.glb", "/workspace/a.glb"])
+def test_workspace_relative_accepts_plain_paths(url):
+ assert workspace_relative(url) == url[len("/workspace/"):]
+
+
+ "url",
+ ["/workspace/", "/workspace/../etc/passwd", "/workspace/a//b.glb", "/workspace/a/./b", "/etc/passwd", "https://x/y", None, "/workspace/a\\b"],
+)
+def test_workspace_relative_refuses_escapes(url):
+ with pytest.raises(PolicyError):
+ workspace_relative(url)
+
+
+def test_readiness_problems():
+ status = [
+ {"id": TRIPOSG, "downloaded": True, "loaded": False},
+ {"id": HUNYUAN_MINI_TURBO, "downloaded": False, "loaded": False},
+ ]
+ assert readiness_problems([TRIPOSG], status, {}) == []
+ problems = readiness_problems(ENABLED, status, {})
+ assert problems == [f"{HUNYUAN_MINI_TURBO}: weights missing from MODELS_DIR"]
+ problems = readiness_problems([TRIPOSG], [], {"triposg": "Traceback\nImportError: no diso"})
+ assert problems == [f"{TRIPOSG}: extension error: ImportError: no diso"]
+ assert readiness_problems([TRIPOSG], [], {}) == [f"{TRIPOSG}: not registered by Modly"]
+
+
+# ── Retry ─────────────────────────────────────────────────────────────────────
+
+def _status_error(code: int) -> httpx.HTTPStatusError:
+ request = httpx.Request("GET", "https://example.com/a.png")
+ return httpx.HTTPStatusError("x", request=request, response=httpx.Response(code, request=request))
+
+
+def test_retry_delays_and_transience():
+ assert retry_delays(3, 1.0) == [1.0, 2.0]
+ assert is_transient_fetch_error(_status_error(503))
+ assert not is_transient_fetch_error(_status_error(404))
+ assert is_transient_fetch_error(httpx.ConnectTimeout("t"))
+ assert not is_transient_fetch_error(ValueError("x"))
+
+
+def test_call_with_retry_recovers_then_gives_up():
+ calls, sleeps = [], []
+
+ def flaky():
+ calls.append(1)
+ if len(calls) < 3:
+ raise httpx.ConnectError("blip")
+ return "ok"
+
+ assert call_with_retry(flaky, sleep=sleeps.append) == "ok"
+ assert sleeps == [1.0, 2.0]
+
+ def broken():
+ raise _status_error(404)
+
+ with pytest.raises(httpx.HTTPStatusError):
+ call_with_retry(broken, sleep=sleeps.append)
diff --git a/workers/modly/test_storage_backend.py b/workers/modly/test_storage_backend.py
new file mode 100644
index 000000000..fa6d14adb
--- /dev/null
+++ b/workers/modly/test_storage_backend.py
@@ -0,0 +1,54 @@
+from __future__ import annotations
+
+import json
+import uuid
+
+import pytest
+
+from storage_backend import LocalStorage, normalize_task_id
+
+
+def test_task_round_trip_survives_process_memory(tmp_path):
+ storage = LocalStorage(tmp_path)
+ task_id = str(uuid.uuid4())
+ task = {"task_id": task_id, "status": "done", "updated_at": 123.0}
+
+ path = storage.write_task(task)
+
+ assert path == tmp_path / "tasks" / f"{task_id}.json"
+ assert storage.read_task(task_id) == task
+ assert json.loads(path.read_text()) == task
+
+
+def test_result_is_written_to_the_mounted_volume(tmp_path):
+ storage = LocalStorage(tmp_path)
+ task_id = str(uuid.uuid4())
+ payload = b"glTF" + bytes(range(32))
+
+ path = storage.write_result(task_id, payload)
+
+ assert path == tmp_path / "results" / f"{task_id}.glb"
+ assert path.read_bytes() == payload
+
+
+ "task_id",
+ ["../escape", "not-a-uuid", "{00000000-0000-0000-0000-000000000000}", "00000000-0000-0000-0000-000000000000/mesh"],
+)
+def test_task_ids_cannot_escape_the_output_volume(task_id):
+ with pytest.raises(ValueError):
+ normalize_task_id(task_id)
+
+
+def test_atomic_writes_leave_no_temporary_files(tmp_path):
+ storage = LocalStorage(tmp_path)
+ task_id = str(uuid.uuid4())
+
+ storage.write_task({"task_id": task_id, "status": "queued"})
+ storage.write_task({"task_id": task_id, "status": "running"})
+ storage.write_result(task_id, b"first")
+ storage.write_result(task_id, b"second")
+
+ assert storage.read_task(task_id)["status"] == "running"
+ assert storage.result_path(task_id).read_bytes() == b"second"
+ assert list(tmp_path.rglob("*.tmp")) == []
diff --git a/workers/modly/worker_security.py b/workers/modly/worker_security.py
new file mode 100644
index 000000000..ed5a528c2
--- /dev/null
+++ b/workers/modly/worker_security.py
@@ -0,0 +1,305 @@
+"""
+Shared security helpers for the three.ws GPU/CPU workers.
+
+This module is intentionally dependency-light (stdlib only) so it can be
+COPYed verbatim into every worker's Docker build context. The same canonical
+file lives in each worker directory; keep them byte-identical when editing.
+
+It provides three primitives that every worker needs:
+
+ 1. ``require_api_key`` - constant-time bearer-token check (timing-safe).
+ 2. ``fetch_remote_bytes`` - SSRF-hardened HTTP(S) fetch of caller-supplied
+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata
+ IP rejection, per-hop redirect re-validation, and a bounded response size.
+ 3. ``safe_error`` - turns an exception into an opaque, correlation-id-tagged
+ message safe to persist/return to callers, after logging the full
+ traceback server-side only.
+"""
+
+from __future__ import annotations
+
+import hmac
+import ipaddress
+import logging
+import asyncio
+import socket
+import time
+import uuid
+from typing import Iterable, Optional
+from urllib.parse import urlsplit
+
+import httpx
+
+log = logging.getLogger("worker_security")
+
+# ── auth ────────────────────────────────────────────────────────────────────────
+
+
+def require_api_key(authorization: Optional[str], api_key: str) -> None:
+ """Validate a ``Bearer <token>`` header in constant time.
+
+ Raises ``PermissionError`` on any failure so callers can translate it into
+ the framework's 401 (FastAPI workers map this to HTTPException(401)).
+ """
+ # Fail closed on an empty configured key: with api_key == "" a bare
+ # "Bearer " header would otherwise strip to "" and compare equal.
+ if not api_key:
+ raise PermissionError("worker api key not configured")
+ if not authorization or not authorization.startswith("Bearer "):
+ raise PermissionError("missing bearer token")
+ token = authorization[len("Bearer "):].strip()
+ if not token:
+ raise PermissionError("missing bearer token")
+ # Compare bytes: hmac.compare_digest is timing-safe, and on str operands it
+ # raises TypeError for non-ASCII input, which would surface as a 500.
+ if not hmac.compare_digest(token.encode("utf-8"), api_key.encode("utf-8")):
+ raise PermissionError("invalid api key")
+
+
+# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────
+
+# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes
+# are comfortably under this; anything larger is almost certainly abuse.
+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB
+_MAX_REDIRECTS = 4
+
+# Transient fetch failures are retried: a dropped connection, a timeout, or a
+# 429/5xx from the image host. The public R2 dev endpoint that serves every
+# forge reference image drops connections under load ("Server disconnected
+# without sending a response"), and before this retry each drop ended a
+# generation as an opaque internal error on TripoSG and Hunyuan3D (about 20 a
+# week measured 2026-10-09). Refusals (UnsafeUrlError), oversize bodies, and
+# other 4xx answers are final and never retried.
+_FETCH_ATTEMPTS = 3
+_FETCH_BACKOFF_SECS = (0.5, 1.5)
+
+
+class UnsafeUrlError(ValueError):
+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""
+
+
+def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:
+ """Reject any address that could reach internal infrastructure.
+
+ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud
+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),
+ multicast, reserved, unspecified, and any other non-global address (CGNAT
+ 100.64.0.0/10 included). IPv4-mapped IPv6 addresses
+ are unwrapped first so a mapped private v4 can't slip through.
+ """
+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:
+ ip = ip.ipv4_mapped
+ return (
+ ip.is_private
+ or ip.is_loopback
+ or ip.is_link_local
+ or ip.is_multicast
+ or ip.is_reserved
+ or ip.is_unspecified
+ # Anything not globally routable, which also covers the CGNAT shared
+ # space 100.64.0.0/10 that is_private does not flag.
+ or not ip.is_global
+ )
+
+
+def _resolve_safe_host(host: str) -> None:
+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.
+
+ Resolving and checking every returned address closes the gap where a name
+ resolves to both a public and a private address.
+ """
+ if not host:
+ raise UnsafeUrlError("missing host")
+ try:
+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)
+ except socket.gaierror as exc:
+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc
+
+ addrs = {info[4][0] for info in infos}
+ if not addrs:
+ raise UnsafeUrlError(f"no addresses for host: {host}")
+ for addr in addrs:
+ ip = ipaddress.ip_address(addr)
+ if _is_blocked_ip(ip):
+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")
+
+
+def assert_safe_url(url: str, *, allow_http: bool = False) -> str:
+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.
+
+ https is required by default; ``allow_http`` exists only for callers that
+ legitimately need cleartext (not used by the workers).
+ """
+ parts = urlsplit(url)
+ scheme = parts.scheme.lower()
+ allowed = ("https", "http") if allow_http else ("https",)
+ if scheme not in allowed:
+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")
+ if not parts.hostname:
+ raise UnsafeUrlError("missing host")
+ _resolve_safe_host(parts.hostname)
+ return url
+
+
+def fetch_remote_bytes(
+ url: str,
+ *,
+ timeout: float = 30.0,
+ max_bytes: int = DEFAULT_MAX_BYTES,
+ allow_http: bool = False,
+ headers: Optional[dict] = None,
+) -> bytes:
+ """Fetch ``url`` safely and return its body bytes.
+
+ Hardening applied:
+ * https-only (unless ``allow_http``).
+ * every URL - including each redirect target - is DNS-resolved and
+ rejected if it maps to a private/loopback/link-local/metadata address.
+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is
+ re-validated; httpx's own redirect following is disabled.
+ * the response body is streamed and aborted once it exceeds ``max_bytes``.
+ * transient failures (dropped connection, timeout, 429/5xx) are retried
+ with a short backoff; see ``_FETCH_ATTEMPTS``.
+
+ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /
+ ``ValueError`` for transport or size failures.
+ """
+ for attempt in range(_FETCH_ATTEMPTS - 1):
+ try:
+ return _fetch_once(
+ url, timeout=timeout, max_bytes=max_bytes,
+ allow_http=allow_http, headers=headers,
+ )
+ except httpx.HTTPError as exc:
+ if not _is_transient(exc):
+ raise
+ log.warning("transient fetch failure (attempt %d): %s", attempt + 1, type(exc).__name__)
+ time.sleep(_FETCH_BACKOFF_SECS[attempt])
+ return _fetch_once(
+ url, timeout=timeout, max_bytes=max_bytes,
+ allow_http=allow_http, headers=headers,
+ )
+
+
+def _is_transient(exc: httpx.HTTPError) -> bool:
+ if isinstance(exc, httpx.HTTPStatusError):
+ code = exc.response.status_code
+ return code == 429 or code >= 500
+ return isinstance(exc, httpx.TransportError)
+
+
+def _fetch_once(
+ url: str,
+ *,
+ timeout: float,
+ max_bytes: int,
+ allow_http: bool,
+ headers: Optional[dict],
+) -> bytes:
+ current = assert_safe_url(url, allow_http=allow_http)
+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:
+ for _ in range(_MAX_REDIRECTS + 1):
+ with client.stream("GET", current, headers=headers) as resp:
+ if resp.is_redirect:
+ location = resp.headers.get("location")
+ if not location:
+ raise UnsafeUrlError("redirect without Location header")
+ current = assert_safe_url(
+ str(resp.url.join(location)), allow_http=allow_http
+ )
+ continue
+ resp.raise_for_status()
+ declared = resp.headers.get("content-length")
+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:
+ raise ValueError(f"response too large: {declared} bytes")
+ chunks: list[bytes] = []
+ total = 0
+ for chunk in resp.iter_bytes(65536):
+ total += len(chunk)
+ if total > max_bytes:
+ raise ValueError(f"response exceeded {max_bytes} bytes")
+ chunks.append(chunk)
+ return b"".join(chunks)
+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")
+
+
+async def fetch_remote_bytes_async(
+ client: "httpx.AsyncClient",
+ url: str,
+ *,
+ max_bytes: int = DEFAULT_MAX_BYTES,
+ allow_http: bool = False,
+ headers: Optional[dict] = None,
+) -> bytes:
+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.
+
+ The provided ``client`` MUST be constructed with ``follow_redirects=False``
+ so this function can re-validate each redirect hop itself. Transient
+ failures are retried exactly as in the sync variant.
+ """
+ for attempt in range(_FETCH_ATTEMPTS - 1):
+ try:
+ return await _fetch_once_async(
+ client, url, max_bytes=max_bytes,
+ allow_http=allow_http, headers=headers,
+ )
+ except httpx.HTTPError as exc:
+ if not _is_transient(exc):
+ raise
+ log.warning("transient fetch failure (attempt %d): %s", attempt + 1, type(exc).__name__)
+ await asyncio.sleep(_FETCH_BACKOFF_SECS[attempt])
+ return await _fetch_once_async(
+ client, url, max_bytes=max_bytes,
+ allow_http=allow_http, headers=headers,
+ )
+
+
+async def _fetch_once_async(
+ client: "httpx.AsyncClient",
+ url: str,
+ *,
+ max_bytes: int,
+ allow_http: bool,
+ headers: Optional[dict],
+) -> bytes:
+ current = assert_safe_url(url, allow_http=allow_http)
+ for _ in range(_MAX_REDIRECTS + 1):
+ async with client.stream("GET", current, headers=headers) as resp:
+ if resp.is_redirect:
+ location = resp.headers.get("location")
+ if not location:
+ raise UnsafeUrlError("redirect without Location header")
+ current = assert_safe_url(
+ str(resp.url.join(location)), allow_http=allow_http
+ )
+ continue
+ resp.raise_for_status()
+ declared = resp.headers.get("content-length")
+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:
+ raise ValueError(f"response too large: {declared} bytes")
+ chunks: list[bytes] = []
+ total = 0
+ async for chunk in resp.aiter_bytes(65536):
+ total += len(chunk)
+ if total > max_bytes:
+ raise ValueError(f"response exceeded {max_bytes} bytes")
+ chunks.append(chunk)
+ return b"".join(chunks)
+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")
+
+
+# ── opaque error handling ───────────────────────────────────────────────────────
+
+
+def safe_error(exc: BaseException, *, context: str = "") -> str:
+ """Log the full traceback server-side and return an opaque client message.
+
+ Never leak ``traceback.format_exc()`` (absolute paths, library versions,
+ internal hostnames, fragments of upstream responses) to callers. A short
+ correlation id is embedded in both the log line and the returned string so
+ operators can join a client-reported failure to the server log.
+ """
+ correlation_id = uuid.uuid4().hex[:12]
+ label = f"{context} " if context else ""
+ log.exception("%serror [correlation_id=%s]", label, correlation_id)
+ return f"internal error (ref {correlation_id})"