Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(stylize): accept FBX input on the stylize and remesh workers
nirholas784b93ccb154
diff --git a/api/_lib/stylize-input.js b/api/_lib/stylize-input.jsnew file mode 100644index 000000000..a28479526--- /dev/null+++ b/api/_lib/stylize-input.js@@ -0,0 +1,29 @@+/**+ * Input formats the stylize worker can read, and the refusal for the one it+ * cannot.+ *+ * workers/stylize loads meshes with trimesh, which has no FBX reader, and its+ * image carries no converter. Before this check an FBX was accepted, queued,+ * and then failed inside the worker as an opaque internal error. The worker+ * refuses FBX itself too (a 422 on the URL, and a byte sniff for an FBX behind+ * an extensionless URL); refusing here as well turns that into a clean 400 for+ * callers instead of a 502 relayed from the worker.+ *+ * Kept in lockstep with SUPPORTED_INPUT_LABEL in workers/stylize/main.py.+ */++export const STYLIZE_INPUT_FORMATS = 'GLB, GLTF, OBJ, STL, PLY, OFF or DAE';++export const STYLIZE_FBX_MESSAGE =+ `FBX input is not supported by stylize: supply ${STYLIZE_INPUT_FORMATS}. ` ++ 'To restyle an FBX, convert it to GLB first with remesh (operation "convert", ' ++ 'output_format "glb" via /api/forge-remesh or the remesh_model MCP tool), which reads FBX.';++/** True when the URL's path names an FBX file, whatever the query string carries. */+export function isFbxMeshUrl(url) {+ try {+ return /\.fbx$/i.test(new URL(url).pathname);+ } catch {+ return false;+ }+}diff --git a/api/forge-stylize.js b/api/forge-stylize.jsindex 55e6cb762..924dcb0d5 100644--- a/api/forge-stylize.js+++ b/api/forge-stylize.js@@ -2,7 +2,7 @@* /api/forge-stylize — one-click geometric stylization for the forge pipeline.** POST /api/forge-stylize {- * mesh_url: string,+ * mesh_url: string, // GLB/GLTF/OBJ/STL/PLY/OFF/DAE; FBX is a 400* style?: "voxel"|"brick"|"voronoi"|"lowpoly",* resolution?: number, // style-specific density (clamped)* output_format?: "glb"|"obj"|"stl"|"ply"@@ -20,6 +20,7 @@ import { cors, json, method, readJson, wrap, rateLimited } from './_lib/http.js'import { limits, clientIp } from './_lib/rate-limit.js';import { assertPublicHttpsUrl, SsrfError } from './_lib/ssrf.js';import { createRegenProvider } from './_providers/gcp.js';+import { isFbxMeshUrl, STYLIZE_FBX_MESSAGE } from './_lib/stylize-input.js';// Provider job ids are base64url JSON envelopes (packJobId in _providers/gcp.js)// and run several hundred chars — a 64-char cap 400s every poll.@@ -65,6 +66,9 @@ async function startJob(req, res) {message: err instanceof SsrfError ? `mesh_url rejected: ${err.message}` : 'mesh_url must be a public https URL.',});}+ if (isFbxMeshUrl(meshUrl)) {+ return json(res, 400, { error: 'unsupported_mesh_format', message: STYLIZE_FBX_MESSAGE });+ }// Object.hasOwn, not a bare truthy lookup: `STYLE_BOUNDS[k]` is truthy for// every Object.prototype key, so `style: "constructor"` (or "toString",diff --git a/tests/api/stylize-fbx-input.test.js b/tests/api/stylize-fbx-input.test.jsnew file mode 100644index 000000000..2e8036ed1--- /dev/null+++ b/tests/api/stylize-fbx-input.test.js@@ -0,0 +1,86 @@+/**+ * FBX input on the stylize lane.+ *+ * workers/stylize reads meshes with trimesh, which has no FBX reader, and its+ * image carries no converter. An FBX used to be accepted, queued, and then fail+ * inside the worker as an opaque internal error. The REST route and the+ * stylize_model MCP tool now refuse it up front with the formats that work and+ * the way to convert, and never reach the worker.+ *+ * The SSRF guard (DNS) and the GCP provider (network) are the mocked+ * boundaries; the real tool handler and input check run.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { mcp3dGenerate: async () => ({ success: true, limit: 60, remaining: 59, reset: Date.now() + 60_000 }) },+ clientIp: () => '203.0.113.9',+}));++vi.mock('../../api/_lib/ssrf-guard.js', async (importOriginal) => ({+ ...(await importOriginal()),+ assertSafePublicUrl: async (raw) => new URL(raw),+}));++const submitted = [];+vi.mock('../../api/_providers/gcp.js', () => ({+ createRegenProvider: () => ({+ supportsMode: () => true,+ submit: async (request) => {+ submitted.push(request);+ return { extJobId: 'job-stylize-test-000000000000', eta: 20 };+ },+ }),+}));++const { isFbxMeshUrl, STYLIZE_FBX_MESSAGE, STYLIZE_INPUT_FORMATS } = await import('../../api/_lib/stylize-input.js');++const AUTH = { userId: null, rateKey: 'test-caller' };++async function stylizeTool() {+ const { toolDefs } = await import('../../api/_mcp3d/tools/studio.js');+ return toolDefs.find((t) => t.name === 'stylize_model');+}++beforeEach(() => {+ submitted.length = 0;+ process.env.GCP_RECONSTRUCTION_KEY = 'test-shared-worker-key';+});++describe('isFbxMeshUrl', () => {+ it('matches an FBX path in any case, ignoring the query string', () => {+ expect(isFbxMeshUrl('https://cdn.example/rig.fbx')).toBe(true);+ expect(isFbxMeshUrl('https://cdn.example/rig.FBX?sig=abc&exp=1')).toBe(true);+ });++ it('does not match other formats, an fbx query value, or a malformed URL', () => {+ expect(isFbxMeshUrl('https://cdn.example/scene.dae')).toBe(false);+ expect(isFbxMeshUrl('https://cdn.example/model.glb?name=rig.fbx')).toBe(false);+ expect(isFbxMeshUrl('not a url')).toBe(false);+ });++ it('names every format the worker reads and how to convert an FBX', () => {+ expect(STYLIZE_INPUT_FORMATS).toBe('GLB, GLTF, OBJ, STL, PLY, OFF or DAE');+ expect(STYLIZE_FBX_MESSAGE).toContain(STYLIZE_INPUT_FORMATS);+ expect(STYLIZE_FBX_MESSAGE).toContain('remesh_model');+ });+});++describe('stylize_model MCP tool', () => {+ it('refuses an FBX mesh_url with the supported formats and queues nothing', async () => {+ const def = await stylizeTool();+ const out = await def.handler({ mesh_url: 'https://cdn.example/rig.fbx', style: 'voxel' }, AUTH);+ expect(out.isError).toBe(true);+ expect(out.content[0].text).toContain(STYLIZE_INPUT_FORMATS);+ expect(submitted).toHaveLength(0);+ });++ it('still queues a DAE mesh', async () => {+ const def = await stylizeTool();+ const out = await def.handler({ mesh_url: 'https://cdn.example/scene.dae', style: 'voxel' }, AUTH);+ expect(out.isError).toBeFalsy();+ expect(submitted).toHaveLength(1);+ expect(submitted[0]).toMatchObject({ mode: 'stylize', sourceUrl: 'https://cdn.example/scene.dae' });+ });+});diff --git a/workers/remesh/Dockerfile b/workers/remesh/Dockerfileindex 981900f0b..3209a00ad 100644--- a/workers/remesh/Dockerfile+++ b/workers/remesh/Dockerfile@@ -45,12 +45,13 @@ RUN git clone --depth 1 --recursive https://github.com/hjwdzh/Manifold /tmp/mani&& install -m 0755 /tmp/manifold/build/manifold /usr/local/bin/manifold \&& rm -rf /tmp/manifold-# ── Runtime deps for trimesh / open3d / assimp / usd / Blender ───────────────+# ── Runtime deps for trimesh / open3d / usd / Blender ────────────────────────# The X11/GL libs are for the `bpy` (Blender) module, which links against them-# even when running headless for FBX export.+# even when running headless for FBX import and export. No libassimp: nothing in+# this image loads it (trimesh 4.x has no assimp loader, FBX goes through+# Blender, DAE through pycollada).RUN apt-get update && apt-get install -y --no-install-recommends \libgl1 libglib2.0-0 libgomp1 \- libassimp-dev libassimp5 \libopenblas-dev \libegl1 libxrender1 libxi6 libxxf86vm1 libxfixes3 libxkbcommon0 \libxrandr2 libxcursor1 libxinerama1 libsm6 libice6 libxext6 \diff --git a/workers/remesh/README.md b/workers/remesh/README.mdindex 55d5a1154..bb3d7f339 100644--- a/workers/remesh/README.md+++ b/workers/remesh/README.md@@ -10,7 +10,7 @@ asset pipeline — not the primary generation lanes.Wraps `trimesh` + `open3d` for geometry, [QuadriFlow](https://github.com/hjwdzh/QuadriFlow)(MIT) for quad remeshing, [xatlas](https://github.com/jpcy/xatlas) (MIT) for UVre-unwrap, and headless [Blender](https://www.blender.org/) (`bpy`) for FBX-export. **No GPU required** — everything runs on CPU.+import and export. **No GPU required**: everything runs on CPU.A FastAPI service on Cloud Run. Jobs are accepted immediately (`202`) and polled— a quad remesh with texture re-bake runs far longer than a request should be@@ -18,10 +18,25 @@ held open.## Why Blender for FBX-FBX is the only format here that needs Blender: `trimesh` has no FBX writer, so-FBX is bridged through a temporary GLB handed to a one-shot headless Blender-subprocess (`blender_fbx.py`). USDZ has no trimesh writer either, but it needs no-Blender: it is authored directly on a USD stage with `pxr` (`_write_usdz` in+FBX is the only format here that needs Blender: `trimesh` has neither an FBX+writer nor an FBX reader (it answers `File type: fbx not supported`). So FBX+goes through a one-shot headless Blender subprocess (`blender_fbx.py`) in both+directions:++- **FBX output** is bridged through a temporary GLB that Blender exports as FBX.+- **FBX input** is imported by Blender and written out as a GLB before any+ trimesh pipeline sees it, so every mode and operation accepts a binary FBX.+ The worker recognises FBX by its bytes (`Kaydara FBX Binary` magic) as well as+ by the URL, so a signed or extensionless URL works too. Blender's importer+ reads binary FBX 7.1 and later only; an ASCII FBX (`; FBX` header), a corrupt+ file, or one with no mesh polygons fails the task with `error_kind: "input"`+ and a message that says what to re-export, never an opaque internal error.++DAE input needs no Blender: trimesh reads it through `pycollada`, which+`trimesh[easy]` installs. The image carries no assimp library at all; nothing+in the worker loads it.++USDZ has no trimesh writer either, but it needs no Blender: it is authored directly on a USD stage with `pxr` (`_write_usdz` in[`main.py`](./main.py)). Every other format trimesh writes itself.That Blender subprocess exits without running interpreter finalization, and the@@ -91,7 +106,7 @@ curl -X POST https://$SERVICE_URL/process \| Field | Required | Default | Notes ||---|---|---|---|-| `mesh` | yes | — | `https://` URL to a GLB / GLTF / OBJ / STL / PLY / FBX / OFF / DAE (≤ 128 MB) |+| `mesh` | yes | n/a | `https://` URL to a GLB / GLTF / OBJ / STL / PLY / FBX (binary, 7.1+) / OFF / DAE (≤ 128 MB) || `remesh_mode` | no | `triangle` | `triangle` \| `quad` \| `lowpoly` || `operation` | no | `full` | `convert` \| `simplify` \| `repair` \| `full` (triangle mode) || `target_faces` | no | `50000` | `1000`–`500000` |@@ -130,7 +145,11 @@ against your own copy locally.````status` is `queued` | `running` | `done` | `failed`. On failure the response-carries a sanitized `error` string; the full traceback stays in the server log.+carries an `error` and an `error_kind`. `input` means the caller's file was the+problem and `error` says how to fix it (for example `ASCII FBX is not supported:+re-export the model as binary FBX (FBX 7.1 or later) or as GLB`). `internal`+means a service fault: `error` is an opaque `internal error (ref <id>)` and the+full traceback stays in the server log under that id.`texture_url` / `mtl_url` are populated when a re-bake produces a sidecar PNG or`.mtl` (e.g. a textured `obj` output).@@ -150,7 +169,7 @@ Unauthenticated, so Cloud Run's startup probe can reach it.| `GCS_BUCKET` | yes | — | Output bucket; artifacts land under the `remesh/` prefix (`three-ws-avatar-reconstructions`) || `MAX_CONCURRENT` | no | `2` | In-flight jobs || `QUADRIFLOW_BIN` | no | `quadriflow` | Path to the QuadriFlow executable. The image builds it and sets this to `/usr/local/bin/quadriflow` |-| `BLENDER_TIMEOUT` | no | `300` | Seconds before a Blender FBX export is killed |+| `BLENDER_TIMEOUT` | no | `300` | Seconds before a Blender FBX conversion (export, or the FBX input bridge) is killed || `MANIFOLD_BIN` | no | `manifold` | Path to the [Manifold](https://github.com/hjwdzh/Manifold) executable (built into the image). Quad mode rebuilds an open mesh watertight with it before QuadriFlow, which requires watertight manifold input || `MANIFOLD_RESOLUTION` | no | `50000` | Octree resolution for that rebuild || `MANIFOLD_TIMEOUT` | no | `120` | Seconds before the rebuild is abandoned and the raw mesh is used |@@ -168,8 +187,10 @@ docker build -t remesh workers/remesh[`test_remesh.py`](./test_remesh.py) is the core-path smoke test: the OBJ bridgeto QuadriFlow, repair, QEM decimation, every `operation`, xatlas UV unwrap,texture bake and seam dilation, every export format, request validation, a real-QuadriFlow quad remesh, and a rigged GLB to FBX round trip re-checked with-[`verify_fbx.py`](./verify_fbx.py). The Docker build runs it as a gate, so a+QuadriFlow quad remesh, a rigged GLB to FBX round trip re-checked with+[`verify_fbx.py`](./verify_fbx.py), FBX *input* through every path (FBX to GLB,+FBX repair to OBJ, FBX behind an extensionless URL, FBX to FBX keeping the rig),+DAE input through pycollada, and the input errors for ASCII and corrupt FBX. The Docker build runs it as a gate, so aregression fails the image instead of reaching Cloud Run. Run it on its ownagainst the built image:diff --git a/workers/remesh/blender_fbx.py b/workers/remesh/blender_fbx.pyindex 8f9a2c3be..41b8a6c40 100644--- a/workers/remesh/blender_fbx.py+++ b/workers/remesh/blender_fbx.py@@ -90,7 +90,13 @@ def _import_source(path: Path) -> None:suffix = path.suffix.lower()if suffix in (".glb", ".gltf"):_enable_addon("io_scene_gltf2")- bpy.ops.import_scene.gltf(filepath=str(path), import_pack_images=True)+ # disable_bone_shape: the importer otherwise builds an 80-face+ # "Icosphere" to draw bones in the viewport. It parks it in a hidden+ # collection, but the FBX exporter writes hidden objects too, so every+ # rigged GLB came out of this script carrying a stray sphere mesh.+ bpy.ops.import_scene.gltf(+ filepath=str(path), import_pack_images=True, disable_bone_shape=True,+ )elif suffix == ".fbx":_enable_addon("io_scene_fbx")bpy.ops.import_scene.fbx(filepath=str(path))@@ -166,10 +172,11 @@ def main() -> None:_reset_scene()try:_import_source(in_path)- except RuntimeError as exc:- # Blender's importers raise RuntimeError for a file they cannot parse- # (an ASCII FBX, a pre-7.1 binary FBX, a truncated download). That is a- # problem with the input, not with this process.+ except Exception as exc: # noqa: BLE001+ # Blender's importers raise RuntimeError for a file they report as+ # unreadable (an ASCII FBX, a pre-7.1 binary FBX) and whatever the parser+ # hit for a corrupt one (struct.error, ValueError on a truncated+ # download). Either way the problem is the input, not this process.reason = str(exc).strip().splitlines()_leave(EXIT_IMPORT_EMPTY, f"IMPORT_EMPTY: {reason[-1] if reason else 'import failed'}")faces = _face_count()diff --git a/workers/remesh/main.py b/workers/remesh/main.pyindex 636b51b1b..b2dfbe09c 100644--- a/workers/remesh/main.py+++ b/workers/remesh/main.py@@ -25,7 +25,7 @@ Tooling / licensing:API contract:POST /process {- mesh: url, # https GLB/OBJ/FBX/STL URL (required)+ mesh: url, # https GLB/GLTF/OBJ/FBX/STL/PLY/OFF/DAE URL (required)remesh_mode: "triangle"|"quad"|"lowpoly", # default: "triangle"operation: "convert"|"simplify"|"repair"|"full", # default: "full" (triangle mode only)target_faces?: int, # default: 50000, range: 1000–500000@@ -45,7 +45,7 @@ Environment variables:GCS_BUCKET — output bucket (required)MAX_CONCURRENT — default 2QUADRIFLOW_BIN — path to the quadriflow executable (default: "quadriflow")- BLENDER_TIMEOUT — seconds before a Blender FBX export is killed (default: 300)+ BLENDER_TIMEOUT: seconds before a Blender FBX conversion is killed (default: 300)"""from __future__ import annotations@@ -54,6 +54,7 @@ import asyncioimport ioimport loggingimport os+import reimport shutilimport subprocessimport sys@@ -113,6 +114,23 @@ BLENDER_TIMEOUT = int(os.environ.get("BLENDER_TIMEOUT", "300"))# .off — Blender has no OFF importer at allBLENDER_IMPORT_FORMATS = {".glb", ".fbx", ".obj", ".stl", ".ply"}+# blender_fbx.py exits with this status when the input imported no mesh+# polygons: an unparseable file, an ASCII FBX, or a scene of only bones/lights.+BLENDER_EXIT_IMPORT_EMPTY = 3++# Binary FBX opens with this fixed 21-byte magic. ASCII FBX opens with a+# `; FBX <version>` comment line, and Blender's importer refuses ASCII outright.+FBX_BINARY_MAGIC = b"Kaydara FBX Binary \x00"+FBX_ASCII_HEADER = b"; FBX"+++class InputFormatError(ValueError):+ """The caller's file is in a form this worker cannot read.++ Unlike every other failure, its message is about the caller's input, carries+ nothing internal, and is returned on the task verbatim so the caller knows+ how to fix the file instead of seeing an opaque internal-error reference."""+@asynccontextmanagerasync def lifespan(app: FastAPI):@@ -146,15 +164,31 @@ def _fetch_mesh(url: str) -> tuple[bytes, str]:data = fetch_remote_bytes(url, timeout=60, max_bytes=MAX_MESH_BYTES)except UnsafeUrlError as exc:raise ValueError(f"refused to fetch mesh: {exc}") from exc- suffix = Path(url.split("?")[0]).suffix.lower()- if suffix not in SUPPORTED_INPUT_FORMATS:- suffix = ".glb"+ suffix = _sniff_suffix(data, Path(url.split("?")[0]).suffix.lower())# A meshopt-compressed asset is transcoded here, before any loader sees it:# trimesh cannot read one, and it is the format most three.ws avatars ship# as. Anything else passes through untouched.return decode_if_meshopt(data, suffix)+def _sniff_suffix(data: bytes, url_suffix: str) -> str:+ """Pick the loader suffix, trusting the bytes over the URL for FBX.++ A signed or extensionless URL used to fall back to `.glb` and then fail+ inside the glTF parser with an error that said nothing about FBX. Binary FBX+ is recognised by its magic and routed through Blender; ASCII FBX is refused+ here, with the fix, because Blender's importer cannot read it either."""+ head = data[:64].lstrip(b"\xef\xbb\xbf").lstrip()+ if head.startswith(FBX_ASCII_HEADER):+ raise InputFormatError(+ "ASCII FBX is not supported: re-export the model as binary FBX "+ "(FBX 7.1 or later) or as GLB"+ )+ if data.startswith(FBX_BINARY_MAGIC):+ return ".fbx"+ return url_suffix if url_suffix in SUPPORTED_INPUT_FORMATS else ".glb"++def _load_concatenated(data: bytes, suffix: str):"""Load a mesh, flattening any scene into one Trimesh. Drops materials —used by the triangle pipeline where texture transfer is not performed."""@@ -657,12 +691,16 @@ def _face_count_marker(stdout: str) -> Optional[int]:return None-def _blender_to_fbx(in_path: Path, out_path: Path, static: bool) -> int:- """Convert a local model file to FBX via headless Blender, preserving the- skeleton, skin weights, and blendshapes when the input carries them.+def _blender_convert(in_path: Path, out_path: Path, static: bool) -> int:+ """Convert a local model file via headless Blender, by `out_path`'s suffix.++ `.fbx` exports an FBX, preserving the skeleton, skin weights, and+ blendshapes when the input carries them. `.glb` is the input bridge: it is+ how an FBX the caller sends becomes something trimesh can read.- Returns the exported polygon count. Raises RuntimeError with a clipped log- tail on failure. `static=True` skips animation baking (used when the upstream+ Returns the converted polygon count. Raises InputFormatError when the input+ imported no mesh polygons, and RuntimeError with a clipped log tail on any+ other failure. `static=True` skips animation baking (used when the upstreamgeometry op already discarded any rig).Completion is judged by the child's FACE_COUNT marker plus a non-empty file,@@ -679,24 +717,68 @@ def _blender_to_fbx(in_path: Path, out_path: Path, static: bool) -> int:cmd, capture_output=True, text=True, timeout=BLENDER_TIMEOUT, check=False,)except subprocess.TimeoutExpired as exc:- raise RuntimeError(f"FBX export timed out after {BLENDER_TIMEOUT}s") from exc+ raise RuntimeError(+ f"Blender {in_path.suffix} to {out_path.suffix} conversion timed out after {BLENDER_TIMEOUT}s"+ ) from exc++ if proc.returncode == BLENDER_EXIT_IMPORT_EMPTY:+ raise InputFormatError(_import_empty_message(in_path.suffix, proc.stderr))faces = _face_count_marker(proc.stdout)written = out_path.exists() and out_path.stat().st_size > 0if faces is None or not written:tail = (proc.stderr or proc.stdout or "").strip().splitlines()[-6:]raise RuntimeError(- f"FBX export failed (rc={proc.returncode}): " + " | ".join(tail)+ f"Blender {in_path.suffix} to {out_path.suffix} conversion failed "+ f"(rc={proc.returncode}): " + " | ".join(tail))if proc.returncode != 0:log.warning(- "blender exited abnormally (rc=%s) after writing a complete %s-byte FBX; keeping it",- proc.returncode, out_path.stat().st_size,+ "blender exited abnormally (rc=%s) after writing a complete %s-byte %s; keeping it",+ proc.returncode, out_path.stat().st_size, out_path.suffix,)return faces+def _import_empty_message(suffix: str, stderr: str) -> str:+ """The caller-facing reason an input imported nothing.++ Blender's own wording is kept when it names the problem (it says so for a+ pre-7.1 binary FBX, for example), since that is the most precise fix."""+ reason = ""+ for line in (stderr or "").splitlines():+ if line.startswith("IMPORT_EMPTY:"):+ reason = line.split(":", 1)[1].strip()+ if reason.lower().startswith("error:"):+ reason = reason[len("error:"):].strip()+ # Blender quotes the temp path it was handed ('/tmp/tmpab12/input.fbx');+ # that is this container's filesystem, not something the caller sent.+ reason = re.sub(r"\s*'[^']*/[^']*'", "", reason)+ reason = re.sub(r"\s*\(\s*\)", "", reason).strip()+ label = suffix.lstrip(".").upper() or "file"+ detail = f": {reason}" if reason else ""+ message = f"could not read any mesh from the {label}{detail}"+ if suffix == ".fbx":+ message += ". Supply a binary FBX (7.1 or later) or a GLB"+ return message+++def _fbx_to_glb(data: bytes) -> bytes:+ """Bridge a caller's FBX into a GLB that the trimesh pipelines can load.++ trimesh 4.x has no FBX reader at all, so before this every FBX input outside+ the rig-preserving FBX-to-FBX convert failed with "File type: fbx not+ supported". Blender is already in this image for FBX export, and its FBX+ importer is the same one the rest of the industry relies on."""+ with tempfile.TemporaryDirectory() as tmp:+ src_path = Path(tmp) / "input.fbx"+ src_path.write_bytes(data)+ glb_path = Path(tmp) / "bridge.glb"+ _blender_convert(src_path, glb_path, static=True)+ return glb_path.read_bytes()++def _convert_to_fbx_preserving_rig(data: bytes, suffix: str, task_id: str) -> tuple[list, dict]:"""`convert` → FBX without touching geometry, so a rigged GLB keeps its bonehierarchy, skin weights, and blendshapes. Blender imports the source@@ -708,13 +790,13 @@ def _convert_to_fbx_preserving_rig(data: bytes, suffix: str, task_id: str) -> tuif suffix in BLENDER_IMPORT_FORMATS:src_path = Path(tmp) / f"input{suffix}"src_path.write_bytes(data)- faces = _blender_to_fbx(src_path, out_path, static=False)+ faces = _blender_convert(src_path, out_path, static=False)else:import trimeshmesh = _load_concatenated(data, suffix)glb_path = Path(tmp) / "bridge.glb"trimesh.scene.scene.Scene(geometry={"mesh": mesh}).export(str(glb_path))- faces = _blender_to_fbx(glb_path, out_path, static=True)+ faces = _blender_convert(glb_path, out_path, static=True)fbx_bytes = out_path.read_bytes()meta = {"quad_ratio": 0.0, "textured": False, "face_count": faces}return [Artifact(f"{task_id}.fbx", fbx_bytes, "application/octet-stream", "model")], meta@@ -808,7 +890,7 @@ def _export_simple(mesh, output_format: str, task_id: str) -> list:if fmt == "fbx":glb_path = Path(tmpdir) / f"{task_id}.glb"trimesh.scene.scene.Scene(geometry={"mesh": mesh}).export(str(glb_path))- _blender_to_fbx(glb_path, out_path, static=True)+ _blender_convert(glb_path, out_path, static=True)elif fmt == "usdz":_write_usdz(mesh, task_id, out_path)elif fmt == "glb":@@ -924,6 +1006,10 @@ def _run_processing(if output_format == "fbx" and remesh_mode == "triangle" and operation == "convert":return _convert_to_fbx_preserving_rig(data, suffix, task_id)+ # Every other path reads the input with trimesh, which cannot parse FBX.+ if suffix == ".fbx":+ data, suffix = _fbx_to_glb(data), ".glb"+if remesh_mode == "quad":source = _load_textured(data, suffix)return _process_quad(source, target_faces, output_format, texture_size, task_id)@@ -998,16 +1084,27 @@ async def _process(meta.get("quad_ratio"), meta.get("textured"), urls.get("model"),)+ except InputFormatError as exc:+ log.info("[%s] rejected input: %s", task_id, exc)+ _tasks[task_id].update({+ "status": "failed",+ "error": str(exc),+ # Same taxonomy the avatar workers report and api/_providers/gcp.js+ # relays: `input` means `error` is caller-facing copy.+ "error_kind": "input",+ "elapsed_ms": int((time.time() - t0) * 1000),+ })except Exception as exc:_tasks[task_id].update({"status": "failed","error": safe_error(exc, context=f"[{task_id}] remesh"),+ "error_kind": "internal","elapsed_ms": int((time.time() - t0) * 1000),})class ProcessRequest(BaseModel):- mesh: str = Field(..., description="https URL to input mesh (GLB/OBJ/FBX/STL/PLY)")+ mesh: str = Field(..., description="https URL to input mesh (GLB/GLTF/OBJ/FBX/STL/PLY/OFF/DAE)")remesh_mode: str = Field(default="triangle", description="triangle|quad|lowpoly")operation: str = Field(default="full", description="convert|simplify|repair|full")target_faces: int = Field(default=50_000, ge=1_000, le=500_000)diff --git a/workers/remesh/test_remesh.py b/workers/remesh/test_remesh.pyindex 7ef8abddc..47ec1f6dc 100644--- a/workers/remesh/test_remesh.py+++ b/workers/remesh/test_remesh.py@@ -17,6 +17,7 @@ the image every dependency is present and nothing is skipped.from __future__ import annotations+import asyncioimport ioimport osimport shutil@@ -378,6 +379,82 @@ for label, kwargs in (check(f"request rejects bad {label}", True)+# -- input format detection ----------------------------------------------------+# trimesh 4.x reads DAE (through pycollada) but has no FBX reader at all, so FBX+# input is routed through Blender. The bytes decide, not just the URL: an+# extensionless URL used to fall back to the glTF parser and fail opaquely.++FBX_MAGIC_HEAD = remesh.FBX_BINARY_MAGIC + b"\x00" * 16+check("binary FBX magic routes to the FBX bridge whatever the URL says",+ remesh._sniff_suffix(FBX_MAGIC_HEAD, ".bin") == ".fbx")+check("binary FBX behind an extensionless URL routes to the FBX bridge",+ remesh._sniff_suffix(FBX_MAGIC_HEAD, "") == ".fbx")+check("a GLB keeps its URL suffix", remesh._sniff_suffix(b"glTF\x02\x00\x00\x00", ".glb") == ".glb")+check("a DAE keeps its URL suffix", remesh._sniff_suffix(b"<?xml version", ".dae") == ".dae")+check("an unknown suffix falls back to glb", remesh._sniff_suffix(b"glTF", ".bin") == ".glb")+for label, head in (+ ("ASCII FBX", b"; FBX 7.4.0 project file\n"),+ ("ASCII FBX with a BOM and leading blank line", b"\xef\xbb\xbf\n; FBX 7.3.0 project file\n"),+):+ try:+ remesh._sniff_suffix(head, ".fbx")+ check(f"{label} is refused with a fix", False, "accepted")+ except remesh.InputFormatError as exc:+ check(f"{label} is refused with a fix", "binary FBX" in str(exc) and "GLB" in str(exc), str(exc))++_dae_bytes = trimesh.exchange.dae.export_collada(trimesh.creation.box())+_dae_mesh = remesh._load_concatenated(_dae_bytes, ".dae")+check("DAE input loads through pycollada", len(_dae_mesh.faces) == 12, str(len(_dae_mesh.faces)))+check("DAE input loads in the textured loader", len(remesh._load_textured(_dae_bytes, ".dae").faces) == 12)+++def run_with_bytes(data: bytes, url: str, **overrides):+ """Drive the real _run_processing (sniff, meshopt decode, FBX bridge,+ pipelines, export) on in-memory bytes, standing in only for the network."""+ params = {"remesh_mode": "triangle", "operation": "convert", "target_faces": 50_000,+ "output_format": "glb", "texture_size": 1024, "task_id": "smoke"}+ params.update(overrides)+ real_fetch = remesh.fetch_remote_bytes+ remesh.fetch_remote_bytes = lambda *_a, **_k: data+ try:+ return remesh._run_processing(+ url, params["remesh_mode"], params["operation"], params["target_faces"],+ params["output_format"], params["texture_size"], params["task_id"],+ )+ finally:+ remesh.fetch_remote_bytes = real_fetch+++_dae_artifacts, _dae_meta = run_with_bytes(_dae_bytes, "https://example.com/model.dae")+_dae_out = trimesh.load(io.BytesIO(_dae_artifacts[0].data), file_type="glb", force="mesh")+check("a DAE converts end to end to GLB", _dae_meta["face_count"] == 12 and len(_dae_out.faces) == 12,+ str(_dae_meta))++try:+ run_with_bytes(b"; FBX 7.4.0 project file\n", "https://example.com/model")+ check("an ASCII FBX job fails as an input error", False, "accepted")+except remesh.InputFormatError:+ check("an ASCII FBX job fails as an input error", True)+++async def _run_task_on(data: bytes, url: str) -> dict:+ remesh._sem = asyncio.Semaphore(1)+ remesh._tasks["input-error"] = {"task_id": "input-error", "status": "queued"}+ real_fetch = remesh.fetch_remote_bytes+ remesh.fetch_remote_bytes = lambda *_a, **_k: data+ try:+ await remesh._process("input-error", url, "triangle", "full", 50_000, "glb", 1024)+ finally:+ remesh.fetch_remote_bytes = real_fetch+ return remesh._tasks.pop("input-error")+++_task = asyncio.run(_run_task_on(b"; FBX 7.4.0 project file\n", "https://example.com/model.fbx"))+check("an input error reaches the caller verbatim, not as an opaque ref",+ _task["status"] == "failed" and _task.get("error_kind") == "input"+ and "ASCII FBX" in _task["error"] and "internal error" not in _task["error"], str(_task))++# -- quad remesh (needs the quadriflow binary) -------------------------------if shutil.which(remesh.QUADRIFLOW_BIN) or os.path.isfile(remesh.QUADRIFLOW_BIN):@@ -534,9 +611,12 @@ if has_bpy:)fbx_path = Path(tmp) / "rigged.fbx"- faces = remesh._blender_to_fbx(glb_path, fbx_path, static=False)+ faces = remesh._blender_convert(glb_path, fbx_path, static=False)check("blender_fbx exported an FBX", fbx_path.exists() and fbx_path.stat().st_size > 0)check("blender_fbx reported a face count", faces > 0, str(faces))+ source_faces = len(trimesh.load(str(glb_path), force="mesh").faces)+ check("rigged FBX carries only the source mesh, no bone-display sphere",+ faces == source_faces, f"{faces} faces exported, source has {source_faces}")verify = subprocess.run([sys.executable, str(Path(__file__).parent / "verify_fbx.py"), str(fbx_path)],@@ -549,7 +629,7 @@ if has_bpy:)static_path = Path(tmp) / "static.fbx"- remesh._blender_to_fbx(glb_path, static_path, static=True)+ remesh._blender_convert(glb_path, static_path, static=True)check("blender_fbx --static exported an FBX", static_path.stat().st_size > 0)artifacts, meta = remesh._convert_to_fbx_preserving_rig(@@ -559,6 +639,46 @@ if has_bpy:check("fbx convert reports a face count", meta["face_count"] > 0, str(meta))check("fbx convert reports no quads and no bake", meta["quad_ratio"] == 0.0 and meta["textured"] is False)+ # FBX *input*. trimesh has no FBX reader, so every path except the+ # rig-preserving FBX-to-FBX convert used to fail with "File type: fbx+ # not supported". Blender now bridges it to a GLB first.+ fbx_bytes = fbx_path.read_bytes()+ bridged = remesh._fbx_to_glb(fbx_bytes)+ bridged_mesh = trimesh.load(io.BytesIO(bridged), file_type="glb", force="mesh")+ check("an FBX bridges to a GLB trimesh can read", len(bridged_mesh.faces) == source_faces,+ f"{len(bridged_mesh.faces)} faces, source has {source_faces}")++ for label, url, overrides, fmt in (+ ("FBX to GLB convert", "https://example.com/rigged.fbx", {}, "glb"),+ ("FBX repair to OBJ", "https://example.com/rigged.fbx",+ {"operation": "repair", "output_format": "obj"}, "obj"),+ ("FBX behind an extensionless URL", "https://example.com/download?sig=abc", {}, "glb"),+ ):+ arts, info = run_with_bytes(fbx_bytes, url, **overrides)+ out = trimesh.load(io.BytesIO(arts[0].data), file_type=fmt, force="mesh")+ check(f"{label} produces real geometry", len(out.faces) > 0 and info["face_count"] > 0,+ f"{len(out.faces)} faces, {info}")++ arts, info = run_with_bytes(fbx_bytes, "https://example.com/rigged.fbx", output_format="fbx")+ refbx_path = Path(tmp) / "refbx.fbx"+ refbx_path.write_bytes(arts[0].data)+ reverify = subprocess.run(+ [sys.executable, str(Path(__file__).parent / "verify_fbx.py"), str(refbx_path)],+ capture_output=True, text=True,+ )+ check("FBX to FBX convert keeps the skeleton", reverify.returncode == 0,+ (reverify.stdout + reverify.stderr)[-600:])++ corrupt = Path(tmp) / "corrupt.fbx"+ corrupt.write_bytes(remesh.FBX_BINARY_MAGIC + b"\x1a\x00" + os.urandom(256))+ try:+ remesh._blender_convert(corrupt, Path(tmp) / "corrupt.glb", static=True)+ check("a corrupt FBX fails as an input error", False, "converted")+ except remesh.InputFormatError as exc:+ check("a corrupt FBX fails as an input error", "FBX" in str(exc), str(exc))+ check("the input error does not leak container paths", "/tmp" not in str(exc) and tmp not in str(exc),+ str(exc))+# ── meshopt-compressed input ─────────────────────────────────────────────────# Callers hand this worker avatar URLs, and most three.ws avatars are saved withdiff --git a/workers/stylize/Dockerfile b/workers/stylize/Dockerfileindex f1ccb7d4f..86efb5a05 100644--- a/workers/stylize/Dockerfile+++ b/workers/stylize/Dockerfile@@ -20,9 +20,11 @@ ENV PYTHONDONTWRITEBYTECODE=1 \COPY --from=gltfpack /usr/local/bin/gltfpack /usr/local/bin/gltfpack+# GL/OpenMP/BLAS runtime for open3d and trimesh. No libassimp: nothing in this+# image loads it (trimesh 4.x has no assimp loader, DAE input goes through+# pycollada, and FBX input is refused).RUN apt-get update && apt-get install -y --no-install-recommends \libgl1 libglib2.0-0 libgomp1 \- libassimp-dev libassimp5 \libopenblas-dev \&& rm -rf /var/lib/apt/lists/*diff --git a/workers/stylize/README.md b/workers/stylize/README.mdindex 1c7a028dc..f6471c90d 100644--- a/workers/stylize/README.md+++ b/workers/stylize/README.md@@ -36,8 +36,25 @@ Hard safety caps (`MAX_VOXELS = 60_000`,`MAX_LATTICE_EDGES = 6_000`, `MAX_MESH_BYTES = 128 MiB`) mean a hostile or hugeinput can never exhaust memory — resolution backs off automatically.-Input formats: `.glb`, `.gltf`, `.obj`, `.stl`, `.ply`, `.fbx`, `.off`, `.dae`-(FBX/DAE via `pyassimp`). Output formats: `glb` (default), `obj`, `stl`, `ply`.+Input formats: `.glb`, `.gltf`, `.obj`, `.stl`, `.ply`, `.off`, `.dae` (DAE+through `pycollada`, which `trimesh[easy]` installs). Output formats: `glb`+(default), `obj`, `stl`, `ply`.++**FBX is not accepted.** trimesh has no FBX reader and this image carries no+converter, so an FBX is refused up front instead of failing inside the parser:++- an `.fbx` mesh URL is a `422` whose message names the formats above;+- an FBX behind an extensionless or signed URL is caught by its bytes (the+ binary `Kaydara FBX Binary` magic or an ASCII `; FBX` header) and the task+ fails with `error_kind: "input"` and that same caller-facing message, not an+ opaque `internal error (ref …)`;+- `/api/forge-stylize` answers `400 unsupported_mesh_format` and the+ `stylize_model` MCP tool returns an error before any job is queued.++To restyle an FBX, convert it to GLB first with the remesh worker+(`operation: "convert"`, `output_format: "glb"`, via `/api/forge-remesh` or the+`remesh_model` MCP tool), which reads binary FBX through headless Blender, then+stylize the GLB it returns.A glTF asset that declares `EXT_meshopt_compression` (what `gltfpack` emits, andwhat most three.ws avatars ship as) is transcoded to plain glTF by@@ -70,7 +87,8 @@ is a `401`. Jobs are async: `POST /process` returns immediately with a`worker_security.fetch_remote_bytes` rejects private/loopback/metadata hosts —SSRF defense; `/api/forge-stylize` also pre-validates it). `style` defaults to`voxel`, `resolution` is clamped to the style's bounds (a missing/`null` value-uses the default), `output_format` defaults to `glb`.+uses the default), `output_format` defaults to `glb`. An `.fbx` `mesh` is a+`422` that names the supported input formats.Response:@@ -95,7 +113,10 @@ Response:````status` is `queued` → `running` → `done` | `failed`. On failure the body-carries a sanitized `error`. Unknown ids return `404`. The finished mesh is+carries an `error` and an `error_kind`: `input` means the caller's file was the+problem and `error` says how to fix it (an FBX, for example); `internal` means a+service fault and `error` is an opaque `internal error (ref <id>)` that matches+the full traceback in the service log. Unknown ids return `404`. The finished mesh isuploaded to the `GCS_BUCKET` under `stylize/<task_id>.<format>` and served fromits public GCS URL; that upload retries transient transport failures, so a TLSblip no longer discards work the worker already did.@@ -193,9 +214,9 @@ API_KEY=dev-secret GCS_BUCKET=your-dev-bucket \```(Uploads need Application Default Credentials with write access to-`GCS_BUCKET`.) The container image installs `libassimp` + `libgl` system libs-so FBX/DAE input and headless mesh IO work, plus the pinned `gltfpack` binary-for meshopt input.+`GCS_BUCKET`.) The container image installs the GL, OpenMP and BLAS system libs+open3d and trimesh need for headless mesh IO, plus the pinned `gltfpack` binary+for meshopt input. It ships no assimp: nothing in the worker loads it.To run it as a self-hosted OIN node with no cloud account at all, keep resultson disk and skip GCS entirely:@@ -267,6 +288,6 @@ curl -s -X POST https://three.ws/api/forge-stylize \| [`test_gltf_meshopt.py`](test_gltf_meshopt.py) | Tests for the decode; a Docker build gate alongside the filter suite. || [`oin.py`](oin.py) | OIN protocol layer: canonicalization, job digests, Ed25519 signing, the `/oin/*` routes. Vendored copy, kept byte-identical across workers. || [`oin_upload.py`](oin_upload.py) | OIN result sinks: GCS in production, a local directory for self-hosted runs. |-| [`requirements.txt`](requirements.txt) | Pinned deps (`trimesh`, `open3d`, `scipy`, `pyassimp`, `pynacl`, …). |-| [`Dockerfile`](Dockerfile) | `python:3.11-slim` + assimp/GL system libs + pinned `gltfpack`; uvicorn on `:8080`. |+| [`requirements.txt`](requirements.txt) | Pinned deps (`trimesh[easy]` with `pycollada`, `open3d`, `scipy`, `pynacl`, …). |+| [`Dockerfile`](Dockerfile) | `python:3.11-slim` + GL/OpenMP/BLAS system libs + pinned `gltfpack`; uvicorn on `:8080`. || [`cloudbuild.yaml`](cloudbuild.yaml) | Cloud Build → Artifact Registry → Cloud Run deploy. |diff --git a/workers/stylize/main.py b/workers/stylize/main.pyindex c2e1d701a..627ee8a87 100644--- a/workers/stylize/main.py+++ b/workers/stylize/main.py@@ -17,7 +17,7 @@ default material is applied.API contract:POST /process {- mesh: url, # https GLB/OBJ/FBX/STL/PLY URL (required)+ mesh: url, # https GLB/GLTF/OBJ/STL/PLY/OFF/DAE URL (required; FBX is refused)style: "voxel"|"brick"|"voronoi"|"lowpoly", # default: "voxel"resolution?: int, # style-specific density (see /styles)output_format?: "glb"|"obj"|"stl"|"ply", # default: "glb"@@ -82,7 +82,20 @@ _tasks: dict[str, dict] = {}# far beyond any caller's poll window, and the results themselves live in GCS.MAX_TRACKED_TASKS = 500-SUPPORTED_INPUT_FORMATS = {".glb", ".gltf", ".obj", ".stl", ".ply", ".fbx", ".off", ".dae"}+# Every input trimesh 4.x reads in this image (DAE through pycollada, which+# trimesh[easy] installs). FBX is deliberately absent: trimesh has no FBX reader+# and this image carries no converter, so an FBX is refused up front with the+# list below instead of failing inside the parser as an internal error.+SUPPORTED_INPUT_FORMATS = {".glb", ".gltf", ".obj", ".stl", ".ply", ".off", ".dae"}+SUPPORTED_INPUT_LABEL = "GLB, GLTF, OBJ, STL, PLY, OFF or DAE"+FBX_UNSUPPORTED_MESSAGE = (+ f"FBX input is not supported by stylize: supply {SUPPORTED_INPUT_LABEL}. "+ "To restyle an FBX, convert it to GLB first (the remesh worker's convert "+ "operation reads FBX)."+)+# Binary FBX opens with this fixed magic; ASCII FBX with a `; FBX` comment line.+FBX_BINARY_MAGIC = b"Kaydara FBX Binary \x00"+FBX_ASCII_HEADER = b"; FBX"SUPPORTED_OUTPUT_FORMATS = {"glb", "obj", "stl", "ply"}MAX_MESH_BYTES = 128 * 1024 * 1024@@ -187,12 +200,34 @@ def _require_api_key(authorization: Optional[str]) -> None:# ── mesh IO ───────────────────────────────────────────────────────────────────────+class InputFormatError(ValueError):+ """The caller's file is in a format this worker cannot read.++ Its message names the formats that do work and is returned on the task+ verbatim (error_kind "input"), unlike internal failures, which stay opaque."""+++def _url_suffix(url: str) -> str:+ return Path(url.split("?")[0].split("#")[0]).suffix.lower()+++def _is_fbx(data: bytes) -> bool:+ if data.startswith(FBX_BINARY_MAGIC):+ return True+ return data[:64].lstrip(b"\xef\xbb\xbf").lstrip().startswith(FBX_ASCII_HEADER)++def _fetch_mesh(url: str) -> tuple[bytes, str]:try:data = fetch_remote_bytes(url, timeout=60, max_bytes=MAX_MESH_BYTES)except UnsafeUrlError as exc:raise ValueError(f"refused to fetch mesh: {exc}") from exc- suffix = Path(url.split("?")[0]).suffix.lower()+ # The bytes decide, not just the URL: a signed or extensionless URL would+ # otherwise fall back to the glTF parser and fail there with an error that+ # says nothing about FBX.+ if _url_suffix(url) == ".fbx" or _is_fbx(data):+ raise InputFormatError(FBX_UNSUPPORTED_MESSAGE)+ suffix = _url_suffix(url)if suffix not in SUPPORTED_INPUT_FORMATS:suffix = ".glb"return data, suffix@@ -572,20 +607,41 @@ async def _process(task_id: str, mesh_url: str, style: str, resolution: int, out"[%s] %s done in %.2fs — %d faces, %d bytes → %s",task_id, style, elapsed, face_count, len(out_bytes), result_url,)+ except InputFormatError as exc:+ log.info("[%s] rejected input: %s", task_id, exc)+ _tasks[task_id].update({+ "status": "failed",+ "error": str(exc),+ # Same taxonomy the avatar workers report and api/_providers/gcp.js+ # relays: `input` means `error` is caller-facing copy.+ "error_kind": "input",+ "elapsed_ms": int((time.time() - t0) * 1000),+ })except Exception as exc: # noqa: BLE001_tasks[task_id].update({"status": "failed","error": safe_error(exc, context=f"[{task_id}] stylize {style}"),+ "error_kind": "internal","elapsed_ms": int((time.time() - t0) * 1000),})class ProcessRequest(BaseModel):- mesh: str = Field(..., description="https URL to input mesh (GLB/OBJ/FBX/STL/PLY)")+ mesh: str = Field(..., description="https URL to input mesh (GLB/GLTF/OBJ/STL/PLY/OFF/DAE)")style: str = Field(default="voxel", description="|".join(STYLE_CATALOG))resolution: Optional[int] = Field(default=None, description="Style-specific density; see /styles")output_format: str = Field(default="glb")+ @field_validator("mesh")+ @classmethod+ def validate_mesh(cls, v: str) -> str:+ # Refuse an FBX at the door with a 422 that names the supported formats,+ # rather than accepting a job that can only fail. An FBX behind an+ # extensionless URL is caught by the byte sniff in _fetch_mesh.+ if _url_suffix(v) == ".fbx":+ raise ValueError(FBX_UNSUPPORTED_MESSAGE)+ return v+@field_validator("style")@classmethoddef validate_style(cls, v: str) -> str:diff --git a/workers/stylize/test_stylize.py b/workers/stylize/test_stylize.pyindex d5bbb5bab..b6c155f1f 100644--- a/workers/stylize/test_stylize.py+++ b/workers/stylize/test_stylize.py@@ -13,6 +13,7 @@ library's default upload retry policy never engages without if_generation_match.from __future__ import annotations+import asyncioimport osimport sys@@ -150,6 +151,77 @@ check().status_code == 404,)+# ── FBX is refused, with the formats that work ──────────────────────────────────+# trimesh has no FBX reader and this image carries no converter, so an FBX used+# to be accepted and then die inside the parser as an opaque internal error.++_fbx_job = client.post(+ "/process",+ json={"mesh": "https://example.com/rig.FBX?sig=1", "style": "voxel"},+ headers={"authorization": f"Bearer {main.API_KEY}"},+)+check(+ "an FBX mesh URL is a 422 that names the supported formats",+ _fbx_job.status_code == 422 and "GLB, GLTF, OBJ, STL, PLY, OFF or DAE" in _fbx_job.text,+ f"{_fbx_job.status_code} {_fbx_job.text[:300]}",+)+check("fbx is not an accepted input suffix", ".fbx" not in main.SUPPORTED_INPUT_FORMATS)+++def _fetch_bytes(data: bytes, url: str):+ real = main.fetch_remote_bytes+ main.fetch_remote_bytes = lambda *_a, **_k: data+ try:+ return main._fetch_mesh(url)+ finally:+ main.fetch_remote_bytes = real+++for label, data, url in (+ ("binary FBX behind an extensionless URL", main.FBX_BINARY_MAGIC + b"\x00" * 32, "https://example.com/dl?sig=1"),+ ("ASCII FBX behind a .bin URL", b"; FBX 7.4.0 project file\n", "https://example.com/model.bin"),+ ("an .fbx URL whatever the bytes", b"glTF\x02\x00\x00\x00", "https://example.com/model.fbx"),+):+ try:+ _fetch_bytes(data, url)+ check(f"{label} is refused as an input error", False, "accepted")+ except main.InputFormatError as exc:+ check(f"{label} is refused as an input error", "FBX input is not supported" in str(exc), str(exc))++check("a DAE URL keeps its loader", _fetch_bytes(b"<?xml", "https://example.com/m.dae")[1] == ".dae")+check("an extensionless GLB still loads as glb", _fetch_bytes(b"glTF", "https://example.com/dl")[1] == ".glb")++_dae = trimesh.exchange.dae.export_collada(trimesh.creation.box())+check("DAE input loads through pycollada", len(main._load_single_mesh(_dae, ".dae").faces) == 12)+_real_fetch_bytes = main.fetch_remote_bytes+main.fetch_remote_bytes = lambda *_a, **_k: _dae+try:+ _dae_out, _dae_faces, _ = main._run_processing("https://example.com/box.dae", "lowpoly", 8, "glb")+finally:+ main.fetch_remote_bytes = _real_fetch_bytes+check("a DAE stylizes end to end", _dae_out[:4] == b"glTF" and _dae_faces > 0, f"faces={_dae_faces}")+++async def _run_task_on(data: bytes, url: str) -> dict:+ main._sem = asyncio.Semaphore(1)+ main._remember_task({"task_id": "fbx-in", "status": "queued"})+ real = main.fetch_remote_bytes+ main.fetch_remote_bytes = lambda *_a, **_k: data+ try:+ await main._process("fbx-in", url, "voxel", 16, "glb")+ finally:+ main.fetch_remote_bytes = real+ return main._tasks.pop("fbx-in")+++_task = asyncio.run(_run_task_on(main.FBX_BINARY_MAGIC + b"\x00" * 32, "https://example.com/dl"))+check(+ "an FBX job fails with caller-facing copy, not an opaque ref",+ _task["status"] == "failed" and _task.get("error_kind") == "input"+ and "FBX input is not supported" in _task["error"],+ str(_task),+)+# ── task tracking ───────────────────────────────────────────────────────────────main._tasks.clear()