Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(i18n): stop translations from turning escaped code samples into live elements
nirholasd86ab53390b1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ad5a2aaa1..c0ca76303 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-07-27- **3D generations that run long now hand back a handle instead of an error** — A detailed model can take several minutes, longer than an assistant will wait inside a single tool call. Those generations used to look like failures even though the GPU finished the model minutes later. The ChatGPT 3D Studio now returns a live handle with a countdown of how much time is left, and a new check_job tool collects the finished model when it lands. Poll responses carry elapsed time and a remaining estimate that counts down, the assistant sees progress instead of identical waiting frames, and the inline viewer shows a real "still rendering" panel rather than an empty one. A generation whose GPU worker dies mid-job is now automatically retried on a healthy engine instead of being written off, including when nobody is watching the page. (`/docs/mcp-studio`) `[improvement, fix]`+- **A translation run can no longer fail quietly into English** — If the translation service was unreachable when a language was being built, the pipeline filled the gaps with the original English and finished reporting success. Nothing flagged it: the language looked complete, passed every check, and stayed in the language picker while reading as English. That is now impossible. A missing credential is recognised as a setup problem rather than a bad sentence, so the run stops immediately with the one line explaining what to fix, and everything already translated is kept. The pipeline also reads its credentials from the project's own configuration now, which is what made the failure so easy to trigger in the first place. `[fix, infra]`- **Chat works again: every built-in model had been retired** — The AI provider behind three.ws's free chat models retired all five of the built-in models at once, without notice. Because the model names were written into the app, every new conversation opened on a model that no longer existed, and the first message anyone sent came back as "This model is unavailable for free" instead of an answer. Chat now reads the list of working models from the provider directly, every time, and opens on one that is actually running. If a model is retired mid-conversation, the request quietly rolls over to a working one instead of failing. The same fix covers the model pickers on the avatar, brain, embed and dashboard pages, which were offering the same dead models. (`/chat`) `[fix]`- **Every 3D service we sell to other agents now ships parameters and a worked example** — The service catalog three.ws publishes to the OKX.AI agent marketplace describes all eleven 3D services the same way: what it does, exactly what you provide numbered one by one, and a concrete example of a real request. Buying agents (and the humans reading over their shoulder) can now tell what a service takes before spending anything, and the free catalog endpoint serves the same text the marketplace listing shows. (`/docs/okx-marketplace`) `[improvement, docs]`- **Every asset address in our docs and API examples now actually loads** — For a long time our developer documentation, API response examples, and the skill file that AI agents read to embed a 3D avatar all pointed model and image URLs at an address that does not exist: there was never a DNS record behind it. Copy one of those examples and you got a connection failure, and an agent following the embed instructions produced a body URL that could never load. It appeared 181 times across 55 files, including every code sample in the 3D and MCP API references. All of them now point at the asset CDN we actually run, which serves the same files from three.ws itself, allows any site to load them, and caches at the edge for a month. The Spatial MCP reference page moved onto it too, which fixes something subtle: it had been loading its example model from a storage origin that is rate-limited and only answers requests from our own domain, so anyone copying that example to prove the standard is portable was blocked by the very page meant to demonstrate portability. A new check refuses to let a dead asset address into the codebase again, and it also pins the route the working URLs depend on, so the two cannot drift apart. `[fix, docs]`@@ -20,6 +21,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **The x402 payment lanes now stop when the treasury runs dry** — When the wallets funding the agent payment economy ran low, the tip seeder kept firing 60 payments a minute that could never settle, turning the public dance-tip endpoint into a wall of errors and burning network calls for nothing. It now reads both wallet balances once before each round and simply sits the round out when a payment cannot succeed, with the reason stated plainly in the response. When the payer holds enough for some but not all of a round, it now sends exactly the number it can afford instead of overshooting. An unreadable balance is treated as unknown rather than empty, so a momentary network hiccup can never stall the economy on its own. `[fix, infra]`- **Trading agents can no longer earn a bigger bet while losing money** — The self-tuning loop judged each strategy on its average percentage return and win rate, which treat a tiny position and a large one as equal. A strategy could post a healthy-looking win rate while its biggest trades bled real SOL, and get rewarded with an even bigger position. The optimizer now shrinks a strategy whose average percentage is positive but whose actual profit is negative, since that pattern only occurs when the larger bets are the losing ones, and it refuses to scale any strategy up while it is down money. (`/blog/autonomous-trading-experiment`) `[improvement]`- **Trading agents no longer lose slots to settled trades** — A trade that sold successfully but whose confirmation timed out could get stuck: the agent kept treating the finished position as live, which used up one of its limited slots for new trades. Five positions were stuck at once, one for over 40 hours, leaving parts of the fleet unable to trade. Finished trades are now recognised from their on-chain record, a stuck position is released automatically instead of waiting forever, and the database itself now refuses to move a settled trade back to open. (`/sniper/experiments`) `[fix]`+- **Translated pages no longer turn code samples into live 3D avatars** — Our pages are written in English and machine-translated into 50 languages. When a page prints a code sample, the sample is stored in an escaped form so the browser shows it as text instead of running it. The translator did not know that, and on 289 pieces of copy across 46 languages it quietly un-escaped them. The worst case: a documentation page showing readers how to write the <agent-3d> embed tag stopped printing the tag and started running it, so a live 3D avatar appeared in the middle of the instructions and the sentence after it disappeared. Every one of those has been repaired, the translator now treats escaped markup as untouchable the same way it already protects $THREE and wallet addresses, and a new build check refuses to ship a translation whose markup does not match the English. `[fix, docs]`- **Translations repaired: whole pages were quietly still in English** — A stretch of the site's translated copy was never actually translated. When the translation service was unreachable, the pipeline wrote the English text into each language file as a placeholder, and because the text was technically present, every later run skipped it. Punjabi was the worst case: the language was offered in the picker but read as English from top to bottom. Punjabi is now fully translated, and the same repair is running across the other languages, covering tens of thousands of phrases that had been sitting in English. There is also a new maintenance command that finds this class of gap, so a language can no longer look complete while reading in English. `[fix, improvement]`## 2026-07-26diff --git a/data/changelog.json b/data/changelog.jsonindex 208fc18ee..c31abc21f 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,24 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-27",+ "title": "Translated pages no longer turn code samples into live 3D avatars",+ "summary": "Our pages are written in English and machine-translated into 50 languages. When a page prints a code sample, the sample is stored in an escaped form so the browser shows it as text instead of running it. The translator did not know that, and on 289 pieces of copy across 46 languages it quietly un-escaped them. The worst case: a documentation page showing readers how to write the <agent-3d> embed tag stopped printing the tag and started running it, so a live 3D avatar appeared in the middle of the instructions and the sentence after it disappeared. Every one of those has been repaired, the translator now treats escaped markup as untouchable the same way it already protects $THREE and wallet addresses, and a new build check refuses to ship a translation whose markup does not match the English.",+ "tags": [+ "fix",+ "docs"+ ]+ },+ {+ "date": "2026-07-27",+ "title": "A translation run can no longer fail quietly into English",+ "summary": "If the translation service was unreachable when a language was being built, the pipeline filled the gaps with the original English and finished reporting success. Nothing flagged it: the language looked complete, passed every check, and stayed in the language picker while reading as English. That is now impossible. A missing credential is recognised as a setup problem rather than a bad sentence, so the run stops immediately with the one line explaining what to fix, and everything already translated is kept. The pipeline also reads its credentials from the project's own configuration now, which is what made the failure so easy to trigger in the first place.",+ "tags": [+ "fix",+ "infra"+ ]+ },{"date": "2026-07-27","title": "Chat works again: every built-in model had been retired",diff --git a/docs/i18n.md b/docs/i18n.mdindex cc8cb2e51..cb541173f 100644--- a/docs/i18n.md+++ b/docs/i18n.md@@ -74,55 +74,97 @@ string. Collisions (same key, different English in two files) fail the command.## 3. Translate```bash-npm run i18n:translate # translate only missing keys, every locale (incremental)-npm run i18n:translate -- --locale=es # one locale-npm run i18n:translate -- --force # retranslate everything-npm run i18n:translate -- --dry-run # show what would translate (also refreshes manifest)-npm run i18n # extract + translate+npm run i18n:translate # translate only missing keys, every locale (incremental)+npm run i18n:translate -- --locale=es # one locale+npm run i18n:translate -- --force # retranslate everything+npm run i18n:translate -- --dry-run # show what would translate (also refreshes manifest)+npm run i18n:translate -- --concurrency=8 # widen the chunk pool for a bulk run+npm run i18n # extract + translate```Configuration lives in [`.i18nrc.json`](../.i18nrc.json) (schema:[`scripts/i18n-rc.schema.json`](../scripts/i18n-rc.schema.json)). Backend is-selected by `provider`. **The default is a free model — no card, no credits.**+selected by `provider`, overridable per run with `--provider=` / `--model=`.Env-var names match [`api/_lib/chat-models.js`](../api/_lib/chat-models.js), so a-key that already powers `/chat` works here too. Set just one:--| provider | free? | env var | get a key |-| ---------------- | ------- | -------------------------------------- | ---------------------------------------------------------- |-| `groq` (default) | ✅ free | `GROQ_API_KEY` | <https://console.groq.com/keys> — Llama 3.3 70B, fast |-| `gemini` | ✅ free | `GEMINI_API_KEY` / `GOOGLE_API_KEY` | <https://aistudio.google.com/apikey> — free tier, best CJK |-| `openrouter` | ✅ free | `OPENROUTER_API_KEY` | <https://openrouter.ai/keys> — use a `:free` model |-| `nvidia` | ✅ free | `NVIDIA_API_KEY` | <https://build.nvidia.com> — free NIM credits |-| `openai` | paid | `OPENAI_API_KEY` (+ `OPENAI_BASE_URL`) | any OpenAI-compatible endpoint |-| `anthropic` | paid | `ANTHROPIC_API_KEY` | Claude Messages API |--```bash-export GROQ_API_KEY=... # free; the default provider-npm run i18n:translate # done-```+key that already powers `/chat` works here too. `.env` and `.env.local` are read+automatically - an exported variable still wins, so a one-off+`GEMINI_API_KEY=… npm run i18n:translate` overrides the file.++| provider | free? | credentials | notes |+| ------------------ | ------- | -------------------------------------- | ----------------------------------------------------------- |+| `vertex` (default) | credits | `GOOGLE_CLOUD_PROJECT` + GCP auth | billed to the platform's GCP credits; no free-tier quota wall |+| `gemini` | ✅ free | `GEMINI_API_KEY` / `GOOGLE_API_KEY` | <https://aistudio.google.com/apikey> - free tier, best CJK |+| `groq` | ✅ free | `GROQ_API_KEY` | <https://console.groq.com/keys> - Llama 3.3 70B, fast |+| `openrouter` | ✅ free | `OPENROUTER_API_KEY` | <https://openrouter.ai/keys> - use a `:free` model |+| `nvidia` | ✅ free | `NVIDIA_API_KEY` | <https://build.nvidia.com> - free NIM credits |+| `openai` | paid | `OPENAI_API_KEY` (+ `OPENAI_BASE_URL`) | any OpenAI-compatible endpoint |+| `anthropic` | paid | `ANTHROPIC_API_KEY` | Claude Messages API |++Vertex takes GCP credentials three ways, in order: `GCP_SERVICE_ACCOUNT_JSON`,+the Cloud Run / GCE metadata server, then the `gcloud` CLI. On a developer+machine the first two are absent, so an authenticated `gcloud auth login` is all+it needs. If none of the three resolve, the run **aborts** rather than degrading+(see *Never silently English* below).++An `OPENROUTER_API_KEY` in the environment is automatically added as a failover+rung behind whichever provider is primary, so a single 429 wall does not end a run.Leave `modelName` unset to use the provider's default model, or pin one (e.g.`"modelName": "meta-llama/llama-3.3-70b-instruct:free"` for OpenRouter). Freetiers rate-limit, so `concurrency` defaults to `2` and the translator backs off-and retries on HTTP 429 (honoring `Retry-After`).+and retries on HTTP 429 (honoring `Retry-After`). A Vertex run billed to our own+project has far more headroom - pass `--concurrency=8` for a bulk job like+generating a locale from scratch (~550 chunks) instead of editing the config+every other lane shares.++### Never silently English++When a translation call fails, the pipeline bakes the English source into the+key so the catalog stays complete and the runtime degrades gracefully. That is+right for the occasional value a model can't render as valid JSON, and very+wrong for a missing credential, which fails **identically on every key**: the run+would march through the whole catalog rewriting it into English and exit 0, with+lint green and the language still offered in the picker. So a credential/config+error is classified separately - it is never retried, never baked, and aborts the+run with the one line that says what to fix. Everything already translated is+kept (the pipeline persists after each chunk) and a re-run resumes.++`i18n:backfill` (below) exists to clean up catalogs damaged by this before the+guard existed.> **Quality note:** Llama 3.3 70B (Groq) is solid for Latin-script languages. For-> CJK/Arabic/Hindi, the **Gemini free tier** (`provider: "gemini"`) is noticeably-> better and still free — switch per run with no code change. Whatever you pick,-> `npm run i18n:lint` catches any model that drops a placeholder or glossary term.->-> Have GCP credits and want Vertex AI? Point `OPENAI_BASE_URL` at a Vertex-> OpenAI-compatible gateway with `provider: "openai"`.+> CJK/Arabic/Hindi, Gemini (free tier or Vertex) is noticeably better - switch per+> run with no code change. Whatever you pick, `npm run i18n:lint` catches any model+> that drops a placeholder, a glossary term, or a tag.### Glossary lock (the important part)Terms in `doNotTranslate` — `$THREE`, the contract address, `x402`, `USDC`,-`Solana`, `IBM watsonx.ai`, etc. — plus every `{{placeholder}}` and HTML tag are-**masked to opaque sentinels before the text reaches the model and restored-after**. The model literally never sees them, so they come back byte-for-byte and-can never be translated, reordered, or hallucinated around. `$THREE` is the only-coin this platform references; this guarantees no machine translation can change-that.+`Solana`, `IBM watsonx.ai`, etc. - plus every `{{placeholder}}`, HTML tag, and+HTML entity are **masked to opaque sentinels before the text reaches the model+and restored after**. The model literally never sees them, so they come back+byte-for-byte and can never be translated, reordered, or hallucinated around.+`$THREE` is the only coin this platform references; this guarantees no machine+translation can change that.++Entities are masked for a reason that is easy to miss. A value harvested from a+`data-i18n-html` element is **raw markup**, and the runtime puts it back through+`innerHTML`. So `<` is source syntax, not typography: a model that helpfully+decodes++```html+<code><agent-3d></code> <!-- a printed code sample -->+```++into++```html+<code><agent-3d></code> <!-- a live custom element -->+```++has just instantiated a 3D avatar in the middle of the SDK docs and swallowed the+copy that followed. Masking makes the round trip byte-exact; the lint rule below+catches any that predate it.## 4. Lint (build gate)@@ -131,8 +173,16 @@ npm run i18n:lint```Validates every **committed** locale against the source: no missing/empty keys,-no `{{placeholder}}` drift, no dropped glossary terms, no stale keys. Locales not-yet generated are skipped (not failures). Needs no API key — safe in CI.+no `{{placeholder}}` drift, no dropped glossary terms, no stale keys, and no+**markup drift**. Locales not yet generated are skipped (not failures). Needs no+API key - safe in CI.++Markup drift compares the set of HTML tags in the translation against the source.+It fires when a translation grows a tag the English never had (an escaped tag that+got decoded into a live element, or one the model invented) or loses one it should+have kept. It deliberately stays quiet on cosmetic entities: `&`, `—`+and `'` decode to the same glyph the reader sees either way, so flagging them+would bury the failures that actually break a page.### Repair (fix lint failures in place)@@ -141,11 +191,12 @@ npm run i18n:repair # every localenpm run i18n:repair -- --locale=he # one locale```-Glossary terms and `{{placeholders}}` are masked to sentinels the model must-reproduce verbatim. A small model occasionally omits a sentinel mid-sentence, so-the term never gets restored and the key fails lint. `--repair` re-translates-**only** the lint-failing keys, one at a time, retrying each until it passes its-own integrity check. A key that never converges after four attempts is baked to+Glossary terms, `{{placeholders}}`, tags, and entities are masked to sentinels+the model must reproduce verbatim. A small model occasionally omits a sentinel+mid-sentence, so the term never gets restored and the key fails lint. `--repair`+re-translates **only** the lint-failing keys (dropped glossary term, placeholder+drift, or markup drift), one at a time, retrying each until it passes its own+integrity check. A key that never converges after four attempts is baked toEnglish (lint-clean, and the runtime already falls back to English for anythingmissing). Idempotent: a clean catalog reports `nothing to repair`. Takes the same`--provider=` / `--model=` overrides as `i18n:translate`.@@ -239,10 +290,35 @@ console.log('keys',n(f),'of',n(e),'| empty',m)"Re-running `i18n:translate` is the fix: `missingKeys()` treats an empty string asuntranslated, so a resumed run tops up exactly the gaps and costs nothing for the-keys already done. For a catalog that is complete but trips the glossary/placeholder-lint, `npm run i18n:repair -- --locale=<code>` re-translates only the failing keys.-A locale that cannot be completed should be left out of `outputLocales` entirely-rather than committed partial, so the switcher never offers it.+keys already done. For a catalog that is complete but trips the+glossary/placeholder/markup lint, `npm run i18n:repair -- --locale=<code>`+re-translates only the failing keys.++Shipping is gated on completeness rather than on your memory: every run rewrites+`public/locales/manifest.json` and **omits any locale with untranslated keys**, so+a half-built catalog is never offered in the switcher. That is what makes a+from-scratch locale safe to build incrementally across several sessions.++### Building the locales that have never been generated++`outputLocales` is deliberately longer than the shipped set. To work through the+backlog:++```bash+scripts/i18n-generate-queue.sh # every incomplete locale, 5 at a time+scripts/i18n-generate-queue.sh 3 # narrower pool+scripts/i18n-generate-queue.sh 5 "ca sr my" # a specific list, in order+```++Each locale is ~18k keys / ~430 chunks, so this is an hours-long job, not a+minutes-long one. It picks locales **most-complete-first** (closest to shipping+ships soonest), skips any locale another process is already translating (two+writers on one catalog would lose one set of writes), and is resumable: the+translator persists after every chunk, so a killed queue loses at most one chunk.++> **Concurrent agents share this worktree.** Before starting a bulk run, check+> `ps -eo args | grep i18n-` - a locale being written by someone else's backfill+> must not also be written by you.## SEO: hreflang alternates@@ -270,3 +346,8 @@ English flash) is the natural next step; the catalogs are static and ready.[`tests/i18n.test.js`](../tests/i18n.test.js) covers extraction, glossaryround-trips, lint rules, runtime resolution/fallback, and catalog merge/prune.+[`tests/i18n-markup.test.js`](../tests/i18n-markup.test.js) pins the markup+guarantees: entities survive a round trip byte-for-byte, an escaped tag that got+decoded into a live element fails lint, and cosmetic entities do not.+[`tests/i18n-backfill.test.js`](../tests/i18n-backfill.test.js) pins the rules for+clearing silently-English values out of a shipped catalog.diff --git a/public/changelog.json b/public/changelog.jsonindex 91d045dcb..a0dff9706 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-27T19:22:39.867Z",+ "generated_at": "2026-07-27T20:59:24.845Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -17,6 +17,17 @@"fix"]},+ {+ "date": "2026-07-27",+ "type": "update",+ "title": "A translation run can no longer fail quietly into English",+ "summary": "If the translation service was unreachable when a language was being built, the pipeline filled the gaps with the original English and finished reporting success. Nothing flagged it: the language looked complete, passed every check, and stayed in the language picker while reading as English. That is now impossible. A missing credential is recognised as a setup problem rather than a bad sentence, so the run stops immediately with the one line explaining what to fix, and everything already translated is kept. The pipeline also reads its credentials from the project's own configuration now, which is what made the failure so easy to trigger in the first place.",+ "link": null,+ "tags": [+ "fix",+ "infra"+ ]+ },{"date": "2026-07-27","type": "update",@@ -155,6 +166,17 @@"fix"]},+ {+ "date": "2026-07-27",+ "type": "update",+ "title": "Translated pages no longer turn code samples into live 3D avatars",+ "summary": "Our pages are written in English and machine-translated into 50 languages. When a page prints a code sample, the sample is stored in an escaped form so the browser shows it as text instead of running it. The translator did not know that, and on 289 pieces of copy across 46 languages it quietly un-escaped them. The worst case: a documentation page showing readers how to write the <agent-3d> embed tag stopped printing the tag and started running it, so a live 3D avatar appeared in the middle of the instructions and the sentence after it disappeared. Every one of those has been repaired, the translator now treats escaped markup as untouchable the same way it already protects $THREE and wallet addresses, and a new build check refuses to ship a translation whose markup does not match the English.",+ "link": null,+ "tags": [+ "fix",+ "docs"+ ]+ },{"date": "2026-07-27","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex cb6432e5a..92910e866 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -14,6 +14,14 @@<category>improvement</category><description>A detailed model can take several minutes, longer than an assistant will wait inside a single tool call. Those generations used to look like failures even though the GPU finished the model minutes later. The ChatGPT 3D Studio now returns a live handle with a countdown of how much time is left, and a new check_job tool collects the finished model when it lands. Poll responses carry elapsed time and a remaining estimate that counts down, the assistant sees progress instead of identical waiting frames, and the inline viewer shows a real "still rendering" panel rather than an empty one. A generation whose GPU worker dies mid-job is now automatically retried on a healthy engine instead of being written off, including when nobody is watching the page.</description></item>+ <item>+ <title>A translation run can no longer fail quietly into English</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-07-27:A translation run can no longer fail quietly into English</guid>+ <pubDate>Mon, 27 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>If the translation service was unreachable when a language was being built, the pipeline filled the gaps with the original English and finished reporting success. Nothing flagged it: the language looked complete, passed every check, and stayed in the language picker while reading as English. That is now impossible. A missing credential is recognised as a setup problem rather than a bad sentence, so the run stops immediately with the one line explaining what to fix, and everything already translated is kept. The pipeline also reads its credentials from the project's own configuration now, which is what made the failure so easy to trigger in the first place.</description>+ </item><item><title>Chat works again: every built-in model had been retired</title><link>https://three.ws/chat</link>@@ -118,6 +126,14 @@<category>fix</category><description>A trade that sold successfully but whose confirmation timed out could get stuck: the agent kept treating the finished position as live, which used up one of its limited slots for new trades. Five positions were stuck at once, one for over 40 hours, leaving parts of the fleet unable to trade. Finished trades are now recognised from their on-chain record, a stuck position is released automatically instead of waiting forever, and the database itself now refuses to move a settled trade back to open.</description></item>+ <item>+ <title>Translated pages no longer turn code samples into live 3D avatars</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-07-27:Translated pages no longer turn code samples into live 3D avatars</guid>+ <pubDate>Mon, 27 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Our pages are written in English and machine-translated into 50 languages. When a page prints a code sample, the sample is stored in an escaped form so the browser shows it as text instead of running it. The translator did not know that, and on 289 pieces of copy across 46 languages it quietly un-escaped them. The worst case: a documentation page showing readers how to write the <agent-3d> embed tag stopped printing the tag and started running it, so a live 3D avatar appeared in the middle of the instructions and the sentence after it disappeared. Every one of those has been repaired, the translator now treats escaped markup as untouchable the same way it already protects $THREE and wallet addresses, and a new build check refuses to ship a translation whose markup does not match the English.</description>+ </item><item><title>Translations repaired: whole pages were quietly still in English</title><link>https://three.ws/changelog</link>diff --git a/scripts/i18n-generate-queue.sh b/scripts/i18n-generate-queue.shnew file mode 100755index 000000000..02dbe518b--- /dev/null+++ b/scripts/i18n-generate-queue.sh@@ -0,0 +1,83 @@+#!/usr/bin/env bash+# i18n-generate-queue - build the configured-but-never-generated locales, N at a time.+#+# `.i18nrc.json` lists 84 output locales; only the ones with a committed catalog+# ship (public/locales/manifest.json holds back anything incomplete, so a locale+# mid-build is never offered in the picker). Generating one from scratch is+# ~18k keys / ~430 chunks, so this runs a small pool rather than 30-odd node+# processes fighting over the same Vertex quota.+#+# Resumable by construction: the translator persists after every chunk and only+# fills keys that are missing, so a killed run loses at most one chunk and+# re-running continues where it stopped.+#+# Usage:+# scripts/i18n-generate-queue.sh # every ungenerated locale, 5 at a time+# scripts/i18n-generate-queue.sh 3 # 5 → 3 concurrent locales+# scripts/i18n-generate-queue.sh 5 "ca sr my" # only these, in this order+set -uo pipefail+cd "$(dirname "$0")/.."++WORKERS="${1:-5}"+LOG_DIR="${I18N_QUEUE_LOG_DIR:-/tmp/i18n-generate}"+mkdir -p "$LOG_DIR"++if [ $# -ge 2 ]; then+ QUEUE="$2"+else+ # Every configured locale that is missing keys - not merely every locale with+ # no file. A run interrupted halfway leaves a partial catalog behind, and+ # selecting on file existence would skip exactly the locales that still need+ # work. Most-complete first, so languages closest to shipping ship soonest.+ QUEUE=$(node -e '+ const cfg = require("./.i18nrc.json");+ const { existsSync, readFileSync } = require("node:fs");+ const flat = (n, p = "", o = {}) => {+ for (const [k, v] of Object.entries(n || {})) {+ const q = p ? `${p}.${k}` : k;+ if (v && typeof v === "object") flat(v, q, o);+ else if (typeof v === "string") o[q] = v;+ }+ return o;+ };+ const src = flat(JSON.parse(readFileSync(cfg.entry, "utf8")));+ const keys = Object.keys(src);+ const missing = (code) => {+ const p = `${cfg.output}/${code}.json`;+ if (!existsSync(p)) return keys.length;+ const t = flat(JSON.parse(readFileSync(p, "utf8")));+ return keys.filter((k) => !t[k] || !String(t[k]).trim()).length;+ };+ const todo = cfg.outputLocales+ .map((code) => ({ code, n: missing(code) }))+ .filter((x) => x.n > 0)+ .sort((a, b) => a.n - b.n);+ console.log(todo.map((x) => x.code).join(" "));+ ')+fi++# Never queue a locale another process is already translating: both would write+# the same catalog file and one set of writes would be lost.+INFLIGHT=$(ps -eo args | grep -oE 'i18n-translate\.mjs --locale=[a-zA-Z-]+' | grep -oE '[^=]+$' | sort -u)+for BUSY in $INFLIGHT; do+ QUEUE=$(echo " $QUEUE " | sed "s/ $BUSY / /g")+done++if [ -z "${QUEUE// /}" ]; then+ echo "i18n-generate-queue: every configured locale already has a catalog."+ exit 0+fi++echo "i18n-generate-queue: $(echo "$QUEUE" | wc -w) locale(s), $WORKERS at a time, logs in $LOG_DIR"++for L in $QUEUE; do+ while [ "$(pgrep -fc 'i18n-translate\.mjs --locale=' || true)" -ge "$WORKERS" ]; do+ sleep 20+ done+ echo "[start] $L ($(date -u +%H:%M:%S)Z)"+ nohup node scripts/i18n-translate.mjs --locale="$L" --concurrency=8 > "$LOG_DIR/$L.log" 2>&1 &+ sleep 5+done++wait+echo "i18n-generate-queue: done ($(date -u +%H:%M:%S)Z)"diff --git a/scripts/i18n-translate.mjs b/scripts/i18n-translate.mjsindex b1c499641..12856bcd2 100644--- a/scripts/i18n-translate.mjs+++ b/scripts/i18n-translate.mjs@@ -24,10 +24,13 @@// node scripts/i18n-translate.mjs --locale=es # one locale// node scripts/i18n-translate.mjs --force # retranslate everything// node scripts/i18n-translate.mjs --lint # validate only (build gate, no API key needed)+// node scripts/i18n-translate.mjs --repair # re-translate only lint-failing keys// node scripts/i18n-translate.mjs --dry-run # report what would translate+// node scripts/i18n-translate.mjs --concurrency=8 # widen the chunk pool for a bulk runimport { writeFileSync, existsSync } from 'node:fs';import { resolve } from 'node:path';+import { config as dotenv } from 'dotenv';import JSON5 from 'json5';import {ROOT,@@ -41,8 +44,18 @@ import {mergeOrdered,buildMasker,lintLocale,+ markupDrift,} from './lib/i18n-shared.mjs';+// The backend credentials live in .env alongside every other platform secret.+// Without this the default provider (vertex) has no project, every call fails+// its config check, and the run bakes English into the whole catalog - the+// silent-English failure `i18n:backfill` exists to clean up afterwards. dotenv+// never overrides a var already exported, so a one-off `GEMINI_API_KEY=… npm+// run i18n:translate` still wins.+dotenv({ path: new URL('../.env', import.meta.url), quiet: true });+dotenv({ path: new URL('../.env.local', import.meta.url), quiet: true });+const args = process.argv.slice(2);const flag = (name) => args.includes(`--${name}`);const opt = (name) => {@@ -56,6 +69,11 @@ const cfg = loadConfig();// --model=openai/gpt-4o-mini when the default GCP/Vertex path is unavailable).if (opt('provider')) cfg.provider = opt('provider');if (opt('model')) cfg.modelName = opt('model');+// The committed concurrency is tuned for free-tier lanes that rate-limit hard.+// A Vertex run billed to the platform's own project has far more headroom, and+// a from-scratch locale is ~550 chunks, so let a bulk run open it up without+// editing the config every other lane still depends on.+if (opt('concurrency')) cfg.concurrency = Math.max(1, Number(opt('concurrency')) || cfg.concurrency);const sourcePath = resolve(ROOT, cfg.entry);const source = readJSON(sourcePath);if (!source) {@@ -172,6 +190,17 @@ function httpError(provider, status, body, retryAfter) {});}+/**+ * A backend that is not configured at all - no key, no project. Distinct from a+ * key the model choked on, and it must never be treated like one: the per-key+ * fallback bakes the English source, so an unconfigured provider would quietly+ * rewrite an entire catalog into English and leave lint green. Marked so the+ * run can abort instead.+ */+function configError(message) {+ return Object.assign(new Error(message), { isConfigError: true });+}+function modelName() {return cfg.modelName || PROVIDER_DEFAULT_MODEL[cfg.provider] || PROVIDER_DEFAULT_MODEL.gemini;}@@ -207,7 +236,7 @@ async function callGemini(prompt) {process.env.GOOGLE_API_KEY ||process.env.GOOGLE_GENAI_API_KEY;if (!key)- throw new Error(+ throw configError('GEMINI_API_KEY (or GOOGLE_API_KEY) not set — free keys: https://aistudio.google.com/apikey',);const url = `https://generativelanguage.googleapis.com/v1beta/models/${modelName()}:generateContent?key=${key}`;@@ -238,7 +267,7 @@ async function callGemini(prompt) {async function callAnthropic(prompt) {const key = process.env.ANTHROPIC_API_KEY;- if (!key) throw new Error('ANTHROPIC_API_KEY not set');+ if (!key) throw configError('ANTHROPIC_API_KEY not set');const res = await fetch('https://api.anthropic.com/v1/messages', {method: 'POST',headers: {@@ -278,19 +307,47 @@ async function callAnthropic(prompt) {// max_tokens (as the chat-completion callers elsewhere use) can burn the// whole budget on reasoning and return empty content with// finish_reason:"length". Use a generous ceiling, matching callAnthropic's.+// Mint a Vertex access token, preferring the same service-account path every+// other platform Vertex caller uses. That path is built for Cloud Run and+// Vercel, where a service account is attached or pasted into the environment;+// on a developer machine neither exists, but an authenticated `gcloud` almost+// always does. Falling back to the CLI is what makes the committed default+// provider actually runnable locally instead of failing into English.+let _cliToken = { value: null, expiresAt: 0 };+async function vertexToken() {+ try {+ const { getGcpAccessToken } = await import('../api/_lib/gcp-auth.js');+ return await getGcpAccessToken();+ } catch (err) {+ if (err?.code !== 'unconfigured') throw err;+ }+ if (_cliToken.value && Date.now() < _cliToken.expiresAt) return _cliToken.value;+ const { spawnSync } = await import('node:child_process');+ const out = spawnSync('gcloud', ['auth', 'print-access-token'], { encoding: 'utf8' });+ const token = out.status === 0 && out.stdout.trim();+ if (!token) {+ throw configError(+ 'No GCP credentials for vertex: set GCP_SERVICE_ACCOUNT_JSON, or run `gcloud auth login` ' ++ '(the CLI token is used automatically). Alternatively pass --provider=gemini with GOOGLE_API_KEY set.',+ );+ }+ // gcloud tokens last an hour; re-shell every 45 minutes rather than per call.+ _cliToken = { value: token, expiresAt: Date.now() + 45 * 60 * 1000 };+ return token;+}+async function callVertex(prompt) {const project = process.env.GOOGLE_CLOUD_PROJECT;if (!project) {- throw new Error(+ throw configError('GOOGLE_CLOUD_PROJECT not set — vertex needs the same GCP project + credentials ' +'(GCP_SERVICE_ACCOUNT_JSON, or the Cloud Run/GCE metadata server) as the rest of the ' +'platform\'s Vertex AI callers.',);}- const { getGcpAccessToken } = await import('../api/_lib/gcp-auth.js');const location = process.env.GOOGLE_CLOUD_LOCATION_GEMINI || 'global';const host = location === 'global' ? 'aiplatform.googleapis.com' : `${location}-aiplatform.googleapis.com`;- const token = await getGcpAccessToken();+ const token = await vertexToken();const res = await fetch(`https://${host}/v1beta1/projects/${project}/locations/${location}/endpoints/openapi/chat/completions`,{@@ -319,7 +376,7 @@ async function callVertex(prompt) {async function callOpenAICompat(prompt, providerName = cfg.provider, modelOverride = null) {const spec = OPENAI_COMPAT[providerName];const key = process.env[spec.envKey];- if (!key) throw new Error(`${spec.envKey} not set`);+ if (!key) throw configError(`${spec.envKey} not set`);const body = {model: modelOverride || modelName(),temperature: cfg.temperature ?? 0.2,@@ -407,6 +464,9 @@ async function callBackendWithRetry(call, langName, payload, attempt = 0) {if (!parsed || typeof parsed !== 'object') throw new Error('non-object response');return parsed;} catch (err) {+ // A missing key or project is not transient - retrying it just burns the+ // backoff budget on an outcome that cannot change.+ if (err?.isConfigError) throw err;// Free tiers rate-limit hard; honor Retry-After and back off more on a 429// than on a transient parse/5xx error.const max = err.status === 429 ? 5 : 2;@@ -502,6 +562,13 @@ async function translateLocale(code) {try {out = await translateChunk(langName, payload);} catch (err) {+ // An unconfigured backend fails identically on every key, so the+ // per-key English fallback below would march through the entire+ // catalog rewriting it into English and finish "successfully". Fail+ // the run instead: nothing already translated is lost (the pipeline+ // persists after each chunk) and the operator gets the one line that+ // actually tells them what to fix.+ if (err?.isConfigError) throw err;if (keys.length > 1) {const mid = Math.ceil(keys.length / 2);await translateKeySet(keys.slice(0, mid));@@ -608,12 +675,18 @@ async function repairLocale(code, maxAttempts = 4) {console.log(`◦ ${code}: not generated yet (skipped)`);return { code, repaired: 0, baked: 0 };}- // Only keys whose current value drops a glossary term or a placeholder.+ // Only keys whose current value drops a glossary term, a placeholder, or an+ // HTML entity - the three failures a re-translation reliably fixes.const problems = lintLocale(source, existing, { code, doNotTranslate: cfg.doNotTranslate });const failingKeys = [...new Set(problems- .map((p) => /(?:glossary term dropped|placeholder drift) in ([^:]+):/.exec(p)?.[1])+ .map(+ (p) =>+ /(?:glossary term dropped|placeholder drift|markup drift) in ([^:]+):/.exec(+ p,+ )?.[1],+ ).filter(Boolean),),];@@ -632,7 +705,8 @@ async function repairLocale(code, maxAttempts = 4) {}const srcVars = (sv.match(/\{\{[^}]+\}\}/g) || []).sort().join('|');const tgtVars = (value.match(/\{\{[^}]+\}\}/g) || []).sort().join('|');- return srcVars === tgtVars;+ if (srcVars !== tgtVars) return false;+ return !markupDrift(sv, value);};let repaired = 0;diff --git a/scripts/lib/i18n-shared.mjs b/scripts/lib/i18n-shared.mjsindex 82d96c8f0..9084d6614 100644--- a/scripts/lib/i18n-shared.mjs+++ b/scripts/lib/i18n-shared.mjs@@ -116,11 +116,38 @@ export function mergeOrdered(source, existing = {}, translated = {}) {const PLACEHOLDER_RE = /\{\{[^}]+\}\}/g; // {{count}}const TAG_RE = /<\/?[a-zA-Z][^>]*>/g; // <br/>, <strong>, </strong>+// HTML entities: named (< & ) and numeric (' '). Values+// extracted from `data-i18n-html` elements carry raw markup, so an entity is+// load-bearing source syntax, not decoration: a model that "helpfully" decodes+// `<50` to `<50` turns the string into a broken tag the moment the runtime+// assigns it to innerHTML. Masked like a tag so the model never sees one.+export const ENTITY_RE = /&(?:[a-zA-Z][a-zA-Z0-9]{1,31}|#\d{1,7}|#[xX][0-9a-fA-F]{1,6});/g;function escapeRe(s) {return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');}+/** Every HTML tag in a string, in a stable order, for comparing two renderings. */+export function tagSignature(text) {+ return (String(text ?? '').match(TAG_RE) || []).sort().join('');+}++/**+ * True when a translation would render different MARKUP than its source.+ *+ * This is the check that matters, and it is stricter than counting entities.+ * Values pulled from `data-i18n-html` elements go back out through innerHTML,+ * so a model that decodes `<code><agent-3d></code>` into+ * `<code><agent-3d></code>` has not made a typographic choice: it has turned a+ * printed code sample into a live custom element that instantiates a 3D avatar+ * inside the docs. Cosmetic entities (`&`, `—`, `'`) decode to+ * the same glyph the reader sees either way and are deliberately NOT flagged,+ * so the build gate only fires on drift that actually breaks a page.+ */+export function markupDrift(source, target) {+ return tagSignature(source) !== tagSignature(target);+}+export function buildMasker(doNotTranslate = []) {// Longer terms first so "IBM watsonx.ai" masks before "watsonx.ai".const terms = [...doNotTranslate].sort((a, b) => b.length - a.length);@@ -140,9 +167,12 @@ export function buildMasker(doNotTranslate = []) {return sentinel(id);});};- // Order matters: placeholders and tags first, then literal glossary terms.+ // Order matters: placeholders and tags first, then entities, then literal+ // glossary terms. Tags outrank entities so `<a href="?a=1&b=2">` is+ // stashed whole instead of being split around a nested sentinel.stash(PLACEHOLDER_RE);stash(TAG_RE);+ stash(ENTITY_RE);for (const term of terms) {if (!term) continue;stash(new RegExp(escapeRe(term), 'g'));@@ -152,7 +182,17 @@ export function buildMasker(doNotTranslate = []) {function unmask(text, tokens) {if (typeof text !== 'string') return text;- return text.replace(/\[\[T(\d+)\]\]/g, (_, i) => tokens[Number(i)] ?? '');+ // One stashed run can contain another (a tag whose href holds a+ // {{placeholder}}), and String.replace never rescans what it just+ // inserted, so restore repeatedly until the text stops changing. Bounded:+ // every pass either resolves a sentinel or the loop is already done.+ let out = text;+ for (let pass = 0; pass < 5; pass++) {+ const next = out.replace(/\[\[T(\d+)\]\]/g, (_, i) => tokens[Number(i)] ?? '');+ if (next === out) break;+ out = next;+ }+ return out;}return { mask, unmask };@@ -195,6 +235,14 @@ export function lintLocale(source, target, { code, doNotTranslate = [] } = {}) {problems.push(`[${code}] glossary term dropped in ${k}: "${term}"`);}}++ // The translation must render the same markup as the source. The `key:`+ // shape matters beyond readability - `--repair` parses these lines to+ // decide which keys to re-translate.+ if (markupDrift(sv, tv)) {+ const show = (s) => (s.match(TAG_RE) || []).join(' ').slice(0, 120) || '∅';+ problems.push(`[${code}] markup drift in ${k}: ${show(sv)} → ${show(tv)}`);+ }}for (const k of Object.keys(tgt)) {diff --git a/tests/i18n-markup.test.js b/tests/i18n-markup.test.jsnew file mode 100644index 000000000..bc7568878--- /dev/null+++ b/tests/i18n-markup.test.js@@ -0,0 +1,117 @@+/**+ * i18n markup integrity, unit tests.+ *+ * Locale values harvested from `data-i18n-html` elements are raw markup, and the+ * runtime puts them back through innerHTML. That makes an HTML entity load-bearing+ * source syntax rather than typography: a model that "helpfully" decodes+ * `<code><agent-3d></code>` into `<code><agent-3d></code>` has not changed a+ * character, it has turned a printed code sample into a live custom element that+ * instantiates a 3D avatar in the middle of the docs.+ *+ * Two properties keep that from shipping, and this file pins both:+ * 1. the masker hides entities from the model the same way it hides tags and+ * glossary terms, so a round trip is byte-identical;+ * 2. lint fails on markup drift (a tag the source never had, or one it lost)+ * while staying silent on cosmetic entities like `&` and `—`,+ * which decode to the same glyph the reader sees either way.+ */++import { describe, expect, it } from 'vitest';++import { buildMasker, lintLocale, markupDrift, tagSignature } from '../scripts/lib/i18n-shared.mjs';++const masker = buildMasker(['$THREE', 'three.ws', 'x402']);+const roundTrip = (text, translate = (s) => s) => {+ const { masked, tokens } = masker.mask(text);+ return masker.unmask(translate(masked), tokens);+};++describe('buildMasker', () => {+ it('hides entities from the model and restores them byte-for-byte', () => {+ const src = '<50<span class="unit">KB</span>';+ const { masked } = masker.mask(src);+ expect(masked).not.toContain('<');+ expect(masked).not.toContain('<span');+ expect(roundTrip(src)).toBe(src);+ });++ it('survives a translation that rewrites everything around the sentinels', () => {+ const src = 'Drop <code><agent-3d></code> into any page on three.ws';+ const out = roundTrip(src, (m) => m.replace('Drop', 'Füge').replace('into any page on', 'in jede Seite auf'));+ expect(out).toContain('<agent-3d>');+ expect(out).toContain('three.ws');+ expect(markupDrift(src, out)).toBe(false);+ });++ it('keeps a nested run intact when a tag wraps a placeholder', () => {+ const src = '<a href="{{url}}" title="R&D">{{count}} agents</a>';+ expect(roundTrip(src)).toBe(src);+ });++ it('masks numeric entities as well as named ones', () => {+ const src = 'It's live — 'now'';+ expect(masker.mask(src).masked).not.toContain('&');+ expect(roundTrip(src)).toBe(src);+ });++ it('leaves a bare ampersand alone', () => {+ expect(roundTrip('Buy & sell')).toBe('Buy & sell');+ });+});++describe('tagSignature', () => {+ it('ignores the order tags appear in', () => {+ expect(tagSignature('<b>a</b><i>c</i>')).toBe(tagSignature('<i>c</i><b>a</b>'));+ });++ it('does not count an escaped tag as a tag', () => {+ expect(tagSignature('<agent-3d>')).toBe('');+ });+});++describe('markupDrift', () => {+ it('catches an escaped tag that got decoded into a live element', () => {+ expect(markupDrift('<code><agent-3d></code>', '<code><agent-3d></code>')).toBe(true);+ });++ it('catches a tag the translation invented', () => {+ expect(markupDrift('Ship fast', 'Ship <b>fast</b>')).toBe(true);+ });++ it('catches a tag the translation dropped', () => {+ expect(markupDrift('Ship <b>fast</b>', 'Ship fast')).toBe(true);+ });++ it('allows cosmetic entities to decode', () => {+ expect(markupDrift('Buy & sell — today', 'Buy & sell - today')).toBe(false);+ });++ it('allows the copy around the markup to change completely', () => {+ expect(markupDrift('<strong>Fast</strong> by default', '<strong>Schnell</strong> von Haus aus')).toBe(false);+ });+});++describe('lintLocale', () => {+ const source = { sdk: { snippet: 'Drop <code><agent-3d></code> in', amp: 'Buy & sell' } };++ it('reports markup drift', () => {+ const problems = lintLocale(source, { sdk: { snippet: 'Setze <code><agent-3d></code> ein', amp: 'Buy & sell' } }, { code: 'de' });+ expect(problems).toHaveLength(1);+ expect(problems[0]).toContain('[de] markup drift in sdk.snippet:');+ });++ it('formats the problem so --repair can parse the key back out', () => {+ // repairLocale() recovers the failing key with /… in ([^:]+):/, so the+ // message must keep `<key>:` immediately after the rule name or repair+ // silently reports "nothing to repair" on a locale full of drift.+ const [problem] = lintLocale(source, { sdk: { snippet: 'Setze <code><agent-3d></code> ein', amp: 'ok' } }, { code: 'de' });+ expect(/(?:glossary term dropped|placeholder drift|markup drift) in ([^:]+):/.exec(problem)?.[1]).toBe(+ 'sdk.snippet',+ );+ });++ it('passes a translation that kept its markup', () => {+ const problems = lintLocale(source, { sdk: { snippet: 'Setze <code><agent-3d></code> ein', amp: 'Kaufen & verkaufen' } }, { code: 'de' });+ expect(problems).toEqual([]);+ });+});