Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

feat: deliver launch film player, 3-grid gallery, animated asset showcase, and viewer enhancements (#56)

Matthew Kissinger8834ceac0ece
diff --git a/README.md b/README.md
index 1f594b85..ae9ee3d8 100644
--- a/README.md
+++ b/README.md
@@ -13,13 +13,19 @@ Kiln runs locally. It includes an MCP server, a CLI, a TypeScript library, and s
for authoring, editing, animation review, and scene composition. Your agent supplies
the model; Kiln does not require a separate model API key for its tools.
-| Abyssal surveyor · GPT-6 Astra | Typewriter · Muse Spark 1.3 | Solar sail courier · Gemini 3.8 Flash |
-| --- | --- | --- |
-| [![Curved-hull survey submersible with an articulated sampling arm](examples/renders/abyssal-surveyor.png)](examples/abyssal-surveyor.kiln.js) | [![Mechanical typewriter](examples/renders/typewriter.png)](examples/typewriter.kiln.js) | [![Faceted gold solar sails supported by dark trussed spars](examples/renders/solar-sail-courier.png)](examples/solar-sail-courier.kiln.js) |
+<video src="assets/video/kiln-launch.mp4" poster="assets/video/kiln-launch-poster.png" controls="controls" width="100%">
+ <a href="assets/video/kiln-launch.mp4">Watch the Kiln launch video (2:44)</a>
+</video>
+
+![Kiln gallery grid 1](assets/gallery/gallery-grid-01.png)
-| Mechanical peacock · Claude Opus 5 | Orbital station · GPT-6 Astra |
-| --- | --- |
-| [![Mechanical peacock with a jewel-coloured fan and brass frame](examples/renders/mechanical-peacock.png)](examples/mechanical-peacock.kiln.js) | [![Orbital station with a symmetric rear service hub, paired radiators and communications dishes](examples/renders/orbital-station.png)](examples/orbital-station.kiln.js) |
+![Kiln gallery grid 2](assets/gallery/gallery-grid-02.png)
+
+![Kiln gallery grid 3](assets/gallery/gallery-grid-03.png)
+
+| Mechanical peacock · Claude Opus 5 | Unfolding dragonfly · GPT-6 Astra | Solar sail courier · Gemini 3.8 Flash |
+| --- | --- | --- |
+| [![Mechanical peacock with articulated jewel fan](assets/gallery/mechanical-peacock.gif)](examples/mechanical-peacock.kiln.js) | [![Clockwork dragonfly with unfolding wings and gears](assets/gallery/demo-unfolding-dragonfly.gif)](examples/demo-unfolding-dragonfly.kiln.js) | [![Solar sail courier deploying origami gold sails](assets/gallery/solar-sail-courier.gif)](examples/solar-sail-courier.kiln.js) |
Mechanical peacock · Claude Opus 5. Maintainer-agent repairs connect the neck and
correct the body shell's face direction; the [source revisions](site/examples/history/mechanical-peacock/history.json)
@@ -35,6 +41,7 @@ The [source revisions](site/examples/history/orbital-station/history.json) retai
These are saved examples from different authoring runs, not a model ranking.
[Credits, review conditions and build records](docs/example-provenance.md).
+
Start with the [installation guide](docs/install.md) for a built package on macOS,
Windows, or Linux. It uses Node.js and creates a project-local agent setup.
Package checks pass on Windows, Linux, and hosted macOS runners for Apple Silicon
@@ -85,6 +92,9 @@ collection stay in the installation directory. See [clean-room setup](docs/clean
for the exact boundaries and headless use, or [installation](docs/install.md) for other
harnesses and the plugin path.
+For Google models, see [Antigravity and Gemini setup](docs/google.md). Local coding
+agents use stdio directly; browser chat connections have different setup requirements.
+
## Revise an asset
Save finished work into a collection with `node kiln.mjs save workbench.kiln.js --name "Workbench"`.
diff --git a/assets/gallery/demo-unfolding-dragonfly.gif b/assets/gallery/demo-unfolding-dragonfly.gif
new file mode 100644
index 00000000..1a056a52
Binary files /dev/null and b/assets/gallery/demo-unfolding-dragonfly.gif differ
diff --git a/assets/gallery/gallery-grid-01.png b/assets/gallery/gallery-grid-01.png
new file mode 100644
index 00000000..24ba92e5
Binary files /dev/null and b/assets/gallery/gallery-grid-01.png differ
diff --git a/assets/gallery/gallery-grid-02.png b/assets/gallery/gallery-grid-02.png
new file mode 100644
index 00000000..3cc457af
Binary files /dev/null and b/assets/gallery/gallery-grid-02.png differ
diff --git a/assets/gallery/gallery-grid-03.png b/assets/gallery/gallery-grid-03.png
new file mode 100644
index 00000000..4ad02444
Binary files /dev/null and b/assets/gallery/gallery-grid-03.png differ
diff --git a/assets/gallery/mechanical-peacock.gif b/assets/gallery/mechanical-peacock.gif
new file mode 100644
index 00000000..8b4d1f09
Binary files /dev/null and b/assets/gallery/mechanical-peacock.gif differ
diff --git a/assets/gallery/solar-sail-courier.gif b/assets/gallery/solar-sail-courier.gif
new file mode 100644
index 00000000..ce752f14
Binary files /dev/null and b/assets/gallery/solar-sail-courier.gif differ
diff --git a/docs/clean-room.md b/docs/clean-room.md
index d6df3423..705dab24 100644
--- a/docs/clean-room.md
+++ b/docs/clean-room.md
@@ -18,6 +18,11 @@ the selected harness's MCP configuration, and `.kiln/workspace.json` identifying
installation and generated configuration. Add composition and batch skills with
`--skills compose,batch` at creation. Supporting files travel with each selected skill.
+OpenCode setup registers the project's existing `skills/` folder through
+`skills.paths` in `opencode.json`, so its native skill tool can discover the copies.
+The same files remain available for explicit reads; repair updates the registered
+path after relocation and preserves edited skills and supporting references.
+
CLI and MCP share `.kiln/programs`. Engine implementation and examples stay outside
the workspace. For a refinement task, supply only the intended `.kiln.js` source.
For creation, supply a brief with no starting asset. Follow the generated `START.md`
@@ -57,14 +62,50 @@ for `kiln_workspace/kiln_list_primitives` with `capabilities: true` and verify i
runtime and source store. The standalone `agy mcp list` view is not proof of which
project tools the conversation used.
+For an interactive Antigravity recording, complete first-run onboarding first.
+Open `/mcp` and wait for the project server's connected status before the asset
+prompt. The September 8 Hub print probe worked immediately, while the first TUI
+attempt lacked model-visible MCP tools. Restarting after onboarding and checking
+the native manager restored access without changing the generated configuration.
+The fresh corrected battleship creation and same-conversation roof-color revision
+then completed through native MCP, with saved lineage and validated exports.
+This is an assisted readiness retest; retain the failed first take separately.
+
Hermes: use `node hermes.mjs --ignore-rules`. The launcher sets a separate `HERMES_HOME`,
process cwd and terminal directory without copying credentials. Authenticate that
profile or provide credentials through the environment. Ask it explicitly to read
the workspace instructions and relevant skill. Use absolute paths in headless briefs.
Codex supports `exec --ignore-user-config --ephemeral`, per-run MCP overrides and
-`--cd`, while retaining authentication. OpenCode supports project MCP configuration
-and `--pure`; audit inherited instructions in its trace.
+`--cd`, while retaining authentication.
+
+For OpenCode, finish setup, change into the generated asset directory, then launch
+a fresh session as described in its `START.md`. Do not assume a session that created
+the workspace has loaded that workspace's MCP configuration. In our OpenCode 1.18.27
+test, the original setup session used CLI commands; a fresh session in `my-assets`
+loaded the native Kiln tools and completed a requested revision. Check actual tool
+calls before describing a run as native MCP. `--pure` disables external plugins;
+do not use it as a general isolation switch for a workflow that needs those plugins.
+Audit inherited instructions separately.
+
+For headless Codex evaluation, the project must be trusted for its generated
+`.codex/config.toml` to load. On Codex 0.153.4, pass a project trust table as a TOML
+**value** when supplying trust for one invocation:
+
+```sh
+codex exec --ignore-user-config --ephemeral --cd /absolute/my-assets \
+ -c 'projects={"/absolute/my-assets"={trust_level="trusted"}}' \
+ 'Read AGENTS.md and call kiln_list_primitives with capabilities true.'
+```
+
+Replace the absolute path in both places with the intended trusted workspace.
+This does not write global configuration. Do not encode the path as a quoted
+dotted override key such as `projects."/absolute/my-assets".trust_level`:
+that CLI version splits override keys on dots literally, retaining the quotes.
+Our isolated test then failed to load the project MCP server even though
+`codex mcp list` displayed it. The corrected table value loaded the generated
+configuration and completed a native tool call without MCP definition overrides.
+Verify actual native calls in the conversation trace before starting asset work.
Claude supports `--strict-mcp-config`, `--mcp-config`, and `--setting-sources project`.
Its `--bare` mode skips OAuth login and requires API-key authentication; do not use it
diff --git a/docs/google.md b/docs/google.md
new file mode 100644
index 00000000..bc6a7417
--- /dev/null
+++ b/docs/google.md
@@ -0,0 +1,117 @@
+# Kiln with Google agents
+
+Use Antigravity for a local Google workflow. It can launch Kiln's existing Node
+MCP server directly. You do not need a public tunnel or an OAuth server for Kiln.
+Sign in to Antigravity normally; your agent supplies the model.
+
+## Antigravity CLI
+
+Install and sign in using Google's [installation guide](https://antigravity.google/docs/cli/install/).
+Install Kiln using the [installation guide](install.md). For the current tool set
+from a checkout:
+
+```sh
+git clone https://github.com/matthew-kissinger/kiln
+cd kiln
+bun install --frozen-lockfile
+bun run build:runtime
+node scripts/create-workspace.mjs ../my-assets --harness agy
+cd ../my-assets
+node agy.mjs --model gemini-3.8-flash-high
+```
+
+Use the supported Bun 1.3.14 and Node 22.23.1 toolchain. A built package avoids the
+Bun/build steps: run `npm exec --offline -- kiln-init ../my-assets --harness agy`
+from its installation directory instead. Check [release compatibility](install.md#release-compatibility)
+before following saved-asset examples with an older package.
+
+Setup creates `.agents/mcp_config.json`, a local CLI launcher, `AGENTS.md`, and
+authoring/refinement/QA skills with their references. Start a new conversation in
+this workspace and accept normal project/tool trust prompts. Try:
+
+> Read AGENTS.md and skills/kiln-author-asset/SKILL.md. Use the kiln_workspace MCP
+> server. Check its capabilities, make a blue one-metre cube on the ground,
+> render it, and review the returned image. Report any connection error.
+
+Then describe the asset you want. Ask for a rendered review and save a revision
+after accepting the result. Run `node kiln.mjs view` to open the local asset
+library. Keep the source alongside the GLB for later edits.
+
+Run `agy models` to check your account's available models. Do not assume a generic
+Flash alias pins 3.8. Google documents [model selection](https://antigravity.google/docs/models/)
+and [local MCP configuration](https://antigravity.google/docs/mcp).
+
+## Antigravity desktop or IDE
+
+Create the same workspace with `--harness agy`, then open that folder as a project
+in Antigravity. The generated MCP configuration uses Google's documented local
+`mcpServers` structure. In the IDE, open **MCP Servers → Manage MCP Servers** to
+check the connection. Antigravity 2.0 exposes installed MCP servers under
+**Settings → Customizations**. Refresh if needed and start a fresh conversation.
+
+Select the desired Gemini model beneath the prompt box. Ask the agent to read
+the workspace's `AGENTS.md` and skill files, then run the connection check above.
+The copied skills are ordinary readable project files; the generated setup does
+not promise native slash-command registration. Native Antigravity plugins are
+an optional packaging route, documented by [Google](https://antigravity.google/docs/plugins/).
+
+These desktop steps follow current official documentation. The latest direct Kiln
+probe verified the CLI, not an Antigravity desktop recording. Confirm actual tool
+calls, image receipt and local viewer behavior in your desktop version.
+
+## Gemini Spark in the browser
+
+Spark uses a separate remote connection. Google's setup starts at **Connected Apps
+→ Custom apps**, where you enter an MCP server URL and complete account linking.
+Local stdio commands are not a documented browser connection method.
+[Google's custom-app instructions](https://support.google.com/gemini/answer/17209137).
+
+Kiln's private compatibility experiment reached registration and its OAuth consent
+page, but Chrome blocked the final submission. Token exchange, tool execution,
+inline 3D viewing and downloads in Spark remain unverified. A selected Flash model
+in ordinary Gemini Chat does not establish Spark's backend version.
+
+Do not use the experiment's handwritten OAuth server and rotating tunnel setup
+as installation instructions. A maintained remote deployment needs authentication,
+isolated asset storage and a reachable viewer/download route. A tunnel supplies
+connectivity; it does not supply those application features.
+
+## Troubleshooting and verification
+
+- **No tools:** open the generated project, accept trust, restart the conversation,
+ and check `kiln_workspace`. A globally configured `kiln` may use another install.
+- **Skill absent:** ask the agent to read the project skill's `SKILL.md`; keep its
+ referenced files adjacent. Native plugin registration is a separate host feature.
+- **No inline 3D card:** MCP image feedback and MCP Apps are separate capabilities.
+ Use `node kiln.mjs view` for the local interactive viewer.
+- **Gemini CLI rejected:** our September 8 probe of Gemini CLI 0.59.0 with an
+ individual account returned `UNSUPPORTED_CLIENT` and directed migration to
+ Antigravity. This does not establish that every Gemini CLI authentication method
+ is unavailable. Follow Google's [migration guide](https://antigravity.google/docs/cli/gcli-migration/).
+
+Direct probe, September 8, 2026: Antigravity CLI 1.1.27 selected
+`gemini-3.8-flash-high`, read project guidance, called `kiln_workspace` capabilities
+and render tools, and received a six-view PNG. A separate Hub probe using fresh public checkout c85a76b5b71c8f985c1ae1f762c44c5cb2601a61 also completed native capabilities/render and image inspection after normal Google sign-in. The earlier Windows checkout includes
+unreleased fixes. CPU feedback establishes geometry/base color, not PBR material
+fidelity. This was a connection check, not a generation-speed benchmark.
+
+### First interactive launch
+
+Finish Antigravity's initial onboarding, then start a fresh CLI session. Before
+submitting an asset prompt, open `/mcp` and wait until `kiln_workspace` is connected
+and its tools are listed. A September 8 Hub test succeeded in print mode but its
+first interactive session did not expose the MCP tools to the agent. Restarting
+after onboarding and checking the normal MCP manager restored native tool access
+without changing Kiln's configuration. The exact initialization cause is not yet
+proven; this is a tested readiness check, not a claim that every installation
+requires a restart. Keep setup checks outside a recorded creation prompt.
+
+The corrected Hub session then created a battleship from a short user prompt,
+reviewed Kiln's returned images, saved source and GLB, and resumed the same
+conversation to paint the three turret roofs dark red. The child revision retained
+its parent; both GLBs passed validation, and the exported bundle matched the saved
+source and GLB. The geometry binary was unchanged by the material edit. Native
+MCP calls and the actual local viewer were recorded. This verifies Antigravity
+CLI 1.1.27 with `gemini-3.8-flash-high` and public checkout `c85a76b5`, not desktop
+operation or the older eight-tool release package. No Antigravity desktop install
+was found in the Hub's checked package and launcher locations.
diff --git a/docs/install.md b/docs/install.md
index 37e691ea..14171e65 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -12,6 +12,34 @@ Windows, Linux, and hosted Apple Silicon/Intel Mac package checks pass; see the
Mac installations are still welcome. CPU package setup and optional GPU support
are separate checks.
+## Choose the simplest connection
+
+| Where you want to work | Setup path |
+| --- | --- |
+| Codex, Claude Code or OpenCode | Install Kiln, generate a project workspace, open your agent there. Local MCP needs no tunnel. |
+| Google Antigravity CLI or desktop | Generate an `agy` workspace. See the [Google setup guide](google.md) for verified CLI steps and desktop checks. |
+| ChatGPT in a browser | Follow the [private MCP tunnel guide](chatgpt.md). This is a separate developer setup. |
+| Gemini Spark in a browser | Remote MCP is required; Kiln's end-to-end Spark integration remains unverified. See [current status](google.md#gemini-spark-in-the-browser). |
+
+For agent-assisted installation, give your agent the repository URL and ask:
+
+> Set up Kiln in a new asset workspace for my current coding agent. Follow
+> docs/install.md and the generated START.md. Keep configuration and skills
+> project-local. Verify tool discovery and a small render before creating my asset.
+> Report missing login or setup failures without substituting another installation.
+
+## Release compatibility
+
+The downloadable `oss-2026-09-05` package (`kiln-engine-0.6.0.tgz`) exposes eight
+MCP tools: discovery, validation, rendering, animation/interior views, inspection,
+editing and source access. A fresh September 8 install verified discovery and a
+CPU-rendered PNG. That package predates `kiln_save`, `kiln_assets`, `kiln_export`,
+`kiln_present` and `kiln_import`; saved-asset examples require the newer checkout.
+
+Use the checkout installation below for that tool set until an updated package is
+released. A successful local build or unreleased fix does not update the GitHub
+release. Do not substitute an unverified npm registry package.
+
## Start on a Mac with a local package
Install Node.js from the [official download page](https://nodejs.org/en/download).
@@ -135,6 +163,11 @@ absolute task-file paths. See [clean-room setup](clean-room.md) for evaluation c
## Verify the connection
+OpenCode workspaces register their local `skills/` directory using the supported
+`skills.paths` configuration. Run `opencode debug skill` from the workspace to
+inspect native discovery without a model request. Author, refine and QA entries
+should point into that workspace. See the [OpenCode configuration schema](https://opencode.ai/config.json).
+
Ask the agent to read `AGENTS.md`, discover geometry helpers, render a small draft,
read its source, edit it by `programRef`, and export the accepted revision. Check the
actual tools and files, not only the agent's final message. CPU rendering needs no
diff --git a/examples/demo-unfolding-dragonfly.kiln.js b/examples/demo-unfolding-dragonfly.kiln.js
new file mode 100644
index 00000000..85edd0e5
--- /dev/null
+++ b/examples/demo-unfolding-dragonfly.kiln.js
@@ -0,0 +1,676 @@
+const meta = {
+ name: 'Mechanical Dragonfly with Unfolding Copper Wings',
+ category: 'character',
+ role: 'prop'
+};
+
+function build() {
+ const root = createRoot('MechanicalDragonfly');
+
+ // --- Materials ---
+ const matCopper = gameMaterial(0xcd683d, { metalness: 0.88, roughness: 0.28 });
+ const matBrightCopper = gameMaterial(0xdf7a4a, { metalness: 0.92, roughness: 0.20 });
+ const matBrass = gameMaterial(0xd4af37, { metalness: 0.85, roughness: 0.30 });
+ const matGunmetal = gameMaterial(0x282a30, { metalness: 0.80, roughness: 0.42 });
+ const matSteel = gameMaterial(0x9ca3af, { metalness: 0.92, roughness: 0.18 });
+ const matObsidianEye = gameMaterial(0x161e26, { metalness: 0.82, roughness: 0.12 });
+ const matGlowAmber = gameMaterial(0xd9822b, { metalness: 0.35, roughness: 0.25, emissive: 0x8a4510, emissiveIntensity: 0.8 });
+ const matPowerCore = gameMaterial(0x38bdf8, { metalness: 0.20, roughness: 0.20, emissive: 0x0284c7, emissiveIntensity: 1.5 });
+ const matCopperFoil = gameMaterial(0xc25e36, { metalness: 0.88, roughness: 0.32 });
+ const matCopperVane = gameMaterial(0xd86f3e, { metalness: 0.92, roughness: 0.22 });
+
+ // --- 1. Head & Cephalon ---
+ const headPos = [0.22, 0.175, 0];
+ const headGroup = createPivot('Head_Mount', headPos, root);
+
+ // Skull casing
+ createPart('Head_Casing', capsuleGeo(0.028, 0.032, 12), matGunmetal, {
+ rotation: [0, 0, 90],
+ parent: headGroup
+ });
+ // Frontal brow plate & cowl
+ createPart('Head_Brow', boxGeo(0.032, 0.016, 0.048), matBrass, {
+ position: [0.018, 0.008, 0],
+ parent: headGroup
+ });
+ createPart('Head_FacePlate', taperConeGeo(0.024, 0.012, 0.028, 'x', 8), matCopper, {
+ position: [0.028, -0.008, 0],
+ parent: headGroup
+ });
+
+ // Large Compound Eyes (Left & Right)
+ for (const s of [1, -1]) {
+ const eyeZ = s * 0.034;
+ // Main faceted compound eye hemisphere
+ createPart(`Eye_${s > 0 ? 'R' : 'L'}`, sphereGeo(0.026, 16, 12), matObsidianEye, {
+ position: [0.008, 0.008, eyeZ],
+ scale: [1.1, 1.0, 0.85],
+ parent: headGroup
+ });
+ // Brass ocular bezel / retaining collar
+ createPart(`EyeBezel_${s > 0 ? 'R' : 'L'}`, torusGeo(0.026, 0.0032, 8, 20), matBrass, {
+ position: [0.008, 0.008, eyeZ * 0.88],
+ rotation: [0, s * 25, 0],
+ parent: headGroup
+ });
+ // Ocular gear teeth ring
+ const eyeGear = gearGeo({ teeth: 18, rootRadius: 0.025, tipRadius: 0.029, boreRadius: 0.022, height: 0.004 });
+ createPart(`EyeGear_${s > 0 ? 'R' : 'L'}`, eyeGear, matBrightCopper, {
+ position: [0.008, 0.008, eyeZ * 0.82],
+ rotation: [90, 0, s * 25],
+ parent: headGroup
+ });
+
+ // Articulated Antenna
+ const antRoot = [0.030, 0.022, s * 0.014];
+ beamBetween(`Antenna_Base_${s > 0 ? 'R' : 'L'}`, antRoot, [antRoot[0] + 0.025, antRoot[1] + 0.020, s * 0.024], 0.0018, matBrass, { parent: headGroup });
+ beamBetween(`Antenna_Tip_${s > 0 ? 'R' : 'L'}`, [antRoot[0] + 0.025, antRoot[1] + 0.020, s * 0.024], [antRoot[0] + 0.048, antRoot[1] + 0.028, s * 0.030], 0.0012, matCopper, { parent: headGroup });
+ createPart(`Antenna_Orb_${s > 0 ? 'R' : 'L'}`, sphereGeo(0.0035, 8, 6), matGlowAmber, {
+ position: [antRoot[0] + 0.048, antRoot[1] + 0.028, s * 0.030],
+ parent: headGroup
+ });
+
+ // Mandibles / Mouthparts
+ beamBetween(`Mandible_${s > 0 ? 'R' : 'L'}`, [0.030, -0.020, s * 0.012], [0.044, -0.030, s * 0.004], 0.0025, matSteel, { parent: headGroup });
+ createPart(`Mandible_Tip_${s > 0 ? 'R' : 'L'}`, coneGeo(0.003, 0.010, 6), matBrass, {
+ position: [0.044, -0.030, s * 0.004],
+ rotation: [0, 0, -60],
+ parent: headGroup
+ });
+ }
+
+ // 3 Dorsal Ocelli (sensory eyes)
+ createPart('Ocellus_Center', sphereGeo(0.0045, 8, 6), matGlowAmber, {
+ position: [0.016, 0.030, 0],
+ parent: headGroup
+ });
+ createPart('Ocellus_R', sphereGeo(0.0035, 8, 6), matGlowAmber, {
+ position: [0.010, 0.028, 0.010],
+ parent: headGroup
+ });
+ createPart('Ocellus_L', sphereGeo(0.0035, 8, 6), matGlowAmber, {
+ position: [0.010, 0.028, -0.010],
+ parent: headGroup
+ });
+
+ // Neck Gimbal Collar
+ createPart('Neck_Ring', torusGeo(0.022, 0.004, 8, 16), matBrass, {
+ position: [0.188, 0.175, 0],
+ rotation: [0, 90, 0],
+ parent: root
+ });
+ createPart('Neck_Joint', sphereGeo(0.018, 10, 8), matSteel, {
+ position: [0.188, 0.175, 0],
+ parent: root
+ });
+
+ // --- 2. Thorax (Chassis & Clockwork Engine Room) ---
+ const thoraxCenter = [0.05, 0.170, 0];
+
+ // Main Dorsal Carapace Shield
+ createPart('Thorax_DorsalCarapace', capsuleGeo(0.040, 0.14, 12), matGunmetal, {
+ position: thoraxCenter,
+ rotation: [0, 0, 90],
+ scale: [1.0, 0.95, 1.1],
+ parent: root
+ });
+ // Copper Spine Crest (Split with open clockwork gearbox bay)
+ createPart('Thorax_SpineCrest_Front', boxGeo(0.045, 0.010, 0.012), matBrightCopper, {
+ position: [thoraxCenter[0] + 0.055, thoraxCenter[1] + 0.042, 0],
+ parent: root
+ });
+ createPart('Thorax_SpineCrest_Aft', boxGeo(0.040, 0.010, 0.012), matBrightCopper, {
+ position: [thoraxCenter[0] - 0.055, thoraxCenter[1] + 0.042, 0],
+ parent: root
+ });
+ // Gearbox bay filigree rim / brass housing
+ createPart('Gearbox_Rim', boxGeo(0.065, 0.006, 0.030), matBrass, {
+ position: [thoraxCenter[0] + 0.002, thoraxCenter[1] + 0.040, 0],
+ parent: root
+ });
+ // Arched brass protective rib cage over exposed gears
+ for (let g = -1; g <= 1; g++) {
+ createPart(`Gearbox_Arch_${g}`, torusGeo(0.018, 0.0018, 6, 16), matBrass, {
+ position: [thoraxCenter[0] + 0.002 + g * 0.020, thoraxCenter[1] + 0.040, 0],
+ rotation: [0, 90, 0],
+ parent: root
+ });
+ }
+
+ // Animated Clockwork Gears inside Thorax (Prominently exposed in central bay)
+ // Main Drive Gear (brass)
+ const gearPivotMain = createPivot('Gear_Main', [thoraxCenter[0] + 0.018, thoraxCenter[1] + 0.024, 0], root);
+ const mainGearMesh = gearGeo({ teeth: 16, rootRadius: 0.026, tipRadius: 0.032, boreRadius: 0.008, height: 0.010 });
+ createPart('Gear_Main_Mesh', mainGearMesh, matBrass, {
+ rotation: [90, 0, 0],
+ parent: gearPivotMain
+ });
+
+ // Secondary Reduction Gear (copper, meshing with main gear)
+ const gearPivotSec = createPivot('Gear_Sec', [thoraxCenter[0] - 0.020, thoraxCenter[1] + 0.028, 0], root);
+ const secGearMesh = gearGeo({ teeth: 10, rootRadius: 0.014, tipRadius: 0.019, boreRadius: 0.005, height: 0.010 });
+ createPart('Gear_Sec_Mesh', secGearMesh, matCopper, {
+ rotation: [90, 0, 0],
+ parent: gearPivotSec
+ });
+
+ // Transverse brass drive shafts linking gearbox to wing saddles
+ beamBetween('Gear_Shaft_Fore',
+ [thoraxCenter[0] + 0.018, thoraxCenter[1] + 0.024, -0.036],
+ [thoraxCenter[0] + 0.018, thoraxCenter[1] + 0.024, 0.036],
+ 0.003, matSteel, { parent: root });
+ beamBetween('Gear_Shaft_Aft',
+ [thoraxCenter[0] - 0.020, thoraxCenter[1] + 0.028, -0.034],
+ [thoraxCenter[0] - 0.020, thoraxCenter[1] + 0.028, 0.034],
+ 0.0025, matSteel, { parent: root });
+
+ // Side Pressure Gauge (Port side)
+ createPart('PressureGauge_Body', cylinderGeo(0.012, 0.012, 0.006, 12), matBrass, {
+ position: [thoraxCenter[0] + 0.010, thoraxCenter[1] + 0.015, 0.046],
+ rotation: [90, 0, 0],
+ parent: root
+ });
+ createPart('PressureGauge_Face', cylinderGeo(0.009, 0.009, 0.007, 12), matGlowAmber, {
+ position: [thoraxCenter[0] + 0.010, thoraxCenter[1] + 0.015, 0.047],
+ rotation: [90, 0, 0],
+ parent: root
+ });
+ // Starboard Escapement Wheel
+ createPart('Escapement_Body', cylinderGeo(0.010, 0.010, 0.006, 10), matBrass, {
+ position: [thoraxCenter[0] - 0.015, thoraxCenter[1] + 0.015, -0.046],
+ rotation: [90, 0, 0],
+ parent: root
+ });
+
+ // Twin Steam Exhaust Funnels on Dorsal Carapace
+ for (const s of [1, -1]) {
+ createPart(`Steam_Funnel_${s > 0 ? 'R' : 'L'}`, cylinderGeo(0.0045, 0.003, 0.022, 10), matBrass, {
+ position: [thoraxCenter[0] - 0.045, thoraxCenter[1] + 0.045, s * 0.020],
+ rotation: [s * 15, 0, -25],
+ parent: root
+ });
+ createPart(`Steam_Rim_${s > 0 ? 'R' : 'L'}`, torusGeo(0.005, 0.0012, 6, 12), matBrightCopper, {
+ position: [thoraxCenter[0] - 0.050, thoraxCenter[1] + 0.054, s * 0.024],
+ rotation: [s * 15, 0, -25],
+ parent: root
+ });
+ }
+
+ // Wing Saddle Mounts on Dorsal Carapace
+ for (const s of [1, -1]) {
+ // Forewing Mount Block
+ createPart(`Forewing_Saddle_${s > 0 ? 'R' : 'L'}`, boxGeo(0.022, 0.014, 0.016), matBrass, {
+ position: [0.08, 0.210, s * 0.038],
+ parent: root
+ });
+ // Hindwing Mount Block
+ createPart(`Hindwing_Saddle_${s > 0 ? 'R' : 'L'}`, boxGeo(0.022, 0.014, 0.016), matBrass, {
+ position: [-0.01, 0.205, s * 0.036],
+ parent: root
+ });
+ }
+
+ // --- 3. 10-Segmented Abdomen & Caudal Claspers ---
+ const abdomenStart = -0.05;
+ const numSegments = 10;
+ const segLength = 0.044;
+ let curX = abdomenStart;
+
+ for (let seg = 1; seg <= numSegments; seg++) {
+ const t = (seg - 1) / (numSegments - 1);
+ const rFront = 0.024 * (1 - 0.65 * t);
+ const rBack = 0.024 * (1 - 0.65 * (t + 1 / numSegments));
+ const centerX = curX - segLength * 0.5;
+
+ // Segment Body Shell
+ createPart(`Abdomen_S${seg}_Shell`, taperConeGeo(rBack, rFront, segLength, 'x', 8), matGunmetal, {
+ position: [centerX, 0.165 - t * 0.025, 0],
+ parent: root
+ });
+
+ // Brass Joint Ring between segments
+ createPart(`Abdomen_S${seg}_Ring`, torusGeo(rFront * 1.05, 0.0022, 6, 16), matBrass, {
+ position: [curX, 0.165 - t * 0.025, 0],
+ rotation: [0, 90, 0],
+ parent: root
+ });
+
+ // Longitudinal Dorsal Spine Conduit
+ beamBetween(`Abdomen_S${seg}_Spine`,
+ [curX, 0.165 - t * 0.025 + rFront * 1.05, 0],
+ [curX - segLength, 0.165 - (t + 1 / numSegments) * 0.025 + rBack * 1.05, 0],
+ 0.0020, matBrightCopper, { parent: root });
+
+ // Lateral copper rivet studs
+ for (const s of [1, -1]) {
+ createPart(`Abdomen_S${seg}_Stud_${s > 0 ? 'R' : 'L'}`, sphereGeo(0.0022, 6, 4), matCopper, {
+ position: [centerX, 0.165 - t * 0.025, s * (rFront + rBack) * 0.5],
+ parent: root
+ });
+ }
+
+ curX -= segLength;
+ }
+
+ // S10 Tip & Tail Claspers (Cerci)
+ const tipX = curX;
+ const tipY = 0.140;
+ createPart('Caudal_Base', cylinderGeo(0.008, 0.006, 0.016, 8), matBrass, {
+ position: [tipX, tipY, 0],
+ rotation: [0, 0, 90],
+ parent: root
+ });
+ // Upper dual forceps / claspers
+ for (const s of [1, -1]) {
+ beamBetween(`Clasper_Upper_${s > 0 ? 'R' : 'L'}`,
+ [tipX - 0.008, tipY + 0.003, s * 0.004],
+ [tipX - 0.038, tipY + 0.012, s * 0.012],
+ 0.0016, matSteel, { parent: root });
+ beamBetween(`Clasper_Tip_${s > 0 ? 'R' : 'L'}`,
+ [tipX - 0.038, tipY + 0.012, s * 0.012],
+ [tipX - 0.052, tipY + 0.008, s * 0.002],
+ 0.0012, matBrightCopper, { parent: root });
+ }
+ // Lower ventral clasper prong
+ beamBetween('Clasper_Lower',
+ [tipX - 0.008, tipY - 0.004, 0],
+ [tipX - 0.040, tipY - 0.010, 0],
+ 0.0016, matSteel, { parent: root });
+
+ // --- 4. 6 Articulated Mechanical Legs (Ground Contact at Y = 0) ---
+ // Legs: Forelegs, Midlegs, Hindlegs
+ const legDefs = [
+ { name: 'Foreleg', rootX: 0.12, rootY: 0.13, rootZ: 0.042, knee: [0.17, 0.19, 0.095], ankle: [0.16, 0.05, 0.120], foot: [0.17, 0.0, 0.135] },
+ { name: 'Midleg', rootX: 0.04, rootY: 0.12, rootZ: 0.045, knee: [0.04, 0.18, 0.125], ankle: [0.02, 0.05, 0.150], foot: [0.02, 0.0, 0.165] },
+ { name: 'Hindleg', rootX: -0.04, rootY: 0.12, rootZ: 0.045, knee: [-0.08, 0.19, 0.135], ankle: [-0.13, 0.06, 0.160], foot: [-0.15, 0.0, 0.175] }
+ ];
+
+ for (const def of legDefs) {
+ for (const s of [1, -1]) {
+ const pRoot = [def.rootX, def.rootY, s * def.rootZ];
+ const pKnee = [def.knee[0], def.knee[1], s * def.knee[2]];
+ const pAnkle = [def.ankle[0], def.ankle[1], s * def.ankle[2]];
+ const pFoot = [def.foot[0], def.foot[1], s * def.foot[2]];
+ const prefix = `${def.name}_${s > 0 ? 'R' : 'L'}`;
+
+ // Coxa mounting ball & socket
+ createPart(`${prefix}_Coxa`, sphereGeo(0.008, 8, 8), matBrass, {
+ position: pRoot,
+ parent: root
+ });
+ // Femur strut (Coxa to Knee)
+ beamBetween(`${prefix}_Femur`, pRoot, pKnee, 0.0035, matGunmetal, { parent: root });
+ // Copper hydraulic line along femur
+ beamBetween(`${prefix}_FemurTube`,
+ [pRoot[0], pRoot[1] + 0.004, pRoot[2]],
+ [pKnee[0], pKnee[1] + 0.004, pKnee[2]],
+ 0.0015, matCopper, { parent: root });
+
+ // Knee hinge disc
+ createPart(`${prefix}_KneeDisc`, cylinderGeo(0.007, 0.007, 0.006, 10), matBrass, {
+ position: pKnee,
+ rotation: [0, 0, 90],
+ parent: root
+ });
+
+ // Tibia strut (Knee to Ankle) with classic dragonfly spines
+ beamBetween(`${prefix}_Tibia`, pKnee, pAnkle, 0.0028, matSteel, { parent: root });
+
+ // 3 Tibial spines
+ for (let sp = 1; sp <= 3; sp++) {
+ const u = sp / 4;
+ const spBase = [
+ pKnee[0] + u * (pAnkle[0] - pKnee[0]),
+ pKnee[1] + u * (pAnkle[1] - pKnee[1]),
+ pKnee[2] + u * (pAnkle[2] - pKnee[2])
+ ];
+ const spTip = [spBase[0] + 0.003, spBase[1] - 0.006, spBase[2] + s * 0.004];
+ beamBetween(`${prefix}_Spine_${sp}`, spBase, spTip, 0.0010, matBrightCopper, { parent: root });
+ }
+
+ // Tarsal Joint / Ankle knuckle
+ createPart(`${prefix}_Ankle`, sphereGeo(0.0045, 8, 6), matBrass, {
+ position: pAnkle,
+ parent: root
+ });
+
+ // Tarsus / Claws reaching firmly down to Y = 0
+ beamBetween(`${prefix}_Tarsus`, pAnkle, pFoot, 0.0022, matSteel, { parent: root });
+ // Sharp curved gripping claw touching Y = 0
+ createPart(`${prefix}_ClawOuter`, coneGeo(0.0028, 0.010, 6), matBrightCopper, {
+ position: [pFoot[0], pFoot[1] + 0.003, pFoot[2]],
+ rotation: [s * 20, 0, -45],
+ parent: root
+ });
+ createPart(`${prefix}_ClawInner`, coneGeo(0.0028, 0.010, 6), matBrightCopper, {
+ position: [pFoot[0] - 0.004, pFoot[1] + 0.003, pFoot[2] - s * 0.003],
+ rotation: [s * 10, 0, -50],
+ parent: root
+ });
+ }
+ }
+
+ // --- 5. Unfolding Copper Wings (Forewings & Hindwings) ---
+ // Helper to build an intricate folding wing
+ function createFoldingWing(wingId, isHind, side, mountPos) {
+ const s = side; // +1 = Right (+Z), -1 = Left (-Z)
+ const sideKey = s > 0 ? 'R' : 'L';
+ const tag = `${wingId}_${sideKey}`;
+
+ // Root Pivot: receives rotation tracks in animation
+ const rootPivot = createPivot(`${tag}_Root`, mountPos, root);
+
+ // Root swivel clevis & actuator piston
+ createPart(`${tag}_Clevis`, boxGeo(0.014, 0.012, 0.012), matBrass, {
+ position: [0, 0, 0],
+ parent: rootPivot
+ });
+ // Miniature hydraulic pushrod pylon
+ beamBetween(`${tag}_Actuator`, [-0.010, -0.015, 0], [0, 0, s * 0.015], 0.0025, matSteel, { parent: rootPivot });
+
+ // Inner Wing Dimensions
+ const innerSpan = isHind ? 0.14 : 0.16;
+ const baseChord = isHind ? 0.070 : 0.052;
+ const midChord = isHind ? 0.065 : 0.048;
+
+ // --- Inner Wing Assembly (attached to rootPivot) ---
+ // Leading tubular copper spar
+ beamBetween(`${tag}_Inner_LeadSpar`, [0, 0, 0], [0, 0, s * innerSpan], 0.0035, matBrightCopper, { parent: rootPivot });
+ // Subcostal spar
+ beamBetween(`${tag}_Inner_SubSpar`, [-0.012, -0.001, s * 0.015], [-0.010, -0.001, s * innerSpan], 0.0022, matCopper, { parent: rootPivot });
+
+ // Inner venation ribs & braces
+ const numInnerRibs = 5;
+ for (let r = 1; r <= numInnerRibs; r++) {
+ const u = r / numInnerRibs;
+ const zPos = s * innerSpan * u;
+ const chord = baseChord * (1 - u) + midChord * u;
+ // Cross vein from leading spar back to trailing edge
+ beamBetween(`${tag}_Inner_Rib_${r}`, [0, 0, zPos], [-chord, -0.001, zPos], 0.0014, matCopper, { parent: rootPivot });
+ // Diagonal cross-truss
+ if (r > 1) {
+ const prevZ = s * innerSpan * ((r - 1) / numInnerRibs);
+ beamBetween(`${tag}_Inner_Truss_${r}`, [-0.010, -0.001, prevZ], [-chord * 0.7, -0.001, zPos], 0.0010, matBrass, { parent: rootPivot });
+ }
+ }
+ // Trailing edge copper framing wire
+ beamBetween(`${tag}_Inner_TrailWire`, [-baseChord, -0.001, s * 0.010], [-midChord, -0.001, s * innerSpan], 0.0016, matBrightCopper, { parent: rootPivot });
+
+ // Inner Wing Translucent Copper Membrane (meshGeo)
+ // Triangle strip from leading edge to trailing edge
+ const innerPositions = [];
+ const innerIndices = [];
+ for (let r = 0; r <= numInnerRibs; r++) {
+ const u = r / numInnerRibs;
+ const zPos = s * innerSpan * u;
+ const chord = baseChord * (1 - u) + midChord * u;
+ innerPositions.push(0, 0, zPos); // front vertex
+ innerPositions.push(-chord, 0, zPos); // back vertex
+ }
+ for (let r = 0; r < numInnerRibs; r++) {
+ const i0 = r * 2;
+ const i1 = r * 2 + 1;
+ const i2 = (r + 1) * 2;
+ const i3 = (r + 1) * 2 + 1;
+ // Two triangles per quad cell (both clockwise and CCW for double-sided visibility)
+ innerIndices.push(i0, i1, i2, i2, i1, i3);
+ innerIndices.push(i2, i1, i0, i3, i1, i2);
+ }
+ const innerMembraneGeo = meshGeo({ positions: innerPositions, indices: innerIndices });
+ createPart(`${tag}_Inner_Membrane`, innerMembraneGeo, matCopperFoil, {
+ position: [0, -0.0005, 0],
+ parent: rootPivot
+ });
+
+ // Elbow Hinge Joint (Nodus / Folding Elbow Mechanism)
+ const elbowPos = [0, 0, s * innerSpan];
+ createPart(`${tag}_ElbowKnuckle`, cylinderGeo(0.006, 0.006, 0.008, 12), matBrass, {
+ position: elbowPos,
+ rotation: [90, 0, 0],
+ parent: rootPivot
+ });
+ // Miniature spur gear linking inner & outer wing
+ const elbowGear = gearGeo({ teeth: 12, rootRadius: 0.006, tipRadius: 0.0085, boreRadius: 0.0025, height: 0.004 });
+ createPart(`${tag}_ElbowGear`, elbowGear, matBrightCopper, {
+ position: [elbowPos[0], elbowPos[1] + 0.003, elbowPos[2]],
+ rotation: [0, 0, 90],
+ parent: rootPivot
+ });
+
+ // --- Mid Pivot: outer wing unfolds from here! ---
+ const midPivot = createPivot(`${tag}_Mid`, elbowPos, rootPivot);
+
+ // Outer Wing Dimensions
+ const outerSpan = isHind ? 0.16 : 0.18;
+ const tipChord = 0.015;
+
+ // Outer leading copper spar
+ beamBetween(`${tag}_Outer_LeadSpar`, [0, 0, 0], [-0.006, 0, s * outerSpan], 0.0030, matBrightCopper, { parent: midPivot });
+ // Outer subcostal spar
+ beamBetween(`${tag}_Outer_SubSpar`, [-0.010, -0.001, 0], [-0.010, -0.001, s * outerSpan * 0.75], 0.0018, matCopper, { parent: midPivot });
+
+ // Outer venation ribs
+ const numOuterRibs = 6;
+ for (let r = 1; r <= numOuterRibs; r++) {
+ const u = r / numOuterRibs;
+ const zPos = s * outerSpan * u;
+ const chord = midChord * (1 - u) + tipChord * u;
+ const frontX = -0.006 * u;
+ // Cross rib
+ beamBetween(`${tag}_Outer_Rib_${r}`, [frontX, 0, zPos], [frontX - chord, -0.001, zPos], 0.0012, matCopper, { parent: midPivot });
+ // Venation diagonals
+ if (r > 1) {
+ const prevZ = s * outerSpan * ((r - 1) / numOuterRibs);
+ const prevFrontX = -0.006 * ((r - 1) / numOuterRibs);
+ beamBetween(`${tag}_Outer_Truss_${r}`, [prevFrontX - 0.008, -0.001, prevZ], [frontX - chord * 0.6, -0.001, zPos], 0.0009, matBrass, { parent: midPivot });
+ }
+ }
+ // Trailing edge wire for outer wing
+ beamBetween(`${tag}_Outer_TrailWire`, [-midChord, -0.001, 0], [-0.006 - tipChord, -0.001, s * outerSpan], 0.0015, matBrightCopper, { parent: midPivot });
+
+ // Pterostigma (Aerodynamic counterweight plate near wing tip)
+ const pteroZ = s * outerSpan * 0.82;
+ createPart(`${tag}_Pterostigma`, boxGeo(0.008, 0.0025, 0.024), matBrass, {
+ position: [-0.008, 0.001, pteroZ],
+ parent: midPivot
+ });
+ createPart(`${tag}_Pterostigma_Trim`, boxGeo(0.005, 0.0035, 0.018), matBrightCopper, {
+ position: [-0.008, 0.001, pteroZ],
+ parent: midPivot
+ });
+
+ // Outer Wing Translucent Copper Membrane (meshGeo)
+ const outerPositions = [];
+ const outerIndices = [];
+ for (let r = 0; r <= numOuterRibs; r++) {
+ const u = r / numOuterRibs;
+ const zPos = s * outerSpan * u;
+ const chord = midChord * (1 - u) + tipChord * u;
+ const frontX = -0.006 * u;
+ outerPositions.push(frontX, 0, zPos); // front vertex
+ outerPositions.push(frontX - chord, 0, zPos); // back vertex
+ }
+ for (let r = 0; r < numOuterRibs; r++) {
+ const i0 = r * 2;
+ const i1 = r * 2 + 1;
+ const i2 = (r + 1) * 2;
+ const i3 = (r + 1) * 2 + 1;
+ outerIndices.push(i0, i1, i2, i2, i1, i3);
+ outerIndices.push(i2, i1, i0, i3, i1, i2);
+ }
+ const outerMembraneGeo = meshGeo({ positions: outerPositions, indices: outerIndices });
+ createPart(`${tag}_Outer_Membrane`, outerMembraneGeo, matCopperFoil, {
+ position: [0, -0.0005, 0],
+ parent: midPivot
+ });
+
+ // Wing Tip Filigree Finial
+ createPart(`${tag}_TipFinial`, sphereGeo(0.0035, 8, 6), matBrightCopper, {
+ position: [-0.006, 0, s * outerSpan],
+ parent: midPivot
+ });
+
+ // --- Trailing Edge Deployable Copper Fan Vane (Flap) ---
+ // Pivots to fan out the rear chord when unfolding
+ const flapPivot = createPivot(`${tag}_Flap`, [-baseChord * 0.45, 0, s * 0.02], rootPivot);
+ const flapWidth = isHind ? 0.030 : 0.020;
+ const flapLength = innerSpan * 0.72;
+ // Flat, thin, filigree copper fan blade
+ const flapPositions = [
+ 0, 0, 0,
+ -flapWidth, 0, s * flapLength * 0.35,
+ -flapWidth * 0.8, 0, s * flapLength,
+ 0, 0, s * flapLength
+ ];
+ const flapIndices = [
+ 0, 1, 2, 0, 2, 3,
+ 2, 1, 0, 3, 2, 0
+ ];
+ const flapGeo = meshGeo({ positions: flapPositions, indices: flapIndices });
+ createPart(`${tag}_FlapVane`, flapGeo, matCopperVane, {
+ position: [0, -0.0008, 0],
+ parent: flapPivot
+ });
+ beamBetween(`${tag}_FlapRib1`, [0, 0, 0], [-flapWidth, -0.0008, s * flapLength * 0.35], 0.0012, matBrightCopper, { parent: flapPivot });
+ beamBetween(`${tag}_FlapRib2`, [0, 0, 0], [-flapWidth * 0.8, -0.0008, s * flapLength], 0.0012, matBrightCopper, { parent: flapPivot });
+ }
+
+ // Instantiate the 4 Wings (Forewings and Hindwings, Right and Left)
+ createFoldingWing('WingF', false, 1, [0.08, 0.220, 0.038]); // Forewing Right
+ createFoldingWing('WingF', false, -1, [0.08, 0.220, -0.038]); // Forewing Left
+ createFoldingWing('WingH', true, 1, [-0.01, 0.215, 0.036]); // Hindwing Right
+ createFoldingWing('WingH', true, -1, [-0.01, 0.215, -0.036]); // Hindwing Left
+
+ return root;
+}
+
+function animate(root) {
+ // Total duration: 5.0 seconds for a majestic, slow unfolding sequence
+ const tracks = [];
+
+ // 1. Clockwork Gears in Thorax
+ tracks.push(rotationTrack('Joint_Gear_Main', [
+ { time: 0.0, rotation: [0, 0, 0] },
+ { time: 1.0, rotation: [0, 0, 90] },
+ { time: 2.5, rotation: [0, 0, 220] },
+ { time: 4.0, rotation: [0, 0, 360] },
+ { time: 5.0, rotation: [0, 0, 360] }
+ ]));
+
+ tracks.push(rotationTrack('Joint_Gear_Sec', [
+ { time: 0.0, rotation: [0, 0, 0] },
+ { time: 1.0, rotation: [0, 0, -144] },
+ { time: 2.5, rotation: [0, 0, -352] },
+ { time: 4.0, rotation: [0, 0, -576] },
+ { time: 5.0, rotation: [0, 0, -576] }
+ ]));
+
+ // 2. Right Forewing
+ // Root Pivot: yaw sweeps from folded back (-76 deg) to flight stance (+3 deg)
+ tracks.push(rotationTrack('Joint_WingF_R_Root', [
+ { time: 0.0, rotation: [-10, -76, 12] },
+ { time: 0.8, rotation: [-8, -68, 10] },
+ { time: 2.0, rotation: [-4, -35, 6] },
+ { time: 3.2, rotation: [-1, -6, 2] },
+ { time: 4.2, rotation: [ 0, 3, 1] },
+ { time: 4.6, rotation: [ 1, 3, 3] },
+ { time: 5.0, rotation: [ 0, 3, 2] }
+ ]));
+ // Mid Pivot (Elbow): hinges open from folded (+135 deg) to straight (0 deg)
+ tracks.push(rotationTrack('Joint_WingF_R_Mid', [
+ { time: 0.0, rotation: [0, 135, 0] },
+ { time: 1.0, rotation: [0, 125, 0] },
+ { time: 2.2, rotation: [0, 70, 0] },
+ { time: 3.4, rotation: [0, 18, 0] },
+ { time: 4.2, rotation: [0, 0, 0] },
+ { time: 5.0, rotation: [0, 0, 0] }
+ ]));
+ // Trailing Flap: fans open
+ tracks.push(rotationTrack('Joint_WingF_R_Flap', [
+ { time: 0.0, rotation: [0, 35, 0] },
+ { time: 1.5, rotation: [0, 30, 0] },
+ { time: 3.0, rotation: [0, 12, 0] },
+ { time: 4.2, rotation: [0, 0, 0] },
+ { time: 5.0, rotation: [0, 0, 0] }
+ ]));
+
+ // 3. Left Forewing (Symmetric)
+ tracks.push(rotationTrack('Joint_WingF_L_Root', [
+ { time: 0.0, rotation: [-10, 76, -12] },
+ { time: 0.8, rotation: [-8, 68, -10] },
+ { time: 2.0, rotation: [-4, 35, -6] },
+ { time: 3.2, rotation: [-1, 6, -2] },
+ { time: 4.2, rotation: [ 0, -3, -1] },
+ { time: 4.6, rotation: [ 1, -3, -3] },
+ { time: 5.0, rotation: [ 0, -3, -2] }
+ ]));
+ tracks.push(rotationTrack('Joint_WingF_L_Mid', [
+ { time: 0.0, rotation: [0, -135, 0] },
+ { time: 1.0, rotation: [0, -125, 0] },
+ { time: 2.2, rotation: [0, -70, 0] },
+ { time: 3.4, rotation: [0, -18, 0] },
+ { time: 4.2, rotation: [0, 0, 0] },
+ { time: 5.0, rotation: [0, 0, 0] }
+ ]));
+ tracks.push(rotationTrack('Joint_WingF_L_Flap', [
+ { time: 0.0, rotation: [0, -35, 0] },
+ { time: 1.5, rotation: [0, -30, 0] },
+ { time: 3.0, rotation: [0, -12, 0] },
+ { time: 4.2, rotation: [0, 0, 0] },
+ { time: 5.0, rotation: [0, 0, 0] }
+ ]));
+
+ // 4. Right Hindwing (Slightly delayed for realistic organic mechanical stagger)
+ tracks.push(rotationTrack('Joint_WingH_R_Root', [
+ { time: 0.0, rotation: [-8, -78, 10] },
+ { time: 1.0, rotation: [-8, -74, 10] },
+ { time: 2.3, rotation: [-4, -42, 6] },
+ { time: 3.5, rotation: [-1, -12, 2] },
+ { time: 4.4, rotation: [ 0, -4, 1] },
+ { time: 4.7, rotation: [ 1, -4, 2.5] },
+ { time: 5.0, rotation: [ 0, -4, 1.5] }
+ ]));
+ tracks.push(rotationTrack('Joint_WingH_R_Mid', [
+ { time: 0.0, rotation: [0, 130, 0] },
+ { time: 1.2, rotation: [0, 120, 0] },
+ { time: 2.5, rotation: [0, 65, 0] },
+ { time: 3.6, rotation: [0, 15, 0] },
+ { time: 4.4, rotation: [0, 0, 0] },
+ { time: 5.0, rotation: [0, 0, 0] }
+ ]));
+ tracks.push(rotationTrack('Joint_WingH_R_Flap', [
+ { time: 0.0, rotation: [0, 32, 0] },
+ { time: 1.6, rotation: [0, 28, 0] },
+ { time: 3.2, rotation: [0, 10, 0] },
+ { time: 4.4, rotation: [0, 0, 0] },
+ { time: 5.0, rotation: [0, 0, 0] }
+ ]));
+
+ // 5. Left Hindwing (Symmetric)
+ tracks.push(rotationTrack('Joint_WingH_L_Root', [
+ { time: 0.0, rotation: [-8, 78, -10] },
+ { time: 1.0, rotation: [-8, 74, -10] },
+ { time: 2.3, rotation: [-4, 42, -6] },
+ { time: 3.5, rotation: [-1, 12, -2] },
+ { time: 4.4, rotation: [ 0, 4, -1] },
+ { time: 4.7, rotation: [ 1, 4, -2.5] },
+ { time: 5.0, rotation: [ 0, 4, -1.5] }
+ ]));
+ tracks.push(rotationTrack('Joint_WingH_L_Mid', [
+ { time: 0.0, rotation: [0, -130, 0] },
+ { time: 1.2, rotation: [0, -120, 0] },
+ { time: 2.5, rotation: [0, -65, 0] },
+ { time: 3.6, rotation: [0, -15, 0] },
+ { time: 4.4, rotation: [0, 0, 0] },
+ { time: 5.0, rotation: [0, 0, 0] }
+ ]));
+ tracks.push(rotationTrack('Joint_WingH_L_Flap', [
+ { time: 0.0, rotation: [0, -32, 0] },
+ { time: 1.6, rotation: [0, -28, 0] },
+ { time: 3.2, rotation: [0, -10, 0] },
+ { time: 4.4, rotation: [0, 0, 0] },
+ { time: 5.0, rotation: [0, 0, 0] }
+ ]));
+
+ return [createClip('Unfold', 5.0, tracks)];
+}
diff --git a/scripts/create-workspace.mjs b/scripts/create-workspace.mjs
index 3b03bfab..da9a2f80 100644
--- a/scripts/create-workspace.mjs
+++ b/scripts/create-workspace.mjs
@@ -46,7 +46,7 @@ function managedFiles(root, runtime, harness, nodeExecutable) {
files['.agents/mcp_config.json'] = quote({ mcpServers: { kiln_workspace: mcp } });
files['agy.mjs'] = `import { spawn } from 'node:child_process';\nimport { dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nconst root = dirname(fileURLToPath(import.meta.url));\nconst args = process.argv.slice(2);\nconst has = names => args.some(arg => names.some(name => arg === name || arg.startsWith(name + '=')));\nif (!has(['--project', '--new-project', '--conversation', '--continue', '-c'])) args.unshift('--new-project');\nargs.unshift('--add-dir', root);\nif (has(['--print', '--prompt', '-p']) && !has(['--disable-slash-commands'])) args.unshift('--disable-slash-commands');\nconst child = spawn('agy', args, { cwd: root, stdio: 'inherit', windowsHide: true });\nchild.on('error', error => { console.error(error.message); process.exitCode = 1; });\nchild.on('exit', code => { process.exitCode = code ?? 1; });\n`;
}
- if (harness === 'opencode') files['opencode.json'] = quote({ $schema: 'https://opencode.ai/config.json', mcp: { kiln_workspace: { type: 'local', command: [mcp.command, server], environment: mcp.env, enabled: true } } });
+ if (harness === 'opencode') files['opencode.json'] = quote({ $schema: 'https://opencode.ai/config.json', skills: { paths: [join(root, 'skills')] }, mcp: { kiln_workspace: { type: 'local', command: [mcp.command, server], environment: mcp.env, enabled: true } } });
if (harness === 'hermes') {
files['.hermes/config.yaml'] = quote({ mcp_servers: { kiln_workspace: mcp } });
files['hermes.mjs'] = `import { spawn } from 'node:child_process';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nconst root = dirname(fileURLToPath(import.meta.url));\nconst child = spawn('hermes', process.argv.slice(2), { cwd: root, stdio: 'inherit', windowsHide: true, env: { ...process.env, HERMES_HOME: join(root, '.hermes'), TERMINAL_CWD: root } });\nchild.on('error', (error) => { console.error(error.message); process.exitCode = 1; });\nchild.on('exit', (code) => { process.exitCode = code ?? 1; });\n`;
diff --git a/site/scripts/collection.mjs b/site/scripts/collection.mjs
index 656911c8..c0598ae8 100644
--- a/site/scripts/collection.mjs
+++ b/site/scripts/collection.mjs
@@ -1,5 +1,5 @@
// Repository source history is broader than the published gallery collection.
-const excluded = new Set(['crate', 'well', 'tidal-observatory', 'fire-lookout-tower', 'brass-tellurion', 'victorian-greenhouse']);
+const excluded = new Set(['crate', 'well', 'tidal-observatory', 'fire-lookout-tower', 'brass-tellurion', 'victorian-greenhouse', 'demo-unfolding-dragonfly']);
export function isPublicExample(name) {
return !excluded.has(name);
}
diff --git a/src/__tests__/examples.test.ts b/src/__tests__/examples.test.ts
index 6244ef74..b233171e 100644
--- a/src/__tests__/examples.test.ts
+++ b/src/__tests__/examples.test.ts
@@ -158,6 +158,7 @@ describe('hero gallery', () => {
'fire-lookout-tower',
'brass-tellurion',
'victorian-greenhouse',
+ 'demo-unfolding-dragonfly',
];
const publicNames = names.filter((name) => !excluded.includes(name));
expect([...(await heroes)].sort()).toEqual(publicNames);
diff --git a/src/__tests__/workspace-bootstrap.test.ts b/src/__tests__/workspace-bootstrap.test.ts
index 94c95e77..711d089d 100644
--- a/src/__tests__/workspace-bootstrap.test.ts
+++ b/src/__tests__/workspace-bootstrap.test.ts
@@ -10,6 +10,34 @@ const setup = join(repo, 'scripts/create-workspace.mjs');
const run = (args: string[], cwd: string) =>
spawnSync('node', [setup, ...args], { cwd, encoding: 'utf8' });
+it('registers the existing local skill tree for OpenCode and preserves edits when repairing paths', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'kiln-opencode-skills-'));
+ try {
+ const before = join(root, 'before');
+ const after = join(root, 'moved');
+ expect(run([before, '--harness', 'opencode', '--skills', 'compose'], root).status).toBe(0);
+ const config = JSON.parse(await readFile(join(before, 'opencode.json'), 'utf8'));
+ expect(config.skills?.paths).toEqual([join(before, 'skills')]);
+ const reference = join('skills', 'kiln-author-asset', 'references', 'program-contract.md');
+ expect(await readFile(join(before, reference), 'utf8')).toBe(
+ await readFile(join(repo, reference), 'utf8'),
+ );
+ expect((await readdir(join(before, 'skills'))).length).toBe(4);
+ const author = join('skills', 'kiln-author-asset', 'SKILL.md');
+ await writeFile(join(before, author), '# owner-edited skill');
+ await writeFile(join(before, reference), '# owner-edited reference');
+ await rename(before, after);
+ expect(run([after, '--repair'], root).status).toBe(0);
+ expect(JSON.parse(await readFile(join(after, 'opencode.json'), 'utf8')).skills.paths).toEqual([
+ join(after, 'skills'),
+ ]);
+ expect(await readFile(join(after, author), 'utf8')).toBe('# owner-edited skill');
+ expect(await readFile(join(after, reference), 'utf8')).toBe('# owner-edited reference');
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+}, 30000);
+
it('defaults to core skills, supports optional skills, and refuses invalid setup before writing', async () => {
const root = await mkdtemp(join(tmpdir(), 'kiln-bootstrap-'));
try {
diff --git a/src/asset-widget.ts b/src/asset-widget.ts
index ca0f86f5..0ee3a026 100644
--- a/src/asset-widget.ts
+++ b/src/asset-widget.ts
@@ -1,6 +1,7 @@
/** MCP-only presentation payload; binary files never enter model-facing tool text. */
import { readFile } from 'node:fs/promises';
import type { AssetLibrary } from './assets';
+import { encodeWidgetFiles, WIDGET_TRANSFER_LIMIT } from './widget-transfer';
export async function assetWidgetData(
library: AssetLibrary,
@@ -15,7 +16,10 @@ export async function assetWidgetData(
selector.asset.assetId,
selector.asset.revisionId,
);
- if (Object.values(record.files).reduce((sum, bytes) => sum + bytes.length, 0) > 16 * 1024 * 1024)
+ if (
+ Object.values(record.files).reduce((sum, bytes) => sum + bytes.length, 0) >
+ WIDGET_TRANSFER_LIMIT
+ )
return {
kilnAsset: {
error: 'This asset exceeds the 16 MiB chat preview limit. Open it with kiln view.',
@@ -25,12 +29,7 @@ export async function assetWidgetData(
kilnAsset: {
manifest: record.manifest,
downloadUrls: selector.downloadUrls,
- files: Object.fromEntries(
- Object.entries(record.files).map(([name, bytes]) => [
- name,
- Buffer.from(bytes).toString('base64'),
- ]),
- ),
+ files: encodeWidgetFiles(record.files),
},
};
}
diff --git a/src/assets-tools.test.ts b/src/assets-tools.test.ts
index d081bfa5..a5f32ee4 100644
--- a/src/assets-tools.test.ts
+++ b/src/assets-tools.test.ts
@@ -7,6 +7,7 @@ import { createKilnMcpServer } from './mcp-server';
import { FileAssetLibrary } from './assets-node';
import { MemoryProgramStore, retainProgram } from './program-store';
import { createKilnProgramToolRegistry } from './tools/registry';
+import { decodeWidgetAsset } from './widget-transfer';
test('MCP saves an editable revision, exposes exact downloadable bytes, and restores source in a new session', async () => {
const root = await mkdtemp(join(tmpdir(), 'kiln-asset-tools-'));
@@ -55,12 +56,19 @@ test('MCP saves an editable revision, exposes exact downloadable bytes, and rest
expect(JSON.stringify(present.content).length).toBeLessThan(6000);
expect((present.structuredContent as { asset?: unknown })?.asset).toBeDefined();
const widget = present._meta?.kilnAsset as {
- files?: Record<string, string>;
+ files?: Record<string, string | { encoding: string; data: string }>;
downloadUrls?: Record<string, string>;
};
expect(widget.downloadUrls?.['asset.glb']).toBe('https://example.com/asset.glb');
expect(widget.files?.['asset.glb']).toBeDefined();
- expect(JSON.stringify(present.content)).not.toContain(widget.files!['asset.glb']!);
+ const wireGlb = widget.files!['asset.glb']!;
+ expect(JSON.stringify(present.content)).not.toContain(
+ typeof wireGlb === 'string' ? wireGlb : wireGlb.data,
+ );
+ const decoded = await decodeWidgetAsset(widget);
+ expect(decoded.record).toEqual(
+ await assetLibrary.read('project', data.asset.assetId, data.asset.revisionId),
+ );
const sourceLink = content.find((b) => b.uri?.endsWith('/source.kiln.js'))!;
expect(sourceLink).toBeDefined();
const source = await client.readResource({ uri: sourceLink.uri! });
diff --git a/src/evaluator/authoring-diagnostic.test.ts b/src/evaluator/authoring-diagnostic.test.ts
index a7e717af..f0eab8f5 100644
--- a/src/evaluator/authoring-diagnostic.test.ts
+++ b/src/evaluator/authoring-diagnostic.test.ts
@@ -9,6 +9,44 @@ import {
import { renderGLBViaSubprocess } from './subprocess';
const code = `function build(){const uvs=[];new THREE.Float32BufferAttribute(uv,2);return createRoot('Duct');}`;
const request = () => createEvaluatorRequestV1({ requestId: 'diagnostic', code }).json;
+
+test('rounded box radius boundary gets a closed hint through handler, subprocess, and registry', async () => {
+ const source = `async function build(){await roundedBoxGeo(0.28,0.068,0.012,0.006);return createRoot('PRIVATE_SOURCE_MARKER');}`;
+ const wire = await evaluateEvaluatorRequestV1(
+ createEvaluatorRequestV1({ requestId: 'rounded-box', code: source }).json,
+ );
+ expect(JSON.parse(wire).error).toEqual({
+ code: 'EXECUTION_REJECTED',
+ message: 'Generated asset execution was rejected.',
+ diagnostic: 'ROUNDED_BOX_RADIUS',
+ });
+ const decoded = decodeEvaluatorResultV1(wire, 100000, 'rounded-box');
+ expect(decoded.ok).toBe(false);
+ const invalidOutcome = JSON.parse(wire);
+ invalidOutcome.error.code = 'WORKER_FAILED';
+ invalidOutcome.error.message = 'Evaluator worker failed.';
+ expect(() =>
+ decodeEvaluatorResultV1(JSON.stringify(invalidOutcome), 100000, 'rounded-box'),
+ ).toThrow();
+ const error = await renderGLBViaSubprocess(source).catch((error: unknown) => error);
+ expect(error).toMatchObject({
+ code: 'EXECUTION_REJECTED',
+ diagnostic: 'ROUNDED_BOX_RADIUS',
+ });
+ expect(String(error)).toContain('radius must be less than half the smallest dimension');
+ const defs = createKilnProgramToolRegistry({ evaluatorPort: { render: renderGLBViaSubprocess } });
+ const out = (await defs.find((d) => d.name === 'kiln_render')!.run({ code: source })) as {
+ ok: boolean;
+ error: string;
+ };
+ expect(out.ok).toBe(false);
+ expect(out.error).toContain('radius must be less than half the smallest dimension');
+ for (const output of [wire, String(error), out.error]) {
+ for (const privateValue of ['0.006', '0.012', 'PRIVATE_SOURCE_MARKER', 'profile.ts']) {
+ expect(output).not.toContain(privateValue);
+ }
+ }
+}, 20000);
test('gear radii mistakes receive a closed repair hint through handler and actual subprocess', async () => {
const source = `function build(){const root=createRoot('Lens');createPart('Gear',gearGeo({teeth:28,tipRadius:0.075,boreRadius:0.012,height:0.024}),gameMaterial(0x909090),{parent:root});return root;}`;
const wire = await evaluateEvaluatorRequestV1(
@@ -68,6 +106,8 @@ test('diagnostic decoder rejects arbitrary strings, extra data, and inappropriat
test('arbitrary exceptions and safety denials retain generic rejection', async () => {
for (const source of [
`function build(){throw new Error('SECRET_HOST_PATH');}`,
+ `function build(){throw new Error('roundedBoxGeo: radius must be less than half the smallest dimension SECRET_HOST_PATH');}`,
+ `function build(){throw Object.assign(new Error('SECRET_HOST_PATH'),{name:'AuthoringDiagnosticError',diagnostic:'ROUNDED_BOX_RADIUS'});}`,
`function build(){return process.env.SECRET;}`,
]) {
const result = JSON.parse(
diff --git a/src/evaluator/authoring-diagnostic.ts b/src/evaluator/authoring-diagnostic.ts
index de71a13b..62a5f639 100644
--- a/src/evaluator/authoring-diagnostic.ts
+++ b/src/evaluator/authoring-diagnostic.ts
@@ -1,11 +1,14 @@
/** Closed, engine-owned repair hints. Never serialize exception messages or stacks. */
-export type AuthoringDiagnostic = 'UNBOUND_VARIABLE' | 'GEAR_RADII_ORDER';
+export type AuthoringDiagnostic = 'UNBOUND_VARIABLE' | 'GEAR_RADII_ORDER' | 'ROUNDED_BOX_RADIUS';
export const UNBOUND_VARIABLE_ADVICE =
'Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying.';
export const GEAR_RADII_ORDER_ADVICE =
'gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.';
+export const ROUNDED_BOX_RADIUS_ADVICE =
+ 'roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.';
export function authoringDiagnosticAdvice(diagnostic: AuthoringDiagnostic | undefined): string {
if (diagnostic === 'UNBOUND_VARIABLE') return UNBOUND_VARIABLE_ADVICE;
+ if (diagnostic === 'ROUNDED_BOX_RADIUS') return ROUNDED_BOX_RADIUS_ADVICE;
return diagnostic === 'GEAR_RADII_ORDER' ? GEAR_RADII_ORDER_ADVICE : '';
}
export class AuthoringDiagnosticError extends Error {
diff --git a/src/evaluator/protocol.ts b/src/evaluator/protocol.ts
index 3e5f2b98..d6f1ade7 100644
--- a/src/evaluator/protocol.ts
+++ b/src/evaluator/protocol.ts
@@ -399,7 +399,8 @@ export function decodeEvaluatorResultV1(
value.error.diagnostic !== undefined &&
(value.error.code !== 'EXECUTION_REJECTED' ||
(value.error.diagnostic !== 'UNBOUND_VARIABLE' &&
- value.error.diagnostic !== 'GEAR_RADII_ORDER'))
+ value.error.diagnostic !== 'GEAR_RADII_ORDER' &&
+ value.error.diagnostic !== 'ROUNDED_BOX_RADIUS'))
)
return fail('result');
if (value.error.qa !== undefined) {
diff --git a/src/profile.ts b/src/profile.ts
index 5ea890fd..f1902f9a 100644
--- a/src/profile.ts
+++ b/src/profile.ts
@@ -48,6 +48,7 @@
import type * as THREE from 'three';
import type { CrossSection, JoinType, Manifold, Vec2 } from 'manifold-3d';
import { getManifoldModule, manifoldToGeometry } from './solids';
+import { AuthoringDiagnosticError } from './evaluator/authoring-diagnostic';
/** A closed 2D outline as `[x, y]` pairs — same convention as `lathe`. */
export type Profile2D = Array<[number, number]>;
@@ -400,10 +401,7 @@ export async function roundedBoxGeo(
const smallest = Math.min(width, height, depth);
if (radius >= smallest / 2) {
- throw new Error(
- `roundedBoxGeo: radius ${radius} must be less than half the smallest dimension ` +
- `(${smallest} / 2 = ${smallest / 2}). A larger radius has no box left to round.`,
- );
+ throw new AuthoringDiagnosticError('ROUNDED_BOX_RADIUS');
}
const mod = await getManifoldModule();
diff --git a/src/tools/registry.ts b/src/tools/registry.ts
index 07fe42db..34c803bf 100644
--- a/src/tools/registry.ts
+++ b/src/tools/registry.ts
@@ -51,7 +51,7 @@ import type { TextureUsage } from '../textures';
// Tool definition contract
// =============================================================================
-export const KILN_ASSET_WIDGET_URI = 'ui://kiln/asset-v3.html';
+export const KILN_ASSET_WIDGET_URI = 'ui://kiln/asset-v5.html';
export interface KilnToolDef {
outputSchema?: z.ZodType;
/** Optional MCP App presentation; metadata is hidden from the language model. */
diff --git a/src/viewer/chat-app.ts b/src/viewer/chat-app.ts
index 5d41b4be..db3c92bd 100644
--- a/src/viewer/chat-app.ts
+++ b/src/viewer/chat-app.ts
@@ -2,6 +2,7 @@
import { createAssetStage } from './scene';
import { encodeAssetBundle, type AssetRecord } from '../assets';
import { downloadChatFile, type ChatFileHost } from './chat-download';
+import { decodeWidgetAsset } from '../widget-transfer';
declare global {
interface Window {
@@ -15,6 +16,7 @@ let record: AssetRecord | undefined;
let downloadUrls: Record<string, string> = {};
let stage: ReturnType<typeof createAssetStage> | undefined;
let sequence = 0;
+let presentationRevision = 0;
const pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>();
function request(method: string, params: unknown): Promise<unknown> {
const id = ++sequence;
@@ -39,52 +41,64 @@ function request(method: string, params: unknown): Promise<unknown> {
function notify(method: string, params: unknown = {}) {
window.parent.postMessage({ jsonrpc: '2.0', method, params }, '*');
}
-function decode(value: string) {
- return Uint8Array.from(atob(value), (c) => c.charCodeAt(0));
-}
function encode(bytes: Uint8Array) {
let binary = '';
for (let i = 0; i < bytes.length; i += 8192)
binary += String.fromCharCode(...bytes.subarray(i, i + 8192));
return btoa(binary);
}
-async function show(result: {
- isError?: boolean;
- content?: { type: string; text?: string }[];
- _meta?: {
- kilnAsset?: {
- error?: string;
- manifest: AssetRecord['manifest'];
- files: Record<string, string>;
- downloadUrls?: Record<string, string>;
- };
- };
-}) {
+async function show(input: unknown) {
+ const revision = ++presentationRevision;
+ record = undefined;
+ for (const button of document.querySelectorAll<HTMLButtonElement>('button[data-download]'))
+ button.disabled = true;
+ try {
+ if (!input || typeof input !== 'object' || Array.isArray(input))
+ throw new Error('Asset transfer metadata is missing. Present the saved asset again.');
+ await showResult(input, revision);
+ } catch (error) {
+ if (revision !== presentationRevision) return;
+ status.textContent =
+ error instanceof Error
+ ? error.message
+ : 'Asset transfer failed. Present the saved asset again.';
+ }
+}
+async function showResult(
+ result: {
+ isError?: boolean;
+ content?: { type: string; text?: string }[];
+ _meta?: { kilnAsset?: unknown };
+ },
+ revision: number,
+) {
if (result.isError) {
status.textContent =
result.content?.find((item) => item.type === 'text')?.text ??
'This asset could not be opened.';
return;
}
- const asset = result._meta?.kilnAsset;
- if (!asset) return;
- if (asset.error) {
- status.textContent = asset.error;
+ let received: Awaited<ReturnType<typeof decodeWidgetAsset>>;
+ try {
+ received = await decodeWidgetAsset(result._meta?.kilnAsset);
+ } catch (error) {
+ if (revision !== presentationRevision) return;
+ status.textContent =
+ error instanceof Error
+ ? error.message
+ : 'Asset transfer failed. Present the saved asset again.';
return;
}
- record = {
- manifest: asset.manifest,
- files: Object.fromEntries(
- Object.entries(asset.files).map(([name, data]) => [name, decode(data)]),
- ),
- };
+ if (revision !== presentationRevision) return;
+ record = received.record;
element('name').textContent = record.manifest.name;
- downloadUrls = asset.downloadUrls ?? {};
+ downloadUrls = received.downloadUrls;
element('revision').textContent =
`${record.manifest.editable ? 'Editable source included' : 'GLB asset'} · ${record.manifest.revisionId.slice(0, 10)}`;
try {
stage ??= createAssetStage(element('stage'));
const stats = await stage.load(record.files['asset.glb']!);
+ if (revision !== presentationRevision) return;
if (stats) {
element('stats').textContent =
`${stats.triangles.toLocaleString()} triangles · ${stats.materials} materials · ${(record.files['asset.glb']!.length / 1024).toFixed(0)} KB`;
@@ -97,6 +111,7 @@ async function show(result: {
}
status.textContent = 'Drag to orbit · Scroll to zoom';
} catch (error) {
+ if (revision !== presentationRevision) return;
const preview = record.files['preview.png'];
if (preview) {
const image = new Image();
@@ -134,6 +149,7 @@ element<HTMLSelectElement>('clips').onchange = (event) =>
for (const button of document.querySelectorAll<HTMLButtonElement>('button[data-download]')) {
button.onclick = async () => {
if (!record) return;
+ const downloadRevision = presentationRevision;
const kind = button.dataset.download!;
const filename =
kind === 'bundle' ? 'editable.zip' : kind === 'source' ? 'source.kiln.js' : 'asset.glb';
@@ -161,6 +177,7 @@ for (const button of document.querySelectorAll<HTMLButtonElement>('button[data-d
host,
downloadUrls[filename],
);
+ if (downloadRevision !== presentationRevision) return;
if (result.downloadUrl) {
const link = document.createElement('a');
link.href = result.downloadUrl;
@@ -177,9 +194,10 @@ for (const button of document.querySelectorAll<HTMLButtonElement>('button[data-d
status.replaceChildren('Download ready. ', link);
} else status.textContent = 'Download requested.';
} catch (error) {
- status.textContent = `Download unavailable in this host: ${(error as Error).message}`;
+ if (downloadRevision === presentationRevision)
+ status.textContent = `Download unavailable in this host: ${(error as Error).message}`;
} finally {
- button.disabled = false;
+ button.disabled = !record || downloadRevision !== presentationRevision;
}
};
}
diff --git a/src/viewer/framing.test.ts b/src/viewer/framing.test.ts
new file mode 100644
index 00000000..39c615ab
--- /dev/null
+++ b/src/viewer/framing.test.ts
@@ -0,0 +1,72 @@
+import { expect, test } from 'bun:test';
+import { Box3, PerspectiveCamera, Vector3 } from 'three';
+import { frameAssetBounds } from './framing';
+
+for (const aspect of [720 / 320, 1, 320 / 720]) {
+ for (const size of [
+ [32, 5, 7],
+ [2, 30, 2],
+ [6, 6, 6],
+ ]) {
+ test(`frames ${size.join('x')} bounds at aspect ${aspect} with useful screen coverage`, () => {
+ const box = new Box3().setFromCenterAndSize(new Vector3(80, -20, 13), new Vector3(...size));
+ const pose = frameAssetBounds(box, aspect);
+ const camera = new PerspectiveCamera(
+ 40,
+ aspect,
+ pose.radius / 1000,
+ pose.distance + pose.radius * 100,
+ );
+ camera.position.copy(pose.position);
+ camera.lookAt(pose.center);
+ camera.updateMatrixWorld();
+ let extent = 0;
+ for (const x of [box.min.x, box.max.x]) {
+ for (const y of [box.min.y, box.max.y]) {
+ for (const z of [box.min.z, box.max.z]) {
+ const projected = new Vector3(x, y, z).project(camera);
+ extent = Math.max(extent, Math.abs(projected.x), Math.abs(projected.y));
+ expect(Math.abs(projected.x)).toBeLessThanOrEqual(0.9);
+ expect(Math.abs(projected.y)).toBeLessThanOrEqual(0.9);
+ expect(projected.z).toBeGreaterThan(-1);
+ expect(projected.z).toBeLessThan(1);
+ }
+ }
+ }
+ expect(extent).toBeGreaterThan(0.85);
+ });
+ }
+}
+
+test('degenerate point bounds retain a finite usable camera distance', () => {
+ const pose = frameAssetBounds(new Box3(new Vector3(), new Vector3()), 2);
+ expect(Number.isFinite(pose.distance)).toBe(true);
+ expect(pose.distance).toBeGreaterThan(0);
+});
+
+test('sparse assemblies fit their occupied bounds instead of empty global corners', () => {
+ const hull = new Box3(new Vector3(-16, -1, -3), new Vector3(16, 1, 3));
+ const mast = new Box3(new Vector3(-1, 1, -0.5), new Vector3(1, 12, 0.5));
+ const box = hull.clone().union(mast);
+ const aspect = 2.25;
+ const conservative = frameAssetBounds(box, aspect);
+ const pose = frameAssetBounds(box, aspect, 40, [hull, mast]);
+ expect(pose.distance).toBeLessThan(conservative.distance * 0.9);
+ const camera = new PerspectiveCamera(40, aspect, 0.01, 1000);
+ camera.position.copy(pose.position);
+ camera.lookAt(pose.center);
+ camera.updateMatrixWorld();
+ for (const component of [hull, mast]) {
+ for (const x of [component.min.x, component.max.x]) {
+ for (const y of [component.min.y, component.max.y]) {
+ for (const z of [component.min.z, component.max.z]) {
+ const point = new Vector3(x, y, z).project(camera);
+ expect(Math.abs(point.x)).toBeLessThanOrEqual(0.9);
+ expect(Math.abs(point.y)).toBeLessThanOrEqual(0.9);
+ expect(point.z).toBeGreaterThan(-1);
+ expect(point.z).toBeLessThan(1);
+ }
+ }
+ }
+ }
+});
diff --git a/src/viewer/framing.ts b/src/viewer/framing.ts
new file mode 100644
index 00000000..a2a6e5ca
--- /dev/null
+++ b/src/viewer/framing.ts
@@ -0,0 +1,55 @@
+import { type Box3, Vector3 } from 'three';
+
+/** Initial orbit-camera pose for an asset's world-space bounds. */
+export function frameAssetBounds(
+ box: Box3,
+ aspect: number,
+ verticalFovDeg = 40,
+ componentBounds: readonly Box3[] = [box],
+) {
+ const center = box.getCenter(new Vector3());
+ const radius = Math.max(box.getSize(new Vector3()).length() / 2, 0.01);
+ const back = new Vector3(1, 0.65, 1.25).normalize();
+ const right = new Vector3().crossVectors(new Vector3(0, 1, 0), back).normalize();
+ const up = new Vector3().crossVectors(back, right);
+ const corners: Vector3[] = [];
+ for (const component of componentBounds.length ? componentBounds : [box]) {
+ for (const x of [component.min.x, component.max.x]) {
+ for (const y of [component.min.y, component.max.y]) {
+ for (const z of [component.min.z, component.max.z]) corners.push(new Vector3(x, y, z));
+ }
+ }
+ }
+ let left = Infinity;
+ let rightmost = -Infinity;
+ let bottom = Infinity;
+ let top = -Infinity;
+ for (const corner of corners) {
+ const offset = corner.clone().sub(center);
+ const horizontal = offset.dot(right);
+ const vertical = offset.dot(up);
+ left = Math.min(left, horizontal);
+ rightmost = Math.max(rightmost, horizontal);
+ bottom = Math.min(bottom, vertical);
+ top = Math.max(top, vertical);
+ }
+ center.addScaledVector(right, (left + rightmost) / 2);
+ center.addScaledVector(up, (bottom + top) / 2);
+ const tanVertical = Math.tan((verticalFovDeg * Math.PI) / 360);
+ const tanHorizontal = tanVertical * aspect;
+ let distance = radius;
+ // At each corner, depth + projected extent is the minimum distance that
+ // fits that point. Reserve 12% padding in both screen dimensions.
+ // Component bounds exclude empty corners between a long hull and a tall mast.
+ for (const corner of corners) {
+ const offset = corner.clone().sub(center);
+ const depth = offset.dot(back);
+ distance = Math.max(
+ distance,
+ depth + (Math.abs(offset.dot(right)) * 1.12) / tanHorizontal,
+ depth + (Math.abs(offset.dot(up)) * 1.12) / tanVertical,
+ );
+ }
+ const position = center.clone().addScaledVector(back, distance);
+ return { center, radius, distance, position };
+}
diff --git a/src/viewer/scene.ts b/src/viewer/scene.ts
index af74a7a7..15e95b20 100644
--- a/src/viewer/scene.ts
+++ b/src/viewer/scene.ts
@@ -4,6 +4,7 @@ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { validateAssetGlb } from '../assets';
+import { frameAssetBounds } from './framing';
/** The gallery's local studio lighting, orbit controls, and framing in a small standalone surface. */
export function createAssetStage(container: HTMLElement) {
@@ -54,18 +55,25 @@ export function createAssetStage(container: HTMLElement) {
const reset = () => {
if (!root) return;
const box = new THREE.Box3().setFromObject(root, true);
- const center = box.getCenter(new THREE.Vector3());
- const size = box.getSize(new THREE.Vector3());
- const radius = Math.max(size.length() / 2, 0.01);
- const fov = Math.min(
- (camera.fov * Math.PI) / 180,
- 2 * Math.atan(Math.tan((camera.fov * Math.PI) / 360) * camera.aspect),
+ const components: THREE.Box3[] = [];
+ root.traverse((object) => {
+ if (
+ object instanceof THREE.Mesh ||
+ object instanceof THREE.Line ||
+ object instanceof THREE.Points
+ ) {
+ const bounds = new THREE.Box3().setFromObject(object, true);
+ if (!bounds.isEmpty()) components.push(bounds);
+ }
+ });
+ const { center, radius, distance, position } = frameAssetBounds(
+ box,
+ camera.aspect,
+ camera.fov,
+ components,
);
- const distance = (radius / Math.sin(fov / 2)) * 1.12;
controls.target.copy(center);
- camera.position
- .copy(center)
- .add(new THREE.Vector3(1, 0.65, 1.25).normalize().multiplyScalar(distance));
+ camera.position.copy(position);
camera.near = Math.max(radius / 1000, 0.0001);
camera.far = distance + radius * 100;
controls.minDistance = radius * 0.1;
diff --git a/src/views/__tests__/glb.test.ts b/src/views/__tests__/glb.test.ts
index c9355a53..b8d2c939 100644
--- a/src/views/__tests__/glb.test.ts
+++ b/src/views/__tests__/glb.test.ts
@@ -71,6 +71,48 @@ function triangleDocument(
}
describe('GLB-native geometry-flat view input', () => {
+ test('shared mesh resources retain owning node names in primitive QA repair hints', async () => {
+ const doc = triangleDocument();
+ const first = doc.getRoot().listNodes()[0]!.setName('ChainLink_A');
+ const sharedMesh = first.getMesh()!;
+ doc
+ .getRoot()
+ .getDefaultScene()!
+ .addChild(doc.createNode('ChainLink_B').setMesh(sharedMesh).setTranslation([2, 0, 0]));
+ const bytes = await io().writeBinary(doc);
+ const exported = await io().readBinary(bytes);
+ expect(exported.getRoot().listMeshes()).toHaveLength(1);
+ expect(
+ exported
+ .getRoot()
+ .listNodes()
+ .map((node) => node.getMesh()),
+ ).toEqual([exported.getRoot().listMeshes()[0]!, exported.getRoot().listMeshes()[0]!]);
+ const loaded = await loadGlbReviewScene(bytes);
+ expect(loaded.root.getObjectByName('ChainLink_A')!.children[0]!.name).toBe(
+ 'ChainLink_A:primitive-0',
+ );
+ expect(loaded.root.getObjectByName('ChainLink_B')!.children[0]!.name).toBe(
+ 'ChainLink_B:primitive-0',
+ );
+ expect(measureBounds(loaded.root)).toEqual({ min: [0, 0, 0], max: [3, 1, 0] });
+ const warnings = renderModule.inspectSceneStructure(loaded.root).join('\n');
+ expect(warnings).toContain(
+ 'shift "ChainLink_A:primitive-0" by [1.000, 0.000, 0.000] toward "ChainLink_B:primitive-0"',
+ );
+ expect(warnings).toContain(
+ 'shift "ChainLink_B:primitive-0" by [-1.000, 0.000, 0.000] toward "ChainLink_A:primitive-0"',
+ );
+ expect(warnings).not.toContain('TriangleMesh');
+ });
+
+ test('unnamed review nodes retain mesh-resource names as a fallback', async () => {
+ const doc = triangleDocument();
+ doc.getRoot().listNodes()[0]!.setName('');
+ const loaded = await loadGlbReviewScene(await io().writeBinary(doc));
+ expect(loaded.root.children[0]!.children[0]!.name).toBe('TriangleMesh:primitive-0');
+ });
+
test('reads exact bytes without executeKilnCode and reports their SHA-256 identity', async () => {
const bytes = await io().writeBinary(triangleDocument());
const executeSpy = spyOn(renderModule, 'executeKilnCode');
@@ -121,6 +163,11 @@ describe('GLB-native geometry-flat view input', () => {
const loaded = await loadGlbGeometryFlatScene(await io().writeBinary(doc));
expect(loaded.instanceCount).toBe(2);
expect(measureBounds(loaded.root)).toEqual({ min: [0, 0, 0], max: [11, 1, 0] });
+ const review = await loadGlbReviewScene(await io().writeBinary(doc));
+ expect(review.root.getObjectByName('Triangle')!.children.map((node) => node.name)).toEqual([
+ 'Triangle:primitive-0:instance-0',
+ 'Triangle:primitive-0:instance-1',
+ ]);
});
test('reports stable structured reasons for ignored PNG and KTX2 sampling', async () => {
diff --git a/src/views/annotate.test.ts b/src/views/annotate.test.ts
new file mode 100644
index 00000000..7ca109ff
--- /dev/null
+++ b/src/views/annotate.test.ts
@@ -0,0 +1,73 @@
+import { expect, test } from 'bun:test';
+import { annotateViewCell, stampAxisGnomon } from './annotate';
+import { stampLabel } from './pose';
+
+const dir = [1, 0, 0] as const;
+const cell = (size: number) => new Uint8Array(size * size * 3).fill(180);
+
+test('tiny port cells preserve the legacy clipped annotation instead of dropping it', () => {
+ for (const size of [4, 8, 10]) {
+ const actual = cell(size);
+ const expected = cell(size);
+ annotateViewCell(actual, size, { name: 'FRONT', dir });
+ stampLabel(expected, size, size, 2, 2, 'FRONT', 2);
+ stampAxisGnomon(expected, size, dir);
+ expect(Buffer.compare(actual, expected)).toBe(0);
+ expect(Buffer.compare(actual, cell(size))).not.toBe(0);
+ }
+});
+
+test('short camera names retain existing pixels at each supported cell size', () => {
+ for (const size of [128, 256, 384, 1024]) {
+ const actual = cell(size);
+ const expected = cell(size);
+ const scale = Math.max(2, Math.round(size / 96));
+ annotateViewCell(actual, size, { name: 'FRONT', dir });
+ stampLabel(expected, size, size, scale, scale, 'FRONT', scale);
+ stampAxisGnomon(expected, size, dir);
+ expect(Buffer.compare(actual, expected)).toBe(0);
+ }
+});
+
+test('reported long custom camera label fits completely without clipping', () => {
+ const size = 256;
+ const name = 'Resolute initial / bow quarter';
+ const actual = cell(size);
+ const expected = cell(size);
+ annotateViewCell(actual, size, { name, dir });
+ stampLabel(expected, size, size, 3, 3, name, 2);
+ stampAxisGnomon(expected, size, dir);
+ expect(Buffer.compare(actual, expected)).toBe(0);
+});
+
+test('long names wrap at legible scale two within three corner rows', () => {
+ const size = 128;
+ const actual = cell(size);
+ const expected = cell(size);
+ annotateViewCell(actual, size, { name: 'FORWARD CAMERA WITH VERY LONG CUSTOM VIEW', dir });
+ stampLabel(expected, size, size, 2, 2, 'FORWARD CAMERA', 2);
+ stampLabel(expected, size, size, 2, 16, 'WITH VERY LONG', 2);
+ stampLabel(expected, size, size, 2, 30, 'CUSTOM VIEW', 2);
+ stampAxisGnomon(expected, size, dir);
+ expect(Buffer.compare(actual, expected)).toBe(0);
+});
+
+test('pathological names split oversized words and end in visible ellipsis', () => {
+ const size = 128;
+ const name = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.repeat(5);
+ const actual = cell(size);
+ const expected = cell(size);
+ const view = { name, dir };
+ annotateViewCell(actual, size, view);
+ stampLabel(expected, size, size, 2, 2, name.slice(0, 15), 2);
+ stampLabel(expected, size, size, 2, 16, name.slice(15, 30), 2);
+ stampLabel(expected, size, size, 2, 30, `${name.slice(30, 42)}...`, 2);
+ stampAxisGnomon(expected, size, dir);
+ expect(Buffer.compare(actual, expected)).toBe(0);
+ expect(view.name).toBe(name);
+ for (let y = 0; y < 48; y++)
+ for (let x = size - 2; x < size; x++) expect(actual[(y * size + x) * 3]).toBe(180);
+ // Label stays in the corner strip; it cannot grow down over the subject.
+ for (let y = 44; y < 70; y++)
+ for (let x = 0; x < size; x++) expect(actual[(y * size + x) * 3]).toBe(180);
+});
diff --git a/src/views/annotate.ts b/src/views/annotate.ts
index e61b4624..292016e0 100644
--- a/src/views/annotate.ts
+++ b/src/views/annotate.ts
@@ -102,7 +102,37 @@ export function annotateViewCell(
size: number,
view: { name: string; dir: readonly number[] },
): void {
- const labelScale = Math.max(2, Math.round(size / 96));
- stampLabel(rgb, size, size, labelScale, labelScale, view.name, labelScale);
+ const inset = Math.max(2, Math.round(size / 96));
+ const width = size - inset * 2;
+ // stampLabel's 3x5 font occupies (4*n + 1)*scale including its backdrop.
+ // Keep ordinary labels byte-for-byte identical; only fit overflowing names.
+ // Tiny injected port cells may not fit even one 7px row. Preserve their
+ // legacy clipped stamp instead of computing zero rows and losing annotation.
+ if (width < 7 || (4 * view.name.length + 1) * inset <= width) {
+ stampLabel(rgb, size, size, inset, inset, view.name, inset);
+ } else {
+ const minimumScale = size >= 128 ? 2 : 1;
+ const scale = Math.max(minimumScale, Math.floor(width / (4 * view.name.length + 1)));
+ const columns = Math.max(1, Math.floor((width / scale - 1) / 4));
+ const rows = Math.min(3, Math.floor((size - inset * 2) / (7 * scale)));
+ let remaining = view.name.toUpperCase();
+ for (let row = 0; row < rows && remaining; row++) {
+ let line = remaining;
+ if (remaining.length > columns) {
+ if (row === rows - 1) {
+ // Names are unbounded in the schema. Show an explicit continuation
+ // rather than clipping or letting the overlay consume the scene.
+ line = `${remaining.slice(0, Math.max(0, columns - 3)).trimEnd()}${'.'.repeat(Math.min(3, columns))}`;
+ remaining = '';
+ } else {
+ const space = remaining.lastIndexOf(' ', columns);
+ const end = space > 0 ? space : columns;
+ line = remaining.slice(0, end);
+ remaining = remaining.slice(end).trimStart();
+ }
+ } else remaining = '';
+ stampLabel(rgb, size, size, inset, inset + row * 7 * scale, line, scale);
+ }
+ }
stampAxisGnomon(rgb, size, view.dir);
}
diff --git a/src/views/glb.ts b/src/views/glb.ts
index 36f7c2b9..2d7bd068 100644
--- a/src/views/glb.ts
+++ b/src/views/glb.ts
@@ -597,7 +597,9 @@ export async function loadGlbReviewScene(bytes: Uint8Array): Promise<LoadedGlbRe
}
for (const [index, matrix] of matrices.entries()) {
const mesh = new Mesh(geometry, threeMaterial);
- const baseName = sourceMesh.getName() || source.getName() || 'Mesh';
+ // A deduplicated mesh resource can serve many distinctly named nodes.
+ // QA repair hints must identify this owning node, not the shared resource.
+ const baseName = source.getName() || sourceMesh.getName() || 'Mesh';
mesh.name = `${baseName}:primitive-${primitiveIndex}${
matrices.length === 1 ? '' : `:instance-${index}`
}`;
diff --git a/src/widget-transfer.test.ts b/src/widget-transfer.test.ts
new file mode 100644
index 00000000..66f5f093
--- /dev/null
+++ b/src/widget-transfer.test.ts
@@ -0,0 +1,141 @@
+import { describe, expect, it } from 'bun:test';
+import { deflateSync } from 'three/addons/libs/fflate.module.js';
+import type { AssetRecord } from './assets';
+import { decodeWidgetAsset, encodeWidgetFiles, WIDGET_TRANSFER_LIMIT } from './widget-transfer';
+
+async function fixture(): Promise<AssetRecord> {
+ const files = {
+ 'asset.glb': new Uint8Array(4096).fill(17),
+ 'source.kiln.js': new TextEncoder().encode('const source = "Exact source bytes";'),
+ 'preview.png': new Uint8Array([0, 255, 1, 2, 3, 128]),
+ };
+ const entries = await Promise.all(
+ Object.entries(files).map(async ([name, bytes]) => [
+ name,
+ {
+ bytes: bytes.length,
+ sha256: `sha256:${Buffer.from(await crypto.subtle.digest('SHA-256', bytes)).toString('hex')}`,
+ },
+ ]),
+ );
+ return {
+ manifest: {
+ version: 'kiln.asset.v1',
+ assetId: 'a_test',
+ revisionId: 'r_test',
+ name: 'Transfer fixture',
+ tags: [],
+ createdAt: '2026-09-08T00:00:00.000Z',
+ editable: true,
+ files: Object.fromEntries(entries),
+ },
+ files,
+ };
+}
+function legacy(record: AssetRecord) {
+ return {
+ manifest: record.manifest,
+ files: Object.fromEntries(
+ Object.entries(record.files).map(([name, bytes]) => [
+ name,
+ Buffer.from(bytes).toString('base64'),
+ ]),
+ ),
+ };
+}
+describe('widget asset transfer', () => {
+ it('losslessly roundtrips compressed GLB, source and preview bytes', async () => {
+ const record = await fixture();
+ const files = encodeWidgetFiles(record.files);
+ expect(typeof files['asset.glb']).toBe('object');
+ const decoded = await decodeWidgetAsset({ manifest: record.manifest, files });
+ expect(decoded.record).toEqual(record);
+ });
+ it('reads legacy plain base64 without changing any bytes', async () => {
+ const record = await fixture();
+ expect((await decodeWidgetAsset(legacy(record))).record).toEqual(record);
+ });
+ it('rejects the observed non-Latin1 transfer error and truncated base64', async () => {
+ const record = await fixture();
+ for (const value of [
+ 'AAAA…AAAA',
+ Buffer.from(record.files['asset.glb']!).toString('base64').slice(0, -1),
+ ]) {
+ const payload = legacy(record);
+ payload.files['asset.glb'] = value;
+ await expect(decodeWidgetAsset(payload)).rejects.toThrow('transfer');
+ }
+ });
+ it('rejects corrupt, truncated and oversized compressed data', async () => {
+ const record = await fixture();
+ const files = encodeWidgetFiles(record.files);
+ const compressed = files['asset.glb'] as { encoding: string; data: string };
+ for (const data of [
+ compressed.data.slice(0, -4),
+ Buffer.from([255, 255, 255]).toString('base64'),
+ Buffer.from(deflateSync(new Uint8Array(8192).fill(17))).toString('base64'),
+ ]) {
+ await expect(
+ decodeWidgetAsset({
+ manifest: record.manifest,
+ files: { ...files, 'asset.glb': { ...compressed, data } },
+ }),
+ ).rejects.toThrow('transfer');
+ }
+ const bad = structuredClone(record.manifest);
+ bad.files['asset.glb']!.bytes = WIDGET_TRANSFER_LIMIT + 1;
+ await expect(decodeWidgetAsset({ manifest: bad, files })).rejects.toThrow('limit');
+ });
+ it('rejects valid-length corruption via manifest hashes', async () => {
+ const record = await fixture();
+ const payload = legacy(record);
+ payload.files['asset.glb'] = Buffer.from(new Uint8Array(4096).fill(18)).toString('base64');
+ await expect(decodeWidgetAsset(payload)).rejects.toThrow('integrity');
+ });
+ it('rejects malformed/missing metadata and unknown encoding', async () => {
+ const record = await fixture();
+ for (const payload of [
+ undefined,
+ null,
+ {},
+ { manifest: record.manifest, files: [] },
+ { manifest: record.manifest, files: {} },
+ {
+ manifest: record.manifest,
+ files: { ...legacy(record).files, 'asset.glb': { encoding: 'unknown', data: 'AAAA' } },
+ },
+ ])
+ await expect(decodeWidgetAsset(payload)).rejects.toThrow('transfer');
+ });
+ it('enforces aggregate decoded and encoded bounds before decoding', async () => {
+ const record = await fixture();
+ const payload = legacy(record);
+ const manifest = structuredClone(record.manifest);
+ manifest.files['asset.glb']!.bytes = WIDGET_TRANSFER_LIMIT;
+ await expect(decodeWidgetAsset({ ...payload, manifest })).rejects.toThrow('limit');
+ await expect(
+ decodeWidgetAsset({
+ ...payload,
+ files: {
+ ...payload.files,
+ 'asset.glb': 'A'.repeat(Math.ceil(WIDGET_TRANSFER_LIMIT / 3) * 4 + 4),
+ },
+ }),
+ ).rejects.toThrow('limit');
+ expect(() =>
+ encodeWidgetFiles({ 'asset.glb': new Uint8Array(WIDGET_TRANSFER_LIMIT + 1) }),
+ ).toThrow('limit');
+ });
+ it('rejects omitted saved files and malformed download metadata', async () => {
+ const record = await fixture();
+ const payload = legacy(record);
+ delete payload.files['preview.png'];
+ await expect(decodeWidgetAsset(payload)).rejects.toThrow('missing a saved file');
+ await expect(decodeWidgetAsset({ ...legacy(record), downloadUrls: [] })).rejects.toThrow(
+ 'download metadata',
+ );
+ await expect(
+ decodeWidgetAsset({ ...legacy(record), downloadUrls: { 'asset.glb': 42 } }),
+ ).rejects.toThrow('download metadata');
+ });
+});
diff --git a/src/widget-transfer.ts b/src/widget-transfer.ts
new file mode 100644
index 00000000..ab5498e2
--- /dev/null
+++ b/src/widget-transfer.ts
@@ -0,0 +1,115 @@
+/** Browser-safe, lossless presentation transport. Stored asset bytes never change. */
+import { deflateSync, inflateSync } from 'three/addons/libs/fflate.module.js';
+import { assetManifestSchema, type AssetRecord } from './assets';
+
+export const WIDGET_TRANSFER_LIMIT = 16 * 1024 * 1024;
+const ENCODED_LIMIT = Math.ceil(WIDGET_TRANSFER_LIMIT / 3) * 4;
+type EncodedFile = string | { encoding: 'kiln.deflate-base64.v1'; data: string };
+const invalid = (detail: string): never => {
+ throw new Error(
+ `Asset transfer ${detail}. Present the saved asset again or open it in Kiln; the saved files are unchanged.`,
+ );
+};
+function base64(bytes: Uint8Array): string {
+ let binary = '';
+ for (let index = 0; index < bytes.length; index += 8192)
+ binary += String.fromCharCode(...bytes.subarray(index, index + 8192));
+ return btoa(binary);
+}
+function unbase64(data: unknown): Uint8Array {
+ if (typeof data !== 'string' || data.length > ENCODED_LIMIT)
+ return invalid('exceeds the encoded size limit');
+ if (data.length % 4 || !/^[A-Za-z0-9+/]*={0,2}$/.test(data))
+ invalid('contains damaged base64 data');
+ let binary: string;
+ try {
+ binary = atob(data);
+ } catch {
+ return invalid('contains damaged base64 data');
+ }
+ const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
+ if (base64(bytes) !== data) invalid('contains noncanonical base64 data');
+ return bytes;
+}
+export function encodeWidgetFiles(files: AssetRecord['files']): Record<string, EncodedFile> {
+ if (
+ Object.values(files).reduce((total, bytes) => total + bytes.length, 0) > WIDGET_TRANSFER_LIMIT
+ )
+ invalid('exceeds the decoded size limit');
+ return Object.fromEntries(
+ Object.entries(files).map(([name, bytes]) => {
+ const plain = base64(bytes);
+ const compressed = base64(deflateSync(bytes, { level: 6 }));
+ return [
+ name,
+ compressed.length + 64 < plain.length
+ ? { encoding: 'kiln.deflate-base64.v1' as const, data: compressed }
+ : plain,
+ ];
+ }),
+ );
+}
+function object(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === 'object' && !Array.isArray(value);
+}
+export async function decodeWidgetAsset(value: unknown): Promise<{
+ record: AssetRecord;
+ downloadUrls: Record<string, string>;
+}> {
+ if (!object(value)) return invalid('metadata is missing');
+ if (typeof value.error === 'string') throw new Error(value.error);
+ const parsed = assetManifestSchema.safeParse(value.manifest);
+ if (!parsed.success || !object(value.files)) return invalid('metadata is malformed');
+ const manifest = parsed.data;
+ const entries = Object.entries(value.files);
+ if (!entries.length || entries.length > 16 || !Object.hasOwn(value.files, 'asset.glb'))
+ return invalid('file list is missing or invalid');
+ let declaredBytes = 0;
+ let encodedBytes = 0;
+ for (const [name, entry] of entries) {
+ if (!/^[a-z0-9][a-z0-9._-]{0,127}$/.test(name) || !Object.hasOwn(manifest.files, name))
+ return invalid('file metadata is missing');
+ declaredBytes += manifest.files[name]!.bytes;
+ if (declaredBytes > WIDGET_TRANSFER_LIMIT) return invalid('exceeds the decoded size limit');
+ const data = typeof entry === 'string' ? entry : object(entry) ? entry.data : undefined;
+ if (typeof data !== 'string') return invalid('file encoding is malformed');
+ encodedBytes += data.length;
+ if (encodedBytes > ENCODED_LIMIT) return invalid('exceeds the encoded size limit');
+ }
+ // A fixed output buffer bounds allocation even when the compressed stream lies
+ // about its expansion. The extra byte detects expansion beyond the manifest.
+ const files: AssetRecord['files'] = {};
+ for (const [name, entry] of entries) {
+ const expected = manifest.files[name]!;
+ let bytes: Uint8Array;
+ if (typeof entry === 'string') bytes = unbase64(entry);
+ else {
+ if (!object(entry) || entry.encoding !== 'kiln.deflate-base64.v1')
+ return invalid('encoding is unsupported');
+ const compressed = unbase64(entry.data);
+ try {
+ bytes = inflateSync(compressed, { out: new Uint8Array(expected.bytes + 1) });
+ } catch {
+ return invalid('compressed data is damaged');
+ }
+ }
+ if (bytes.length !== expected.bytes) return invalid('byte count does not match the saved file');
+ const digest = await crypto.subtle.digest('SHA-256', Uint8Array.from(bytes));
+ const hex = Array.from(new Uint8Array(digest), (byte) =>
+ byte.toString(16).padStart(2, '0'),
+ ).join('');
+ if (`sha256:${hex}` !== expected.sha256) return invalid('integrity check failed');
+ files[name] = bytes;
+ }
+ for (const name of Object.keys(manifest.files))
+ if (!Object.hasOwn(files, name)) return invalid('is missing a saved file');
+ const downloadUrls: Record<string, string> = {};
+ if (value.downloadUrls !== undefined) {
+ if (!object(value.downloadUrls)) return invalid('download metadata is malformed');
+ for (const [name, url] of Object.entries(value.downloadUrls)) {
+ if (typeof url !== 'string') return invalid('download metadata is malformed');
+ downloadUrls[name] = url;
+ }
+ }
+ return { record: { manifest, files }, downloadUrls };
+}