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(start): bring avatars back into the wizard, apply the chosen brain, and offer sign-in at publish instead of a dead end
nirholas6f06f51bb621
diff --git a/data/changelog.json b/data/changelog.jsonindex 8a537ab50..0005f7853 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -25430,6 +25430,16 @@"improvement"],"link": "/studio"+ },+ {+ "date": "2026-09-01",+ "title": "Get Started wizard: avatars come back into the flow, the brain you pick is the brain you get, and sign-in happens at publish time",+ "summary": "The 5-step wizard at /start now finishes what it starts. Taking a selfie, writing a prompt, building in the studio, or using the editor brings the finished avatar straight back into the wizard instead of stranding you on the avatar page, and Upload GLB uses the same storage path as every other upload, so it works. The AI model you choose is now applied to the agent (before, it was collected and dropped), the embed snippet points at the real loader, and a signed-out visitor who reaches the publish step gets a sign-in panel that resumes exactly where they left off rather than a cryptic error. Helper pills no longer sit on top of the Continue button, off-screen steps are no longer tabbable, the price and wallet fields have names for screen readers, and failed price or wallet saves are reported instead of swallowed.",+ "tags": [+ "fix",+ "improvement"+ ],+ "link": "/start"}]}diff --git a/docs/make-your-agent.md b/docs/make-your-agent.mdindex 62137a7db..b315e4495 100644--- a/docs/make-your-agent.md+++ b/docs/make-your-agent.md@@ -11,7 +11,7 @@ This guide walks you through creating a 3D AI agent in the browser — no code,Go to [three.ws/start](/start). This is the new-agent wizard.-You'll be asked to sign in if you haven't already. See [Do I need crypto?](./do-i-need-crypto.md) if you're not sure which sign-in option to choose.+You can walk through the whole setup before signing in: the avatar, the name, the brain, and the skills are kept in the tab. The wizard asks you to sign in (or create a free account) at the publish step, then picks up exactly where you left off. See [Do I need crypto?](./do-i-need-crypto.md) if you're not sure which sign-in option to choose.---@@ -78,6 +78,17 @@ Changes take effect immediately — no republishing needed for most settings.---+## How the avatar step hands back to the wizard++Step 1 of the wizard sends you to one of the avatar pages (`/create/selfie`, `/create`, `/create/prompt`, `/create/studio`) and expects the finished avatar back. Those pages share one small contract, implemented in [src/shared/wizard-return.js](../src/shared/wizard-return.js):++1. The wizard links out with `?wizard=1&next=/start?from=selfie`.+2. The first page in the chain calls `captureWizardReturn()`, which keeps the `next` path in `sessionStorage` and removes it from the address bar. Only a same-origin path under `/start` is ever stored; anything else is ignored.+3. Whichever page finally saves the avatar calls `pendingWizardReturn()`. When a return is pending, it offers "Use this avatar and continue setup" (the selfie and prompt pages) or goes straight back (the review and studio pages) via `returnToWizard({ avatarId, avatarName, avatarThumb })`, instead of its usual post-save destination. The wizard creates the agent itself, so the avatar page must not attach the avatar to an agent on this path.+4. The wizard reads `?avatarId=&avatarName=&avatarThumb=` on arrival, attaches the avatar, and moves to step 2.++Entries expire after two hours so an abandoned setup never hijacks a later, unrelated avatar save. A new avatar-producing page joins the flow by calling `captureWizardReturn()` on boot and `returnToWizard()` at its save point.+## What's next- **Put it on your website** → [Share & embed](./share-and-embed.md)diff --git a/pages/create-selfie.html b/pages/create-selfie.htmlindex b1b47642e..3f50195cc 100644--- a/pages/create-selfie.html+++ b/pages/create-selfie.html@@ -2001,6 +2001,11 @@</div><script type="module">+ import { captureWizardReturn, pendingWizardReturn, clearWizardReturn, wizardReturnUrl } from '/src/shared/wizard-return.js';+ // The /start wizard links here with ?next=; remember it so the finished+ // avatar can be handed straight back into the setup flow.+ captureWizardReturn();+function showStep(name) {document.querySelectorAll('.step[data-step]').forEach((s) => {const isTarget = s.dataset.step === name;@@ -2167,6 +2172,7 @@// In 'platform' mode the camera step is already the default active step.let _avatarId = null;+ let _wizardThumb = null;let _modelUrl = null;let _docTitleBase = document.title;let _notifyPermission =@@ -2228,6 +2234,43 @@s.className = 'build-step completed';});+ // Mid-wizard: the primary action is to take this avatar back to /start.+ const wizardNext = pendingWizardReturn();+ if (wizardNext && !document.getElementById('done-wizard-btn')) {+ const actions = document.querySelector('.done-actions');+ const wizardBtn = document.createElement('button');+ wizardBtn.id = 'done-wizard-btn';+ wizardBtn.type = 'button';+ wizardBtn.className = 'btn-save';+ wizardBtn.textContent = 'Use this avatar and continue setup →';+ wizardBtn.addEventListener('click', async () => {+ if (!_avatarId) return;+ wizardBtn.disabled = true;+ wizardBtn.textContent = 'Back to setup…';+ const nameEl = /** @type {HTMLInputElement|null} */ (document.getElementById('done-name'));+ const name = nameEl?.value?.trim();+ if (name) {+ try {+ await fetch(`/api/avatars/${encodeURIComponent(_avatarId)}`, {+ method: 'PATCH',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ name }),+ });+ } catch (_) {}+ }+ clearWizardReturn();+ window.location.assign(wizardReturnUrl(wizardNext, {+ avatarId: _avatarId,+ avatarName: name || '',+ avatarThumb: _wizardThumb || '',+ }));+ });+ actions?.prepend(wizardBtn);+ const saveBtn = document.getElementById('done-save-btn');+ if (saveBtn) saveBtn.className = 'btn-secondary';+ }+const viewer = document.querySelector('.done-viewer');viewer?.classList.add('loading');viewer?.classList.remove('failed');@@ -2242,6 +2285,7 @@const modelEl = document.getElementById('done-model');const modelUrl = avatar?.model_url || avatar?.url;_modelUrl = modelUrl || null;+ _wizardThumb = avatar?.thumbnail_url || null;if (modelEl && modelUrl) {modelEl.addEventListener('load',diff --git a/pages/start.html b/pages/start.htmlindex d103aee17..084125213 100644--- a/pages/start.html+++ b/pages/start.html@@ -5,21 +5,21 @@<script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />- <title data-i18n="start.meta_title">Get started · three.ws</title>- <meta name="description" content="Create your 3D AI agent in minutes. Give it a body, a brain, and a revenue stream." data-i18n-attr="content:start.meta_description"/>+ <title data-i18n="start.meta_title_wizard">Get started: build your 3D AI agent in 5 steps · three.ws</title>+ <meta name="description" content="A 5-step onboarding wizard: create a 3D avatar, name your agent, enable skills, deploy an embed widget, and set up monetization, all in under 5 minutes." data-i18n-attr="content:start.meta_description_wizard" /><meta name="robots" content="noindex" /><meta property="og:type" content="website" /><meta property="og:site_name" content="three.ws" /><meta property="og:url" content="https://three.ws/start" />- <meta property="og:title" content="Get started · three.ws" data-i18n-attr="content:start.meta_og_title" />- <meta property="og:description" content="Create your 3D AI agent in minutes. Give it a body, a brain, and a revenue stream." data-i18n-attr="content:start.meta_og_description" />+ <meta property="og:title" content="Get started: build your 3D AI agent in 5 steps · three.ws" data-i18n-attr="content:start.meta_og_title_wizard" />+ <meta property="og:description" content="A 5-step onboarding wizard: create a 3D avatar, name your agent, enable skills, deploy an embed widget, and set up monetization, all in under 5 minutes." data-i18n-attr="content:start.meta_og_description_wizard" /><meta property="og:image" content="https://three.ws/api/page-og?s=build&t=Get+Started&d=5-step+onboarding+wizard%3A+create+a+3D+avatar%2C+name+your+agent%2C+enable+skills%2C+deploy+an+embed+widget%2C+and+set+up+monetization%2C+all+in+under+5+minutes.&p=%2Fstart" /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="630" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:site" content="@trythreews" />- <meta name="twitter:title" content="Get started · three.ws" data-i18n-attr="content:start.meta_twitter_title" />- <meta name="twitter:description" content="Create your 3D AI agent in minutes. Give it a body, a brain, and a revenue stream." data-i18n-attr="content:start.meta_twitter_description" />+ <meta name="twitter:title" content="Get started: build your 3D AI agent in 5 steps · three.ws" data-i18n-attr="content:start.meta_twitter_title_wizard" />+ <meta name="twitter:description" content="A 5-step onboarding wizard: create a 3D avatar, name your agent, enable skills, deploy an embed widget, and set up monetization, all in under 5 minutes." data-i18n-attr="content:start.meta_twitter_description_wizard" /><meta name="twitter:image" content="https://three.ws/api/page-og?s=build&t=Get+Started&d=5-step+onboarding+wizard%3A+create+a+3D+avatar%2C+name+your+agent%2C+enable+skills%2C+deploy+an+embed+widget%2C+and+set+up+monetization%2C+all+in+under+5+minutes.&p=%2Fstart" /><link rel="icon" href="/favicon.ico" sizes="any" /><link rel="icon" type="image/svg+xml" href="/favicon.svg" />@@ -128,7 +128,10 @@display: flex;align-items: center;justify-content: center;- padding: 32px 24px;+ /* Bottom clearance tracks the live height of the shared helper-widget+ stack (set by the script), so the last controls of a scrolled step+ can always move out from under the pills. */+ padding: 32px 24px calc(32px + var(--wz-helper-clearance, 0px));overflow-y: auto;opacity: 0;transform: translateX(40px);@@ -140,6 +143,13 @@transform: translateX(0);pointer-events: auto;}+ /* Inactive steps stay in the DOM for the slide transition but must not+ be reachable: visibility flips after the motion, inert (set by the+ script) drops them from the tab order and the accessibility tree. */+ .wz-step:not(.active) {+ visibility: hidden;+ transition: opacity 0.35s ease, transform 0.35s ease, visibility 0s linear 0.35s;+ }.wz-step.exit-left {opacity: 0;transform: translateX(-40px);@@ -467,6 +477,22 @@gap: 16px;}.wz-deploy-success.show { display: flex; }+ .wz-deploy-meta { font-size: 13px; color: var(--text-2); line-height: 1.5; }+ .wz-deploy-signin {+ display: flex;+ flex-direction: column;+ gap: 14px;+ align-items: center;+ text-align: center;+ padding: 28px 20px;+ border: 1px solid var(--border);+ border-radius: var(--radius-lg);+ background: var(--surface);+ }+ .wz-deploy-signin .wz-sub { margin: 0; max-width: 42ch; }+ .wz-deploy-signin-actions { display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; }+ .wz-deploy-retry { margin: 16px auto 0; display: block; }+ .wz-toast-action { color: inherit; font-weight: 600; text-decoration: underline; text-underline-offset: 2px; }.wz-success-icon {font-size: 40px;text-align: center;@@ -635,6 +661,13 @@/* ── Footer buttons ────────────────────────────────────────── */.wz-footer {flex-shrink: 0;+ /* Sticky (never merely in-flow) so the shared corner stack+ (public/corner-stack.js) detects it as a bottom dock and lifts its+ helper pills clear of the Continue button. */+ position: sticky;+ bottom: 0;+ z-index: 2;+ background: var(--bg);padding: 16px 24px;border-top: 1px solid var(--border);display: flex;@@ -653,6 +686,8 @@font-family: inherit;}.wz-btn:disabled { opacity: 0.35; cursor: not-allowed; }+ a.wz-btn { display: inline-flex; align-items: center; justify-content: center; text-decoration: none; }+ .wz-btn:focus-visible, .wz-btn-skip:focus-visible, .wz-toast-action:focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; }.wz-btn-primary {background: var(--accent);color: var(--accent-ink);@@ -1148,17 +1183,17 @@<p class="wz-label" style="margin-bottom:10px" data-i18n="start.ai_model">AI model</p><div class="wz-model-grid" id="model-grid">- <button type="button" class="wz-model-card active" data-model="claude-sonnet-4-5" aria-pressed="true">- <div class="wz-model-name">Claude Sonnet</div>- <div class="wz-model-desc">Smart & fast</div>+ <button type="button" class="wz-model-card active" data-model="claude-sonnet-4-6" aria-pressed="true">+ <div class="wz-model-name">Claude Sonnet 4.6</div>+ <div class="wz-model-desc" data-i18n="start.model_claude_desc">Best quality, hosted by three.ws</div></button>- <button type="button" class="wz-model-card" data-model="gpt-5.6-sol" aria-pressed="false">- <div class="wz-model-name">GPT-5.6 Sol</div>- <div class="wz-model-desc">OpenAI flagship</div>+ <button type="button" class="wz-model-card" data-model="openai/gpt-oss-20b:free" aria-pressed="false">+ <div class="wz-model-name">GPT-OSS 20B</div>+ <div class="wz-model-desc" data-i18n="start.model_gpt_oss_desc">OpenAI open-weight, free</div></button>- <button type="button" class="wz-model-card" data-model="llama-3.3-70b" aria-pressed="false">- <div class="wz-model-name">Llama 3.3</div>- <div class="wz-model-desc">Open source</div>+ <button type="button" class="wz-model-card" data-model="llama-3.3-70b-versatile" aria-pressed="false">+ <div class="wz-model-name">Llama 3.3 70B</div>+ <div class="wz-model-desc" data-i18n="start.model_llama_desc">Open source, fastest</div></button></div></div>@@ -1238,27 +1273,39 @@<section class="wz-step" id="step-4" aria-label="Step 4: Deploy your agent"><div class="wz-step-inner"><p class="wz-eyebrow" data-i18n="start.step_4_of_5">Step 4 of 5</p>- <h1 class="wz-headline" data-i18n="start.your_agent_is_live">Your agent is live</h1>- <p class="wz-sub" data-i18n="start.we_created_your_agent_and_generated_an">We created your agent and generated an embeddable widget.</p>+ <h1 class="wz-headline" id="step4-headline" data-i18n="start.your_agent_is_live">Your agent is live</h1>+ <p class="wz-sub" id="step4-sub" data-i18n="start.we_created_your_agent_and_generated_an">We created your agent and generated an embeddable widget.</p>- <div class="wz-deploy-status" id="deploy-status">+ <div class="wz-deploy-status" id="deploy-status" role="status" aria-live="polite"><div class="wz-deploy-spinner"></div><div class="wz-deploy-label" id="deploy-label">Creating your agent…</div></div>+ <div class="wz-deploy-signin" id="deploy-signin" hidden>+ <div class="wz-success-icon" aria-hidden="true">🔐</div>+ <div class="wz-success-title" data-i18n="start.sign_in_to_publish_your_agent">Sign in to publish your agent</div>+ <p class="wz-sub" data-i18n="start.your_setup_is_saved_in_this_tab">Your avatar, name, and skills are saved in this tab. Sign in or create a free account and we pick up right here.</p>+ <div class="wz-deploy-signin-actions">+ <a class="wz-btn wz-btn-primary" id="deploy-signin-login" href="/login?next=%2Fstart" data-i18n="start.sign_in">Sign in</a>+ <a class="wz-btn wz-btn-ghost" id="deploy-signin-register" href="/register?next=%2Fstart" data-i18n="start.create_a_free_account">Create a free account</a>+ </div>+ </div>+<div class="wz-deploy-success" id="deploy-success"><div class="wz-success-icon">🎉</div><div class="wz-success-title" id="deploy-agent-name">Your agent is live</div><div><p class="wz-code-label" data-i18n="start.live_page">Live page</p>- <a class="wz-live-link" id="deploy-live-link" target="_blank" rel="noopener">+ <a class="wz-live-link" id="deploy-live-link" href="/agents" target="_blank" rel="noopener"><span class="wz-live-link-icon">🔗</span><span class="wz-live-link-text" id="deploy-live-url">…</span><span class="wz-live-link-arrow">↗</span></a></div>+ <div class="wz-deploy-meta" id="deploy-brain"></div>+<div><p class="wz-code-label" data-i18n="start.embed_snippet">Embed snippet</p><div class="wz-code-block" id="embed-code-block">@@ -1300,13 +1347,13 @@<div class="wz-earn-row"><div class="wz-earn-icon">💰</div><div class="wz-earn-row-body">- <div class="wz-earn-row-label">Price per API call</div>+ <div class="wz-earn-row-label" id="earn-price-label">Price per API call</div><div class="wz-earn-row-desc">Others pay <span data-term="usdc" data-i18n="start.usdc_a_1_digital_dollar">USDC (a $1 digital dollar)</span> every time they call your agent's API</div></div><div><div class="wz-earn-input-wrap"><span class="wz-earn-prefix">$</span>- <input type="number" class="wz-earn-num" id="earn-price" min="0" max="100" step="0.001" placeholder="0.001" />+ <input type="number" class="wz-earn-num" id="earn-price" min="0" max="100" step="0.001" placeholder="0.001" aria-labelledby="earn-price-label" inputmode="decimal" /><span class="wz-earn-suffix" data-i18n="start.usdc">USDC</span></div><div class="wz-earn-usd-hint" id="earn-price-usd-hint"></div>@@ -1316,13 +1363,13 @@<div class="wz-earn-row"><div class="wz-earn-icon">◎</div><div class="wz-earn-row-body">- <div class="wz-earn-row-label">Payout wallet</div>+ <div class="wz-earn-row-label" id="earn-wallet-label">Payout wallet</div><div class="wz-earn-row-desc">Wallet address for withdrawals</div></div></div><div style="padding: 0 0 4px;"><div class="wz-wallet-input-wrap">- <input type="text" class="wz-wallet-input" id="earn-wallet" placeholder="Solana or wallet address" />+ <input type="text" class="wz-wallet-input" id="earn-wallet" placeholder="Solana or wallet address" aria-labelledby="earn-wallet-label" autocomplete="off" spellcheck="false" /><span class="wz-wallet-chain" id="earn-chain" data-i18n="start.sol">SOL</span></div></div>diff --git a/prompts/swarm-100/route-start.md b/prompts/swarm-100/route-start.mddeleted file mode 100644index 950c8b52a..000000000--- a/prompts/swarm-100/route-start.md+++ /dev/null@@ -1,119 +0,0 @@-# Route audit: /start (Get Started)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. This route's declared entry (path, description, added date):-- node -e "const p=require('./data/pages.json');for(const s of p.sections)for(const g of s.pages)if(g.path==='/start')console.log(JSON.stringify(g,null,2))"--2. Find the serving implementation: grep "/start" in vercel.json (the live- route table server/index.mjs boots from), then list matching files in- pages/ and src/. STRUCTURE.md maps every surface to its directory if the- grep is ambiguous.-3. Production right now:-- curl -so /dev/null -w '%{http_code}\n' https://three.ws/start--4. Start (or reuse) the local dev server: npm run dev (vite, port 3000).--## Task: audit this one route end to end, then fix everything found--Route: /start ("Get Started", section "build").-Declared purpose: 5-step onboarding wizard: create a 3D avatar, name your agent, enable skills, deploy an embed widget, and set up monetization: all in under 5 minutes.--Drive the page in a real headless browser. Playwright is already a dev-dependency; keep your probe script in the session scratchpad, never in the-repo.--1. Load http://localhost:3000/start. Record the HTTP status, every console- error and warning, and every failed network request.-2. Exercise it like a first-time user: click the primary actions, run the- primary flow if one exists, follow the page's internal links. Every button- must do something real; every link must resolve. If the page renders data,- prove in the network log that it came from a live endpoint, not a baked-in- fallback array.-3. States: verify populated, empty, loading, and error states are designed and- reachable. Block the page's primary fetch in Playwright and confirm an- actionable error state appears, not a blank void or a raw exception.-4. Responsive: render at 320, 768, and 1440 px. No horizontal page scroll, no- overlapping or clipped controls.-5. Accessibility basics: one h1; interactive elements are real buttons or- links with visible focus states; images carry alt text; form fields have- labels.-6. Head: a specific title tag and meta description that match the declared- purpose above.-7. Fix every defect at its root in the page's real source files and re-run the- probe until clean. Defects in shared modules are in scope when this route- exercises them.--## Definition of done--- [ ] Local load of /start: HTTP 200, zero console errors, zero unhandled- failed requests (a third-party outage must land in a designed fallback,- not a broken page).-- [ ] No dead interactive element on the page: no stub href="#", no button- without a handler, no link to a missing path.-- [ ] Empty, loading, error, and populated states verified.-- [ ] 320 / 768 / 1440 px renders verified clean.-- [ ] Title and meta description present and specific.-- [ ] npm test passes; npm run check:rules -- --paths <touched files> exits 0.-- [ ] Production status from step 0 recorded in the report; if production- needs a deploy to pick up a fix, the report says so (deploys stay- owner-gated).--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/route-start.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/src/avatar-studio.js b/src/avatar-studio.jsindex 8dfa46601..fb638fc6d 100644--- a/src/avatar-studio.js+++ b/src/avatar-studio.js@@ -30,6 +30,11 @@ import {} from './avatar-proportions.js';import { canonicalBoneNodesFromObject } from './animation-retarget.js';import { saveRemoteGlbToAccount, apiFetch } from './account.js';+import { captureWizardReturn, returnToWizard } from './shared/wizard-return.js';++// The /start wizard links here with ?next=; remember it so the saved avatar+// can be handed straight back into the setup flow.+captureWizardReturn();import { uploadAvatarSnapshot } from './voice/avatar-snapshot.js';import { optimizeAndValidateGlb } from './avatar-studio-optimize.js';import { poseSkeletonsToBind, captureBoneTransforms, restoreBoneTransforms } from './glb-bind-pose.js';@@ -1984,6 +1989,9 @@ async function finishSave(avatar) {await new Promise((r) => setTimeout(r, 700));hideSaveOverlay();+ // Mid-wizard: skip the toast and hand the avatar straight back to /start.+ if (returnToWizard({ avatarId: avatar.id, avatarName: name, avatarThumb: avatar.thumbnail_url || '' })) return;+// Show a save-success toast with next-step CTAs (launch a coin / view).// Give the user time to choose; fall back to the avatar page if they don't.showSaveToast(avatar.id);diff --git a/src/create-prompt.js b/src/create-prompt.jsindex d6ddd72b0..800cb5e99 100644--- a/src/create-prompt.js+++ b/src/create-prompt.js@@ -17,6 +17,11 @@import { log } from './shared/log.js';import { injectFestivePresets } from './shared/festive-presets.js';import { mountPromptDictation } from './voice/prompt-dictation.js';+import { captureWizardReturn, pendingWizardReturn, clearWizardReturn, wizardReturnUrl } from './shared/wizard-return.js';++// The /start wizard links here with ?next=; remember it so the finished avatar+// can be handed straight back into the setup flow.+captureWizardReturn();const SUBMIT_ENDPOINT = '/api/avatars/reconstruct';const STATUS_ENDPOINT = '/api/avatars/regenerate-status';@@ -475,6 +480,23 @@ async function renderDone(avatarId, run) {return;}showStep('done');+ // Mid-wizard: the primary action is to take this avatar back to /start.+ const wizardNext = pendingWizardReturn();+ const editorLink = $('#open-editor');+ if (wizardNext && editorLink && !document.getElementById('done-wizard-link')) {+ const back = document.createElement('a');+ back.id = 'done-wizard-link';+ back.className = 'btn-primary';+ back.href = wizardReturnUrl(wizardNext, {+ avatarId,+ avatarName: avatar?.display_name || avatar?.name || '',+ avatarThumb: avatar?.thumbnail_url || '',+ });+ back.textContent = 'Use this avatar and continue setup →';+ back.addEventListener('click', () => clearWizardReturn());+ editorLink.className = 'btn-ghost';+ editorLink.parentNode.insertBefore(back, editorLink);+ }// Let the site-wide discovery layer offer the natural next steps// (Studio, agent wizard, Walk) with this avatar pre-loaded.document.dispatchEvent(diff --git a/src/create-review.js b/src/create-review.jsindex d51224e2c..807fd4b1d 100644--- a/src/create-review.js+++ b/src/create-review.js@@ -38,6 +38,7 @@ import {toggleEmoteStrip,} from './create-review-features.js';import { log } from './shared/log.js';+import { captureWizardReturn, pendingWizardReturn, clearWizardReturn, wizardReturnUrl } from './shared/wizard-return.js';const RESUME_KEY = '3dagent:guest-avatar-resume';const $ = (sel) => document.querySelector(sel);@@ -103,6 +104,7 @@ let viewerIdle = /** @type {IdleAnimation | null} */ (null);let viewerIdleDispose = /** @type {(() => void) | null} */ (null);async function boot() {+ captureWizardReturn();staged = await loadGuest();if (!staged) {location.replace('/create');@@ -407,6 +409,25 @@ async function onSave({ auto = false } = {}) {setSaveProgress(null);setSaveCancellable(false);+ // Came from the /start wizard: hand the avatar back and let the wizard+ // create the agent. Attaching it to a default agent here would leave the+ // user with two agents for one setup.+ const wizardNext = pendingWizardReturn();+ if (wizardNext) {+ updateSaveOverlay('Back to setup…', '');+ await clearGuest();+ await captureAndUploadThumbnail(avatar.id).catch(() => {});+ releaseObjectUrl();+ try { window.__twsGuide?.complete('create'); } catch (_) {}+ clearWizardReturn();+ window.location.href = wizardReturnUrl(wizardNext, {+ avatarId: avatar.id,+ avatarName: name,+ avatarThumb: avatar.thumbnail_url || '',+ });+ return;+ }+if (isObject) {updateSaveOverlay('Saving to library…', '');await clearGuest();diff --git a/src/create.js b/src/create.jsindex 1818a9d76..7bb163f42 100644--- a/src/create.js+++ b/src/create.js@@ -4,6 +4,14 @@ import { stage as stageGuestAvatar } from './guest-avatar.js';import { createFromTemplate } from './shared/template-picker.js';import { log } from './shared/log.js';import { clearSharedIntent, sharedIntent, takeSharedFiles } from './shared/share-target.js';+import { captureWizardReturn } from './shared/wizard-return.js';++// The /start wizard links here with ?next=; remember it before anything else+// loads, so whichever creation page finishes the avatar can hand it back+// (src/shared/wizard-return.js). Top level, not boot(): this hub pulls in+// heavy modules first and a visitor can click through to a sub-page before+// boot() ever runs.+captureWizardReturn();// GLB magic bytes: ASCII "glTF"const GLB_MAGIC = [0x67, 0x6c, 0x54, 0x46];diff --git a/src/shared/wizard-return.js b/src/shared/wizard-return.jsnew file mode 100644index 000000000..3c5b26be8--- /dev/null+++ b/src/shared/wizard-return.js@@ -0,0 +1,118 @@+/**+ * Wizard return contract.+ *+ * The /start onboarding wizard sends people off-page to make an avatar+ * (/create, /create/selfie, /create/prompt, /create/studio) and expects them+ * back on /start with the finished avatar attached. The hop can span several+ * pages and a sign-in round trip, so the return address is not carried in the+ * URL from page to page: the first page in the chain captures `?next=` into+ * sessionStorage and whichever page finally saves the avatar reads it back.+ *+ * Contract:+ * - The wizard links out with `?wizard=1&next=<same-origin path under /start>`.+ * - An avatar-producing page calls captureWizardReturn() on boot.+ * - On save it calls pendingWizardReturn(); when that is set, it hands the+ * avatar back with returnToWizard({ avatarId, avatarName, avatarThumb })+ * instead of its usual post-save destination. The wizard creates the+ * agent itself, so the producing page must not attach the avatar to an+ * agent on this path.+ *+ * Only a same-origin path that starts with /start is ever stored, so a+ * crafted link cannot bounce a visitor to another site with their avatar id.+ * Entries expire after two hours; a stale one from an abandoned session must+ * not hijack a later, unrelated avatar save.+ */++export const WIZARD_RETURN_KEY = 'wz:return';+export const WIZARD_RETURN_TTL_MS = 2 * 60 * 60 * 1000;++function storageOf(storage) {+ if (storage) return storage;+ try { return globalThis.sessionStorage || null; } catch { return null; }+}++/**+ * Normalize a candidate return target to a same-origin /start path, or null.+ * Accepts a bare path ("/start?from=selfie") or an absolute URL on `origin`.+ */+export function sanitizeWizardReturn(candidate, origin) {+ if (typeof candidate !== 'string' || !candidate) return null;+ const base = origin || (typeof location !== 'undefined' ? location.origin : 'https://three.ws');+ let url;+ try { url = new URL(candidate, base); } catch { return null; }+ if (url.origin !== base) return null;+ if (!/^\/start(\/|$)/.test(url.pathname)) return null;+ return url.pathname + url.search;+}++/**+ * Read `?next=` off the current URL, remember it when it is a valid wizard+ * return target, and strip `next` / `wizard` from the address bar so a reload+ * or a copied link does not re-arm the flow. Returns the stored path or null.+ */+export function captureWizardReturn({ url, storage, now = Date.now() } = {}) {+ const store = storageOf(storage);+ let current = url || null;+ if (!current) {+ // A page under test may stub location with a bare object; an unparsable+ // href means there is no query to capture, not a failure.+ try { current = typeof location !== 'undefined' ? new URL(location.href) : null; } catch { current = null; }+ }+ if (!current) return null;+ const next = sanitizeWizardReturn(current.searchParams.get('next'), current.origin);+ if (!next) return null;+ try { store?.setItem(WIZARD_RETURN_KEY, JSON.stringify({ next, at: now })); } catch {}+ if (!url && typeof history !== 'undefined') {+ const clean = new URL(current.href);+ clean.searchParams.delete('next');+ clean.searchParams.delete('wizard');+ history.replaceState(history.state, '', clean.pathname + clean.search + clean.hash);+ }+ return next;+}++/** The stored return path when one is present and fresh, otherwise null. */+export function pendingWizardReturn({ storage, now = Date.now() } = {}) {+ const store = storageOf(storage);+ let raw = null;+ try { raw = store?.getItem(WIZARD_RETURN_KEY) || null; } catch { return null; }+ if (!raw) return null;+ try {+ const parsed = JSON.parse(raw);+ if (!parsed || typeof parsed.next !== 'string') return null;+ if (typeof parsed.at === 'number' && now - parsed.at > WIZARD_RETURN_TTL_MS) {+ clearWizardReturn({ storage: store });+ return null;+ }+ return sanitizeWizardReturn(parsed.next);+ } catch {+ return null;+ }+}++export function clearWizardReturn({ storage } = {}) {+ try { storageOf(storage)?.removeItem(WIZARD_RETURN_KEY); } catch {}+}++/** Build the /start URL that hands a finished avatar back to the wizard. */+export function wizardReturnUrl(next, { avatarId, avatarName = '', avatarThumb = '' } = {}) {+ const origin = typeof location !== 'undefined' ? location.origin : 'https://three.ws';+ const url = new URL(next, origin);+ if (avatarId) url.searchParams.set('avatarId', String(avatarId));+ if (avatarName) url.searchParams.set('avatarName', String(avatarName).slice(0, 100));+ if (avatarThumb) url.searchParams.set('avatarThumb', String(avatarThumb));+ return url.pathname + url.search;+}++/**+ * Hand the avatar back to the wizard and forget the return address. Returns+ * false (and navigates nowhere) when no return is pending, so callers can fall+ * through to their normal post-save destination.+ */+export function returnToWizard(details, { storage } = {}) {+ const next = pendingWizardReturn({ storage });+ if (!next) return false;+ clearWizardReturn({ storage });+ location.href = wizardReturnUrl(next, details);+ return true;+}diff --git a/src/start.js b/src/start.jsindex cb02a9763..90f525516 100644--- a/src/start.js+++ b/src/start.js@@ -1,16 +1,21 @@/**- * /start — Onboarding wizard+ * /start: onboarding wizard*- * 5-step flow: avatar → name/brain → skills → deploy → earn- * State is persisted in sessionStorage so users can navigate away and back.+ * 5-step flow: avatar, name and brain, skills, deploy, earn.+ * State is persisted in sessionStorage so users can navigate away and back,+ * including the round trip to an avatar-producing page and the sign-in hop+ * before deploy. See src/shared/wizard-return.js for the avatar hand-back.*/import { formatUsdcEq } from './shared/usd-price.js';import { TEMPLATES, TEMPLATES_BY_ID } from './templates.js';import { log } from './shared/log.js';+import { apiFetch, noteSession } from './api.js';+import { saveRemoteGlbToAccount } from './account.js';const STORAGE_KEY = 'wz:state';const TOTAL_STEPS = 5;+const START_PATH = '/start';// ── Personality presets ────────────────────────────────────────────────────@@ -41,6 +46,18 @@ const PRESETS = {},};+// ── Brain models ──────────────────────────────────────────────────────────+// Every id here is a route the embed brain can actually serve (api/llm/anthropic.js+// MODELS) and an option the dashboard's embed-policy page offers, so the choice+// made here is the same setting the owner later sees under Dashboard.++const MODELS = {+ 'claude-sonnet-4-6': { label: 'Claude Sonnet 4.6' },+ 'openai/gpt-oss-20b:free': { label: 'GPT-OSS 20B' },+ 'llama-3.3-70b-versatile': { label: 'Llama 3.3 70B' },+};+const DEFAULT_MODEL = 'claude-sonnet-4-6';+// ── Skill → backend skills mapping ───────────────────────────────────────const BASE_SKILLS = ['greet', 'present-model', 'validate-model', 'remember', 'think'];@@ -74,7 +91,9 @@ function initState() {const url = new URL(location.href);const saved = loadState();- // Check if returning from avatar creation+ // Returning from an avatar-producing page (src/shared/wizard-return.js).+ // URLSearchParams already decodes the values; decoding again would throw+ // on a name that legitimately contains a percent sign.const avatarId = url.searchParams.get('avatarId');const avatarName = url.searchParams.get('avatarName');const avatarThumb = url.searchParams.get('avatarThumb');@@ -88,33 +107,62 @@ function initState() {widgetId: null,name: '',description: '',- model: 'claude-sonnet-4-5',+ model: DEFAULT_MODEL,enabledSkills: ['memory', 'think'],cryptoMode: false,price: '',wallet: '',deployed: false,+ modelApplied: null,embedCode: '',liveUrl: '',};if (base.cryptoMode === undefined) base.cryptoMode = false;+ // A session saved before the model list changed may hold an id no lane serves.+ if (!MODELS[base.model]) base.model = DEFAULT_MODEL;if (avatarId) {base.avatarId = avatarId;- if (avatarName) base.avatarName = decodeURIComponent(avatarName);- if (avatarThumb) base.avatarThumb = decodeURIComponent(avatarThumb);+ if (avatarName) base.avatarName = avatarName;+ if (avatarThumb) base.avatarThumb = avatarThumb;// Advance to step 2 if returning from avatar creationif (base.step === 1) base.step = 2;- // Remove avatar params from URL cleanly- url.searchParams.delete('avatarId');- url.searchParams.delete('avatarName');- url.searchParams.delete('avatarThumb');- history.replaceState(null, '', url.toString());}+ for (const key of ['avatarId', 'avatarName', 'avatarThumb', 'from']) url.searchParams.delete(key);+ if (url.href !== location.href) history.replaceState(null, '', url.toString());return base;}+// ── Session ───────────────────────────────────────────────────────────────+// null = not resolved yet, true/false once /api/auth/me answered. The deploy+// step reads this to offer sign-in instead of firing requests that can only 401.++let authed = null;++async function resolveAuth() {+ try {+ const r = await apiFetch('/api/auth/me', { allowAnonymous: true });+ if (r.status === 401) {+ authed = false;+ } else if (r.ok) {+ const j = await r.json();+ authed = Boolean(j && j.user);+ } else {+ throw new Error(`auth/me ${r.status}`);+ }+ noteSession(authed);+ } catch (err) {+ log.warn('[wizard] session probe failed; deploy will find out', err?.message || err);+ authed = null;+ }+ return authed;+}++function loginHref(target = '/login') {+ return `${target}?next=${encodeURIComponent(START_PATH)}`;+}+// ── Templates gallery ─────────────────────────────────────────────────────const templatesScreen = document.getElementById('templates-screen');@@ -122,9 +170,9 @@ const wizardEl = document.getElementById('wizard');const startFreshBtn = document.getElementById('btn-start-fresh');function showWizard({ fromTemplate = false } = {}) {- // Show "← Templates" button only when the gallery was bypassed (stale state).- // When triggered by a template card click, the gallery is already visible so- // no need to offer a way back.+ // Show "← Templates" only when the gallery was bypassed (saved state or a+ // returning avatar). When a template card was clicked the gallery was just+ // on screen, so there is nothing to offer a way back to.if (startFreshBtn) startFreshBtn.style.display = fromTemplate ? 'none' : '';if (templatesScreen) {@@ -132,9 +180,9 @@ function showWizard({ fromTemplate = false } = {}) {setTimeout(() => {templatesScreen.classList.add('tpl-hidden');templatesScreen.classList.remove('tpl-exit');- // Reveal wizard only after template screen is gone — avoids a black- // flash caused by both full-height elements being in the DOM at once- // with overflow:hidden on body hiding the below-fold wizard.+ // Reveal the wizard only after the template screen is gone: both are+ // full-height, and body has overflow:hidden, so showing both at once+ // flashes black while the below-fold wizard is clipped.if (wizardEl) wizardEl.classList.remove('wz-offstage');}, 200);} else {@@ -145,14 +193,14 @@ function showWizard({ fromTemplate = false } = {}) {if (startFreshBtn) {startFreshBtn.addEventListener('click', () => {try { sessionStorage.removeItem(STORAGE_KEY); } catch {}- location.reload();+ location.href = START_PATH;});}function applyTemplate(tpl) {state.description = tpl.bio;state.enabledSkills = [...tpl.skills];- if (tpl.model) state.model = tpl.model;+ if (tpl.model && MODELS[tpl.model]) state.model = tpl.model;state.cryptoMode = Boolean(tpl.cryptoMode);// Jump to step 2 (Name & Brain) so the user immediately sees the prefilled personastate.step = 2;@@ -189,20 +237,20 @@ function initTemplateGallery() {const hasSavedState = Boolean(loadState());// If a specific template is requested via ?template=id, apply it immediately.- // applyTemplate() calls renderStep() — return true so caller skips its own call.+ // applyTemplate() calls renderStep(), so return true and the caller skips its own call.if (tplParam && TEMPLATES_BY_ID[tplParam]) {applyTemplate(TEMPLATES_BY_ID[tplParam]);return true;}- // If there's an in-progress wizard session, skip the gallery and let caller renderStep.- // Show "← Templates" so the user can always reset back to the template gallery.- if (hasSavedState) {+ // An in-progress session, or an avatar that just came back from a creation+ // page, skips the gallery. "← Templates" stays available to reset.+ if (hasSavedState || state.avatarId) {showWizard({ fromTemplate: false });return false;}- // Show the gallery — renderStep still runs so wizard state is primed behind the overlay.+ // Show the gallery; renderStep still runs so wizard state is primed behind the overlay.templatesScreen.classList.remove('tpl-hidden');const grid = document.getElementById('tpl-grid');@@ -219,43 +267,48 @@ function initTemplateGallery() {return false;}-// ── CSRF helper ───────────────────────────────────────────────────────────--let _csrf = null;+// ── API helper ────────────────────────────────────────────────────────────+// apiFetch carries the CSRF token for mutations. allowAnonymous keeps a 401+// in our hands (the deploy step turns it into a sign-in panel) instead of+// letting the shared client bounce the tab to /login mid-wizard.-async function getCsrfToken() {- if (_csrf && _csrf.expiresAt > Date.now() + 5_000) return _csrf.token;- const r = await fetch('/api/csrf-token', { credentials: 'include' });- if (!r.ok) throw new Error('Could not get CSRF token. Please sign in again.');- const j = await r.json();- _csrf = { token: j.data.token, expiresAt: Date.now() + (j.data.expires_in - 30) * 1000 };- return _csrf.token;-}--async function apiPost(url, body) {- const token = await getCsrfToken();- _csrf = null;- const r = await fetch(url, {- method: 'POST',- headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': token },- credentials: 'include',+async function apiJson(method, url, body) {+ const r = await apiFetch(url, {+ method,+ allowAnonymous: true,+ headers: { 'content-type': 'application/json' },body: JSON.stringify(body),});- const j = await r.json();- if (!r.ok) throw new Error(j.error_description || j.error || `Server error ${r.status}`);+ const j = await r.json().catch(() => ({}));+ if (!r.ok) {+ const err = new Error(j.error_description || j.error || `Server error ${r.status}`);+ err.status = r.status;+ throw err;+ }return j;}+function isSignedOut(err) {+ return err?.status === 401 || err?.code === 'not_signed_in' || err?.redirected === true;+}+// ── Toast helper ──────────────────────────────────────────────────────────const toast = document.getElementById('wz-toast');let _toastTimer = null;-function showError(msg) {+function showError(msg, action) {if (_toastTimer) clearTimeout(_toastTimer);toast.textContent = msg;+ if (action) {+ const a = document.createElement('a');+ a.className = 'wz-toast-action';+ a.href = action.href;+ a.textContent = action.label;+ toast.append(' ', a);+ }toast.classList.add('show');- _toastTimer = setTimeout(() => toast.classList.remove('show'), 4000);+ _toastTimer = setTimeout(() => toast.classList.remove('show'), action ? 8000 : 4000);}// ── DOM helpers ───────────────────────────────────────────────────────────@@ -313,9 +366,15 @@ function setCryptoMode(on) {function renderStep() {steps.forEach((s, i) => {const stepNum = i + 1;+ const on = stepNum === state.step;s.classList.remove('active', 'exit-left');- if (stepNum === state.step) s.classList.add('active');+ if (on) s.classList.add('active');else if (stepNum < state.step) s.classList.add('exit-left');+ // Off-screen steps slide out visually but stayed in the tab order and the+ // accessibility tree, so a keyboard user tabbed through five screens of+ // controls they could not see. inert removes them from both.+ s.inert = !on;+ s.setAttribute('aria-hidden', String(!on));});dots.forEach((d, i) => {@@ -326,16 +385,18 @@ function renderStep() {});$('btn-back').hidden = state.step <= 1;- $('btn-next').hidden = state.step === 4 && !state.deployed;const nextBtn = $('btn-next');+ nextBtn.disabled = false;if (state.step === 5) {nextBtn.textContent = hasCryptoSkills() ? 'Save & finish' : 'Go to dashboard';+ nextBtn.hidden = false;} else if (state.step === 4) {nextBtn.textContent = 'Continue';nextBtn.hidden = !state.deployed;} else {nextBtn.textContent = state.step === 3 ? 'Continue to deploy' : 'Continue';+ nextBtn.hidden = false;}// Skip button: show on step 1 always; on step 5 only when crypto skills selected (skip wallet setup)@@ -345,8 +406,7 @@ function renderStep() {if (state.step === 1) renderStep1();if (state.step === 2) { renderStep2(); updateCryptoUI(); }if (state.step === 3) { renderStep3(); updateCryptoUI(); }- if (state.step === 4 && !state.deployed) startDeploy();- if (state.step === 4 && state.deployed) showDeploySuccess();+ if (state.step === 4) renderStep4();if (state.step === 5) renderStep5();// Announce progress to screen readers@@ -435,10 +495,51 @@ function renderStep5() {// ── Step 4: Deploy ─────────────────────────────────────────────────────────+function setStep4Copy(headline, sub) {+ const h = $('step4-headline');+ const p = $('step4-sub');+ // The i18n pass lands after an async catalog fetch; marking the element as+ // script-owned stops it from reverting this state-specific copy.+ if (h) { h.textContent = headline; h.setAttribute('data-i18n-owned', '1'); }+ if (p) { p.textContent = sub; p.setAttribute('data-i18n-owned', '1'); }+}++function renderStep4() {+ if (state.deployed) {+ showDeploySuccess();+ } else if (authed === false) {+ showDeploySignIn();+ } else {+ startDeploy();+ }+}++function showDeploySignIn() {+ $('deploy-status').style.display = 'none';+ $('deploy-success').classList.remove('show');+ $('deploy-signin').hidden = false;+ $('btn-next').hidden = true;+ setStep4Copy('Publish your agent', 'One more thing before it goes live.');+ $('deploy-signin-login').href = loginHref('/login');+ $('deploy-signin-register').href = loginHref('/register');+}++let _deploying = false;+async function startDeploy() {- $('deploy-status').style.display = 'block';+ if (_deploying) return;+ _deploying = true;+ const status = $('deploy-status');+ status.style.display = 'block';+ status.querySelectorAll('.wz-deploy-retry').forEach((b) => b.remove());+ const spinner = status.querySelector('.wz-deploy-spinner');+ if (spinner) spinner.style.display = '';+ const label = $('deploy-label');+ label.style.color = '';$('deploy-success').classList.remove('show');+ $('deploy-signin').hidden = true;$('btn-next').hidden = true;+ setStep4Copy('Publishing your agent', 'Creating the agent, applying its brain, and building the embed widget.');try {// Build skills list@@ -447,81 +548,117 @@ async function startDeploy() {(SKILL_MAP[key] || []).forEach((s) => skillSet.add(s));}- // 1. Create agent- $('deploy-label').textContent = 'Creating your agent…';- const agentBody = {- name: state.name || 'My Agent',- description: state.description || null,- skills: [...skillSet],- };- if (state.avatarId) agentBody.avatar_id = state.avatarId;-- const agentRes = await apiPost('/api/agents', agentBody);- const agentId = agentRes.agent?.id;- if (!agentId) throw new Error('Agent creation failed — no ID returned.');- state.agentId = agentId;- saveState(state);+ // 1. Create agent (idempotent across retries: a created agent is kept)+ let agentId = state.agentId;+ if (!agentId) {+ label.textContent = 'Creating your agent…';+ const agentBody = {+ name: state.name || 'My Agent',+ description: state.description || null,+ skills: [...skillSet],+ };+ if (state.avatarId) agentBody.avatar_id = state.avatarId;++ const agentRes = await apiJson('POST', '/api/agents', agentBody);+ agentId = agentRes.agent?.id;+ if (!agentId) throw new Error('Agent creation failed: no ID returned.');+ state.agentId = agentId;+ saveState(state);+ }- // 2. Create widget- $('deploy-label').textContent = 'Building your embed widget…';- const widgetBody = {- type: 'talking-agent',- name: (state.name || 'My Agent') + ' — Chat',- config: { agent_id: agentId },- is_public: true,- };- if (state.avatarId) widgetBody.avatar_id = state.avatarId;-- const widgetRes = await apiPost('/api/widgets', widgetBody);- const widgetId = widgetRes.widget?.id;- if (!widgetId) throw new Error('Widget creation failed — no ID returned.');- state.widgetId = widgetId;-- // 3. Build embed code- const origin = location.origin;- const embedCode = `<script src="${origin}/widget.js" data-widget="${widgetId}" async><\/script>`;- const liveUrl = `${origin}/agents/${agentId}`;+ // 2. Apply the chosen brain. The embed policy is the per-agent model+ // setting every chat lane reads (talk, embed brain, delegate), and the+ // same field the dashboard's embed-policy page edits.+ label.textContent = `Setting the brain to ${MODELS[state.model].label}…`;+ try {+ await apiJson('PUT', `/api/agents/${agentId}/embed-policy`, { brain: { model: state.model } });+ state.modelApplied = true;+ } catch (err) {+ if (isSignedOut(err)) throw err;+ log.warn('[wizard/deploy] embed-policy update failed; agent keeps the platform default model', err);+ state.modelApplied = false;+ }- state.liveUrl = liveUrl;- state.embedCode = embedCode;+ // 3. Create widget+ if (!state.widgetId) {+ label.textContent = 'Building your embed widget…';+ const widgetBody = {+ type: 'talking-agent',+ name: `${state.name || 'My Agent'} chat`,+ config: { agent_id: agentId },+ is_public: true,+ };+ if (state.avatarId) widgetBody.avatar_id = state.avatarId;++ const widgetRes = await apiJson('POST', '/api/widgets', widgetBody);+ const widgetId = widgetRes.widget?.id;+ if (!widgetId) throw new Error('Widget creation failed: no ID returned.');+ state.widgetId = widgetId;+ }++ // 4. Build embed code (same snippet the dashboard's Widgets page hands out)+ const origin = location.origin;+ state.embedCode =+ `<script async src="${origin}/embed.js"\n` ++ ` data-widget="${state.widgetId}"\n` ++ ` data-reveal="interaction"\n` ++ ` data-poster="auto"><\/script>`;+ state.liveUrl = `${origin}/agents/${agentId}`;state.deployed = true;saveState(state);+ try {+ window.__twsGuide?.complete('brain', { silent: true });+ window.__twsGuide?.complete('embed', { silent: true });+ } catch {}+showDeploySuccess();} catch (err) {log.error('[wizard/deploy]', err);- $('deploy-label').textContent = err.message || 'Deployment failed. Please try again.';- $('deploy-label').style.color = '#f87171';- const spinner = document.querySelector('.wz-deploy-spinner');+ saveState(state);+ if (isSignedOut(err)) {+ authed = false;+ noteSession(false);+ showDeploySignIn();+ return;+ }+ setStep4Copy('Publishing hit a snag', 'Nothing you entered was lost. Retry, or go back and adjust.');+ label.textContent = err.message || 'Deployment failed. Please try again.';+ label.style.color = '#f87171';if (spinner) spinner.style.display = 'none';- // Show a retry buttonconst retryBtn = document.createElement('button');retryBtn.type = 'button';retryBtn.textContent = 'Try again';- retryBtn.className = 'wz-btn wz-btn-ghost';- retryBtn.style.margin = '16px auto 0';- retryBtn.style.display = 'block';- retryBtn.onclick = () => {- retryBtn.remove();- $('deploy-label').style.color = '';- if (spinner) spinner.style.display = '';- startDeploy();- };- $('deploy-status').appendChild(retryBtn);+ retryBtn.className = 'wz-btn wz-btn-ghost wz-deploy-retry';+ retryBtn.addEventListener('click', () => startDeploy());+ status.appendChild(retryBtn);+ retryBtn.focus();+ } finally {+ _deploying = false;}}function showDeploySuccess() {$('deploy-status').style.display = 'none';+ $('deploy-signin').hidden = true;const success = $('deploy-success');success.classList.add('show');+ setStep4Copy('Your agent is live', 'We created your agent and generated an embeddable widget.');$('deploy-agent-name').textContent = `${state.name || 'Your agent'} is live 🎉`;$('deploy-live-url').textContent = state.liveUrl;const liveLink = $('deploy-live-link');liveLink.href = state.liveUrl;+ const brain = $('deploy-brain');+ if (brain) {+ const label = MODELS[state.model]?.label || state.model;+ brain.textContent = state.modelApplied === false+ ? `Brain: platform default. ${label} could not be applied; change it any time under Dashboard → Embed policy.`+ : `Brain: ${label}. Change it any time under Dashboard → Embed policy.`;+ }+const codeEl = $('embed-code');if (codeEl) codeEl.textContent = state.embedCode;@@ -536,37 +673,44 @@ function detectChain(addr) {return 'SOL';}+// Returns a list of human-readable problems; empty when everything saved.async function saveEarnSettings() {const price = parseFloat($('earn-price')?.value || '0') || 0;const wallet = ($('earn-wallet')?.value || '').trim();-- const promises = [];+ const problems = [];if (price > 0 && state.agentId) {const amountAtomics = Math.round(price * 1_000_000);- promises.push(- apiPost(`/api/agents/${state.agentId}/skills/set-price`, {+ try {+ await apiJson('POST', `/api/agents/${state.agentId}/skills/set-price`, {skill: 'chat',amount: amountAtomics,currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',chain: 'solana',mint_decimals: 6,- }).catch(() => {}),- );+ });+ } catch (err) {+ if (isSignedOut(err)) throw err;+ problems.push(`the price (${err.message})`);+ }}if (wallet) {- const chain = detectChain(wallet).toLowerCase().includes('eth') ? 'base' : 'solana';- promises.push(- apiPost('/api/billing/payout-wallets', {+ const chain = detectChain(wallet) === 'ETH/BASE' ? 'base' : 'solana';+ try {+ await apiJson('POST', '/api/billing/payout-wallets', {chain,address: wallet,- label: 'Wizard setup',- }).catch(() => {}),- );+ agent_id: state.agentId,+ is_default: true,+ });+ } catch (err) {+ if (isSignedOut(err)) throw err;+ problems.push(`the payout wallet (${err.message})`);+ }}- await Promise.allSettled(promises);+ return problems;}// ── Navigation logic ───────────────────────────────────────────────────────@@ -585,17 +729,37 @@ function validateStep() {return true;}+function finishWizard() {+ try { sessionStorage.removeItem(STORAGE_KEY); } catch {}+ location.href = '/dashboard?welcome=1';+}+async function goNext() {if (!validateStep()) return;if (state.step === 5) {- $('btn-next').disabled = true;- $('btn-next').textContent = 'Saving…';+ const nextBtn = $('btn-next');+ const originalLabel = nextBtn.textContent;+ nextBtn.disabled = true;+ nextBtn.textContent = 'Saving…';if (hasCryptoSkills()) {- await saveEarnSettings().catch(() => {});+ let problems;+ try {+ problems = await saveEarnSettings();+ } catch (err) {+ nextBtn.disabled = false;+ nextBtn.textContent = originalLabel;+ showError('Your session ended. Sign in to save these settings.', { href: loginHref('/login'), label: 'Sign in' });+ return;+ }+ if (problems.length) {+ nextBtn.disabled = false;+ nextBtn.textContent = originalLabel;+ showError(`We could not save ${problems.join(' and ')}. Fix it and try again, or skip this step.`);+ return;+ }}- sessionStorage.removeItem(STORAGE_KEY);- location.href = '/dashboard?welcome=1';+ finishWizard();return;}@@ -617,9 +781,7 @@ function skipStep() {saveState(state);renderStep();} else if (state.step === 5) {- // Skip earning setup, go to dashboard- sessionStorage.removeItem(STORAGE_KEY);- location.href = '/dashboard?welcome=1';+ finishWizard();}}@@ -638,19 +800,17 @@ document.addEventListener('keydown', (e) => {});// ── Step 1: Avatar method selection ───────────────────────────────────────+// The creation pages capture ?next= (src/shared/wizard-return.js) and bring+// the finished avatar back here as ?avatarId=&avatarName=&avatarThumb=.-$('btn-selfie').addEventListener('click', () => {+function leaveForAvatar(path, from) {saveState(state);- // Navigate to selfie flow, expect return with ?avatarId=- const returnUrl = encodeURIComponent(location.origin + '/start?from=selfie');- location.href = `/create/selfie?wizard=1&next=${returnUrl}`;-});+ const returnUrl = encodeURIComponent(`${START_PATH}?from=${from}`);+ location.href = `${path}?wizard=1&next=${returnUrl}`;+}-$('btn-editor').addEventListener('click', () => {- saveState(state);- const returnUrl = encodeURIComponent(location.origin + '/start?from=editor');- location.href = `/create?wizard=1&next=${returnUrl}`;-});+$('btn-selfie').addEventListener('click', () => leaveForAvatar('/create/selfie', 'selfie'));+$('btn-editor').addEventListener('click', () => leaveForAvatar('/create', 'editor'));$('btn-upload').addEventListener('click', () => {$('glb-file-input').click();@@ -660,46 +820,56 @@ $('glb-file-input').addEventListener('change', async (e) => {const file = e.target.files?.[0];if (!file) return;if (file.size > 50 * 1024 * 1024) {- showError('File too large — maximum 50 MB.');+ showError('File too large: the maximum is 50 MB.');+ e.target.value = '';+ return;+ }+ if (!/\.(glb|gltf)$/i.test(file.name)) {+ showError('Choose a .glb or .gltf file.');+ e.target.value = '';return;}const btn = $('btn-upload');- const origLabel = btn.querySelector('.wz-avatar-card-label').textContent;- btn.querySelector('.wz-avatar-card-label').textContent = 'Uploading…';+ const labelEl = btn.querySelector('.wz-avatar-card-label');+ const origLabel = labelEl.textContent;+ labelEl.textContent = 'Uploading… 0%';btn.disabled = true;try {- // Get CSRF token first- const token = await getCsrfToken();- _csrf = null;-- const fd = new FormData();- fd.append('file', file);- fd.append('name', file.name.replace(/\.(glb|gltf)$/i, '') || 'My Avatar');- fd.append('visibility', 'private');-- const r = await fetch('/api/avatars', {- method: 'POST',- headers: { 'X-CSRF-Token': token },- credentials: 'include',- body: fd,- });- const j = await r.json();- if (!r.ok) throw new Error(j.error_description || j.error || `Upload failed ${r.status}`);+ const name = file.name.replace(/\.(glb|gltf)$/i, '') || 'My Avatar';+ // Presign, upload to storage, then register the record: the same path+ // every other upload surface uses. /api/avatars itself only accepts+ // the registration step, never a multipart body.+ const avatar = await saveRemoteGlbToAccount(+ file,+ {+ name,+ source: 'direct-upload',+ visibility: 'private',+ source_meta: { generator: 'start-wizard' },+ },+ {+ onProgress: (pct) => { labelEl.textContent = `Uploading… ${Math.round(pct)}%`; },+ },+ );- const av = j.avatar || j;- state.avatarId = av.id;- state.avatarName = av.name || file.name;- state.avatarThumb = av.thumbnail_url || '';+ state.avatarId = avatar.id;+ state.avatarName = avatar.name || name;+ state.avatarThumb = avatar.thumbnail_url || '';saveState(state);renderStep1();+ try { window.__twsGuide?.complete('create', { silent: true }); } catch {}} catch (err) {log.error('[wizard/upload]', err);- showError(err.message || 'Upload failed. Please try again.');+ if (isSignedOut(err)) {+ showError('Sign in to upload your own model.', { href: loginHref('/login'), label: 'Sign in' });+ } else {+ showError(err.message || 'Upload failed. Please try again.');+ }} finally {- btn.querySelector('.wz-avatar-card-label').textContent = origLabel;+ labelEl.textContent = origLabel;btn.disabled = false;e.target.value = '';}@@ -739,6 +909,7 @@ document.querySelectorAll('[data-preset]').forEach((btn) => {document.querySelectorAll('[data-model]').forEach((btn) => {btn.addEventListener('click', () => {+ if (!MODELS[btn.dataset.model]) return;document.querySelectorAll('[data-model]').forEach((b) => {b.classList.remove('active');b.setAttribute('aria-pressed', 'false');@@ -813,8 +984,8 @@ $('earn-wallet').addEventListener('input', () => {});// ── Step 5: Earn price USD equivalent ────────────────────────────────────-// USDC is pegged 1:1 to USD — show "≈ $X.XXX per call" so users know-// exactly what they're charging in dollars.+// USDC is pegged 1:1 to USD, so the "≈ $0.001 per call" hint tells users exactly what+// they are charging in dollars.function updateEarnPriceHint() {const hint = $('earn-price-usd-hint');@@ -828,9 +999,46 @@ function updateEarnPriceHint() {$('earn-price').addEventListener('input', updateEarnPriceHint);updateEarnPriceHint();+// ── Helper-widget clearance ───────────────────────────────────────────────+// The shared corner stack (public/corner-stack.js) lifts itself above the+// sticky footer, but on a phone its pills still float over the bottom of the+// scrolling step. Mirror its live height into a CSS variable the steps use+// as extra bottom padding, so the last control can always scroll clear.++function trackHelperClearance() {+ const root = document.documentElement;+ let observed = null;+ const apply = () => {+ const stack = document.getElementById('tws-corner-stack');+ const h = stack ? stack.getBoundingClientRect().height : 0;+ root.style.setProperty('--wz-helper-clearance', h > 0 ? `${Math.round(h) + 12}px` : '0px');+ };+ const watch = () => {+ const stack = document.getElementById('tws-corner-stack');+ if (!stack || stack === observed) return;+ observed = stack;+ if ('ResizeObserver' in window) new ResizeObserver(apply).observe(stack);+ apply();+ };+ watch();+ // The stack mounts lazily, after the deferred helper scripts run.+ if ('MutationObserver' in window) {+ new MutationObserver(watch).observe(document.body, { childList: true });+ }+ window.addEventListener('tws-corner-stack:ready', watch);+ window.addEventListener('resize', apply);+}++trackHelperClearance();+// ── Initial render ─────────────────────────────────────────────────────────-// initTemplateGallery may call renderStep() itself (template apply or ?template= param).-// Only call renderStep() here if the gallery didn't already do it.-const _galleryRendered = initTemplateGallery();-if (!_galleryRendered) renderStep();+// Resolve the session first so a signed-out visitor who lands on step 4 (a+// saved session, or the sign-in round trip) sees the sign-in panel instead of+// a request that can only fail. The probe is one fast GET; when it errors the+// deploy step still discovers a 401 on its own.+resolveAuth().finally(() => {+ // initTemplateGallery may call renderStep() itself (template apply or ?template= param).+ const galleryRendered = initTemplateGallery();+ if (!galleryRendered) renderStep();+});diff --git a/src/templates.js b/src/templates.jsindex 21815ee10..adc4c731a 100644--- a/src/templates.js+++ b/src/templates.js@@ -15,7 +15,7 @@ export const TEMPLATES = [tagline: 'Clear answers, no filler — gets things done',bio: 'A helpful, honest assistant. Clear and concise answers. No filler. Gets things done.',skills: ['memory', 'think', 'web'],- model: 'claude-sonnet-4-5',+ model: 'claude-sonnet-4-6',icon: '✅',cryptoMode: false,},@@ -25,7 +25,7 @@ export const TEMPLATES = [tagline: 'Digs into any topic and delivers sourced insights',bio: 'A sharp web researcher who digs into any topic, synthesizes sources, and delivers clear, well-organized insights on demand.',skills: ['memory', 'think', 'web'],- model: 'claude-sonnet-4-5',+ model: 'claude-sonnet-4-6',icon: '🔍',cryptoMode: false,},@@ -35,7 +35,7 @@ export const TEMPLATES = [tagline: 'Answers questions, resolves issues, keeps users happy',bio: 'A calm, helpful customer support agent who answers questions thoroughly, resolves issues efficiently, and keeps users feeling heard.',skills: ['memory', 'think'],- model: 'claude-sonnet-4-5',+ model: 'claude-sonnet-4-6',icon: '💬',cryptoMode: false,},@@ -45,7 +45,7 @@ export const TEMPLATES = [tagline: 'Explains complex topics in plain, engaging language',bio: 'A patient, knowledgeable tutor who breaks down complex subjects into clear explanations, adapts to any skill level, and uses examples to make ideas stick.',skills: ['memory', 'think', 'web'],- model: 'claude-sonnet-4-5',+ model: 'claude-sonnet-4-6',icon: '📚',cryptoMode: false,},@@ -55,7 +55,7 @@ export const TEMPLATES = [tagline: 'Brainstorms concepts, develops ideas across any medium',bio: 'A creative collaborator with a bold visual aesthetic. Helps brainstorm concepts, generate ideas, and develop artistic projects across any medium.',skills: ['memory', 'think'],- model: 'claude-sonnet-4-5',+ model: 'claude-sonnet-4-6',icon: '🎨',cryptoMode: false,},@@ -65,7 +65,7 @@ export const TEMPLATES = [tagline: 'Episode ideas, interview questions, polished show notes',bio: 'A conversational podcast host with a knack for storytelling. Brainstorms episode ideas, drafts interview questions, and writes engaging show notes.',skills: ['memory', 'think'],- model: 'claude-sonnet-4-5',+ model: 'claude-sonnet-4-6',icon: '🎙️',cryptoMode: false,},@@ -75,7 +75,7 @@ export const TEMPLATES = [tagline: 'Monitors Solana launches, tracks whale moves in real time',bio: 'A crypto-savvy assistant that monitors Solana token launches, tracks whale movements, and helps users make informed trading decisions in real time.',skills: ['memory', 'think', 'pumpfun', 'solana'],- model: 'claude-sonnet-4-5',+ model: 'claude-sonnet-4-6',icon: '◎',cryptoMode: true,},@@ -85,7 +85,7 @@ export const TEMPLATES = [tagline: 'Liquidity pools, yield strategies, cross-chain analytics',bio: 'A DeFi expert fluent in liquidity pools, yield strategies, blockchain analytics, and protocol mechanics across Solana and EVM networks.',skills: ['memory', 'think', 'pumpfun', 'solana', 'x402'],- model: 'claude-sonnet-4-5',+ model: 'claude-sonnet-4-6',icon: '💹',cryptoMode: true,},diff --git a/tests/e2e/start-wizard.spec.js b/tests/e2e/start-wizard.spec.jsnew file mode 100644index 000000000..d390ac5a6--- /dev/null+++ b/tests/e2e/start-wizard.spec.js@@ -0,0 +1,188 @@+/**+ * /start onboarding wizard: end-to-end smoke.+ *+ * Drives the shipped wizard (pages/start.html + src/start.js) through the+ * no-avatar path and asserts the contract the deploy step has with the API:+ * • POST /api/agents carries the name and the resolved skill list+ * • PUT /api/agents/:id/embed-policy applies the chosen brain model+ * • POST /api/widgets is created for that agent, and the snippet handed out+ * points at the real loader (/embed.js with data-widget)+ * • a failed create shows a retry that finishes the publish+ * • a signed-out visitor gets a sign-in panel, never a failing request+ * • off-screen steps are inert and the footer's Continue is not covered by+ * the shared helper-widget corner stack+ * • an avatar coming back from a creation page is attached without double+ * decoding its name+ *+ * Auth, CSRF, and the three mutation endpoints are fulfilled at the Playwright+ * route layer so the run is deterministic and never writes to the database;+ * everything between the click and the assertion is the product code.+ */++import { test, expect } from '@playwright/test';++const FIXTURE_USER = { id: 'usr_e2e_start', handle: 'e2e-start', display_name: 'E2E Start', plan: 'free' };+const AGENT_ID = '3d3f9c1e-6c3b-4d2e-9a3a-1b2c3d4e5f60';+const WIDGET_ID = 'wdgt_e2e_start';++function jsonRoute(status, body) {+ return (route) => route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(body) });+}++async function installFixtures(page, { signedIn = true, failFirstCreate = false } = {}) {+ const calls = { agents: [], policies: [], widgets: [] };+ await page.route('**/api/auth/me**', jsonRoute(200, { user: signedIn ? FIXTURE_USER : null }));+ await page.route('**/api/csrf-token**', jsonRoute(200, {+ token: 'csrf-e2e', expires_in: 600, data: { token: 'csrf-e2e', expires_in: 600 },+ }));+ await page.route('**/api/agents', (route, req) => {+ if (req.method() !== 'POST') return route.fallback();+ calls.agents.push(req.postDataJSON());+ if (failFirstCreate && calls.agents.length === 1) return route.abort('failed');+ return route.fulfill({+ status: 201, contentType: 'application/json',+ body: JSON.stringify({ agent: { id: AGENT_ID, name: calls.agents.at(-1).name } }),+ });+ });+ await page.route(`**/api/agents/${AGENT_ID}/embed-policy`, (route, req) => {+ calls.policies.push(req.postDataJSON());+ return route.fulfill({+ status: 200, contentType: 'application/json',+ body: JSON.stringify({ policy: { brain: req.postDataJSON().brain } }),+ });+ });+ await page.route('**/api/widgets', (route, req) => {+ if (req.method() !== 'POST') return route.fallback();+ calls.widgets.push(req.postDataJSON());+ return route.fulfill({+ status: 201, contentType: 'application/json',+ body: JSON.stringify({ widget: { id: WIDGET_ID } }),+ });+ });+ return calls;+}++/** Start from scratch, skip the avatar, name the agent, pick a model, reach step 4. */+async function reachDeploy(page, { model = 'llama-3.3-70b-versatile' } = {}) {+ await page.goto('/start');+ await page.locator('#btn-blank-start').click();+ await expect(page.locator('#step-1')).toHaveClass(/active/);+ await page.locator('#btn-skip-step').click({ timeout: 5_000 });+ await expect(page.locator('#step-2')).toHaveClass(/active/);+ await page.locator('#agent-name').fill('E2E Wizard Agent');+ await page.locator(`[data-model="${model}"]`).click();+ await page.locator('#btn-next').click({ timeout: 5_000 });+ await expect(page.locator('#step-3')).toHaveClass(/active/);+ await page.locator('#btn-next').click({ timeout: 5_000 });+ await expect(page.locator('#step-4')).toHaveClass(/active/);+}++test.describe('/start wizard', () => {+ test.beforeEach(async ({ page }) => {+ page.on('pageerror', (err) => {+ // Vite's dev-only HMR socket noise is not a product error.+ if (/WebSocket closed without opened/i.test(err.message)) return;+ throw new Error(`Uncaught page error: ${err.message}`);+ });+ });++ test('publishes the agent, applies the chosen brain, and hands out the real embed snippet', async ({ page }) => {+ test.setTimeout(90_000);+ const calls = await installFixtures(page);+ await reachDeploy(page);++ await expect(page.locator('#deploy-success')).toBeVisible({ timeout: 15_000 });+ await expect(page.locator('#deploy-live-url')).toContainText(`/agents/${AGENT_ID}`);+ await expect(page.locator('#deploy-live-link')).toHaveAttribute('href', new RegExp(`/agents/${AGENT_ID}$`));+ const snippet = await page.locator('#embed-code').textContent();+ expect(snippet).toContain('/embed.js');+ expect(snippet).toContain(`data-widget="${WIDGET_ID}"`);+ await expect(page.locator('#deploy-brain')).toContainText('Llama 3.3 70B');++ expect(calls.agents).toHaveLength(1);+ expect(calls.agents[0].name).toBe('E2E Wizard Agent');+ expect(calls.agents[0].skills).toEqual(expect.arrayContaining(['greet', 'remember', 'think']));+ expect(calls.policies).toEqual([{ brain: { model: 'llama-3.3-70b-versatile' } }]);+ expect(calls.widgets).toHaveLength(1);+ expect(calls.widgets[0]).toMatchObject({ type: 'talking-agent', config: { agent_id: AGENT_ID }, is_public: true });++ // One heading in the accessibility tree at a time.+ await expect(page.locator('h1:visible')).toHaveCount(1);++ await page.locator('#btn-next').click({ timeout: 5_000 });+ await expect(page.locator('#step-5')).toHaveClass(/active/);+ await expect(page.locator('#btn-next')).toHaveText('Go to dashboard');+ });++ test('a failed create shows a retry that finishes the publish', async ({ page }) => {+ test.setTimeout(90_000);+ const calls = await installFixtures(page, { failFirstCreate: true });+ await reachDeploy(page);++ const retry = page.locator('#deploy-status .wz-deploy-retry');+ await expect(retry).toBeVisible({ timeout: 15_000 });+ await expect(page.locator('#step4-headline')).toHaveText('Publishing hit a snag');+ await expect(page.locator('#deploy-label')).not.toHaveText('');+ await expect(page.locator('#btn-next')).toBeHidden();++ await retry.click();+ await expect(page.locator('#deploy-success')).toBeVisible({ timeout: 15_000 });+ expect(calls.agents).toHaveLength(2);+ expect(calls.widgets).toHaveLength(1);+ });++ test('a signed-out visitor is offered sign-in at the deploy step, not a failing request', async ({ page }) => {+ test.setTimeout(90_000);+ const calls = await installFixtures(page, { signedIn: false });+ await reachDeploy(page);++ const panel = page.locator('#deploy-signin');+ await expect(panel).toBeVisible();+ await expect(page.locator('#step4-headline')).toHaveText('Publish your agent');+ await expect(page.locator('#deploy-signin-login')).toHaveAttribute('href', '/login?next=%2Fstart');+ await expect(page.locator('#deploy-signin-register')).toHaveAttribute('href', '/register?next=%2Fstart');+ await expect(page.locator('#deploy-status')).toBeHidden();+ await expect(page.locator('#btn-next')).toBeHidden();+ expect(calls.agents).toHaveLength(0);++ // The saved session survives a reload and lands straight back on the panel.+ await page.reload();+ await expect(page.locator('#step-4')).toHaveClass(/active/);+ await expect(panel).toBeVisible();+ });++ test('off-screen steps are inert and Continue is not covered by helper widgets', async ({ page }) => {+ test.setTimeout(90_000);+ await installFixtures(page);+ await page.setViewportSize({ width: 1440, height: 900 });+ await page.goto('/start');+ await page.locator('#btn-blank-start').click();+ await page.locator('#btn-skip-step').click({ timeout: 5_000 });+ await expect(page.locator('#step-2')).toHaveClass(/active/);++ await expect(page.locator('.wz-step[inert]')).toHaveCount(4);+ await expect(page.locator('.wz-step.active[inert]')).toHaveCount(0);+ await expect(page.locator('h1:visible')).toHaveCount(1);+ // Playwright's actionability check fails when another element would+ // receive the click; before the sticky footer the corner stack sat here.+ await page.locator('#btn-next').click({ trial: true, timeout: 5_000 });++ for (const width of [320, 768, 1440]) {+ await page.setViewportSize({ width, height: 800 });+ const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);+ expect(overflow, `horizontal overflow at ${width}px`).toBe(0);+ }+ });++ test('an avatar returning from a creation page is attached, name intact', async ({ page }) => {+ test.setTimeout(90_000);+ await installFixtures(page);+ await page.goto('/start?avatarId=ava-e2e-one&avatarName=Luna%20100%25&avatarThumb=%2Ffavicon-32x32.png&from=selfie');+ await expect(page.locator('#step-2')).toHaveClass(/active/);+ await expect(page).toHaveURL(/\/start$/);+ await page.locator('#btn-back').click({ timeout: 5_000 });+ await expect(page.locator('#step-1')).toHaveClass(/active/);+ await expect(page.locator('#ap-name')).toHaveText('Luna 100%');+ await expect(page.locator('#avatar-method-grid')).toBeHidden();+ });+});diff --git a/tests/wizard-return.test.js b/tests/wizard-return.test.jsnew file mode 100644index 000000000..a41909679--- /dev/null+++ b/tests/wizard-return.test.js@@ -0,0 +1,99 @@+/**+ * Wizard return contract (src/shared/wizard-return.js).+ *+ * The /start wizard sends people to an avatar-producing page and expects the+ * finished avatar handed back. These tests pin the safety rules of that hop:+ * only a same-origin /start path is ever stored, stale entries expire, and+ * the hand-back URL carries the avatar fields the wizard reads.+ */+import { describe, it, expect } from 'vitest';+import {+ sanitizeWizardReturn,+ captureWizardReturn,+ pendingWizardReturn,+ clearWizardReturn,+ wizardReturnUrl,+ WIZARD_RETURN_KEY,+ WIZARD_RETURN_TTL_MS,+} from '../src/shared/wizard-return.js';++const ORIGIN = 'https://three.ws';++function memoryStorage() {+ const map = new Map();+ return {+ getItem: (k) => (map.has(k) ? map.get(k) : null),+ setItem: (k, v) => map.set(k, String(v)),+ removeItem: (k) => map.delete(k),+ };+}++describe('sanitizeWizardReturn', () => {+ it('accepts a bare /start path and keeps its query', () => {+ expect(sanitizeWizardReturn('/start?from=selfie', ORIGIN)).toBe('/start?from=selfie');+ });+ it('accepts an absolute same-origin /start URL', () => {+ expect(sanitizeWizardReturn('https://three.ws/start', ORIGIN)).toBe('/start');+ });+ it('rejects other origins, protocol-relative hosts, and non-wizard paths', () => {+ expect(sanitizeWizardReturn('https://evil.example/start', ORIGIN)).toBeNull();+ expect(sanitizeWizardReturn('//evil.example/start', ORIGIN)).toBeNull();+ expect(sanitizeWizardReturn('/dashboard', ORIGIN)).toBeNull();+ expect(sanitizeWizardReturn('/startup', ORIGIN)).toBeNull();+ expect(sanitizeWizardReturn('javascript:alert(1)', ORIGIN)).toBeNull();+ expect(sanitizeWizardReturn('', ORIGIN)).toBeNull();+ expect(sanitizeWizardReturn(null, ORIGIN)).toBeNull();+ });+});++describe('captureWizardReturn / pendingWizardReturn', () => {+ it('stores a valid next= target and reads it back', () => {+ const storage = memoryStorage();+ const url = new URL('https://three.ws/create/selfie?wizard=1&next=%2Fstart%3Ffrom%3Dselfie');+ expect(captureWizardReturn({ url, storage, now: 1000 })).toBe('/start?from=selfie');+ expect(pendingWizardReturn({ storage, now: 2000 })).toBe('/start?from=selfie');+ });+ it('ignores an invalid next= target and leaves storage untouched', () => {+ const storage = memoryStorage();+ const url = new URL('https://three.ws/create?next=https%3A%2F%2Fevil.example%2Fstart');+ expect(captureWizardReturn({ url, storage })).toBeNull();+ expect(storage.getItem(WIZARD_RETURN_KEY)).toBeNull();+ });+ it('expires an entry older than the TTL', () => {+ const storage = memoryStorage();+ const url = new URL('https://three.ws/create?next=%2Fstart');+ captureWizardReturn({ url, storage, now: 0 });+ expect(pendingWizardReturn({ storage, now: WIZARD_RETURN_TTL_MS + 1 })).toBeNull();+ expect(storage.getItem(WIZARD_RETURN_KEY)).toBeNull();+ });+ it('survives a corrupt entry', () => {+ const storage = memoryStorage();+ storage.setItem(WIZARD_RETURN_KEY, '{not json');+ expect(pendingWizardReturn({ storage })).toBeNull();+ });+ it('clears on demand', () => {+ const storage = memoryStorage();+ captureWizardReturn({ url: new URL('https://three.ws/create?next=%2Fstart'), storage });+ clearWizardReturn({ storage });+ expect(pendingWizardReturn({ storage })).toBeNull();+ });+});++describe('wizardReturnUrl', () => {+ it('appends the avatar fields the wizard reads and preserves the stored query', () => {+ const out = wizardReturnUrl('/start?from=selfie', {+ avatarId: 'ava-1',+ avatarName: 'Luna 100%',+ avatarThumb: 'https://cdn.example/t.png?x=1&y=2',+ });+ const url = new URL(out, ORIGIN);+ expect(url.pathname).toBe('/start');+ expect(url.searchParams.get('from')).toBe('selfie');+ expect(url.searchParams.get('avatarId')).toBe('ava-1');+ expect(url.searchParams.get('avatarName')).toBe('Luna 100%');+ expect(url.searchParams.get('avatarThumb')).toBe('https://cdn.example/t.png?x=1&y=2');+ });+ it('omits empty optional fields', () => {+ expect(wizardReturnUrl('/start', { avatarId: 'a' })).toBe('/start?avatarId=a');+ });+});