Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(dashboard): show the retention cohorts, the Farcaster consent flow, and voice key setup in the product

nirholase5b400fe27ba
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 9a3034ec3..458bebdd1 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -159,6 +159,48 @@ Requires auth. Owner only. Soft-deletes the agent on the platform. Does not affe
---
+### Signed manifest
+
+```
+GET /api/agents/:id/manifest/signed
+GET /api/agents/:id/manifest/history
+POST /api/agents/:id/manifest/publish
+GET /api/manifest-verify?cid=<cid>
+```
+
+The agent's full configuration, system prompt included, canonicalized, ed25519-signed by the platform attester identity, and pinned to IPFS. Published automatically on every persona save. The first three reads are public and CORS-open; `publish` is owner-only.
+
+**`GET /manifest/signed` response**
+
+```json
+{
+ "agent_id": "b2b1...",
+ "cid": "bafy...",
+ "pinned": true,
+ "digest": "3f9c...",
+ "issuer": "6Yb...",
+ "signed_at": "2026-08-11T12:00:00.000Z",
+ "verified": true,
+ "gatewayUrls": ["https://ipfs.io/ipfs/bafy..."],
+ "verifyUrl": "/api/manifest-verify?cid=bafy...",
+ "envelope": { "spec": "threews.agent.manifest.v1", "manifest": {} }
+}
+```
+
+Returns `404 not_published` when the agent has never published a manifest.
+
+**`GET /api/manifest-verify`** fetches the envelope from public IPFS gateways (not from our database), verifies the signature, and diffs the pinned manifest against the agent's live configuration. Accepts `cid`, `digest`, or `agent`. `verified` is true only when the signature checks out **and** the issuer is the platform identity; `signature_valid` and `issuer_trusted` are reported separately so an envelope signed by an unknown key can never read as ours. `drift.changed` names every field that moved since the pin.
+
+Verify it yourself, with no account:
+
+```bash
+node scripts/verify-agent-manifest.mjs --cid bafy...
+```
+
+Full reference: [Agent Manifest](./agent-manifest.md#signed-manifests-v03). Wire format: [specs/AGENT_MANIFEST.md](../specs/AGENT_MANIFEST.md#signed-envelope-v03).
+
+---
+
### Link wallet to agent
```
diff --git a/src/dashboard-next/farcaster-seed.js b/src/dashboard-next/farcaster-seed.js
new file mode 100644
index 000000000..1cee056f5
--- /dev/null
+++ b/src/dashboard-next/farcaster-seed.js
@@ -0,0 +1,430 @@
+// Consent-first Farcaster memory seeding, as a self-contained panel.
+//
+// The flow the user walks, and why it is shaped this way: Farcaster has no
+// OAuth and we deliberately never ask for a signer, so ownership of the account
+// is proved with a wallet the fid has already verified on the protocol. Solana
+// leads, because that is the home chain and the wallet our users already have
+// connected. Nothing is read into memory until the signature verifies, and the
+// same panel that grants consent is the one that revokes it.
+//
+// look up → review exactly what will be read → sign with a verified
+// wallet → seeded → revoke (deletes every memory the grant produced)
+//
+// Mounted by src/dashboard-next/pages/agents.js inside the agent persona editor.
+
+import { get, post, del, esc, ApiError } from './api.js';
+import { toast } from '../shared/toast.js';
+
+const DIM = 'var(--nxt-ink-dim)';
+const INK = 'var(--nxt-ink)';
+const DANGER = 'var(--nxt-danger)';
+
+function solanaProvider() {
+ return window.phantom?.solana || window.solana || null;
+}
+
+// Base64 of an ed25519 signature — the server (verifySiwsSignature) accepts base64.
+function bytesToB64(bytes) {
+ const arr = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
+ let bin = '';
+ for (const b of arr) bin += String.fromCharCode(b);
+ return btoa(bin);
+}
+
+function ethereumProvider() {
+ return window.ethereum || null;
+}
+
+function shortAddress(address) {
+ const a = String(address || '');
+ return a.length > 14 ? `${a.slice(0, 6)}…${a.slice(-4)}` : a;
+}
+
+function formatDate(value) {
+ if (!value) return null;
+ const d = new Date(value);
+ return Number.isNaN(d.getTime()) ? null : d.toLocaleDateString();
+}
+
+function messageFor(err) {
+ if (err instanceof ApiError) return err.message || err.code;
+ return err?.message || 'Something went wrong.';
+}
+
+/**
+ * Ask the wallet to sign the consent text. Solana signs ed25519 through the
+ * injected provider; an EVM verification falls back to personal_sign so a fid
+ * that only ever verified an Ethereum address is not locked out.
+ */
+async function signConsent({ chain, address, message }) {
+ if (chain === 'solana') {
+ const provider = solanaProvider();
+ if (!provider?.signMessage) {
+ throw new Error('No Solana wallet found. Install Phantom (phantom.com) and reload.');
+ }
+ const connected = await provider.connect();
+ const active = (connected?.publicKey || provider.publicKey)?.toString();
+ if (active && active !== address) {
+ throw new Error(`Switch your wallet to ${shortAddress(address)} — that is the wallet this Farcaster account verified.`);
+ }
+ const signed = await provider.signMessage(new TextEncoder().encode(message), 'utf8');
+ return bytesToB64(signed?.signature ?? signed);
+ }
+
+ const provider = ethereumProvider();
+ if (!provider?.request) throw new Error('No Ethereum wallet found in this browser.');
+ const accounts = await provider.request({ method: 'eth_requestAccounts' });
+ const active = String(accounts?.[0] || '').toLowerCase();
+ if (active && active !== String(address).toLowerCase()) {
+ throw new Error(`Switch your wallet to ${shortAddress(address)} — that is the wallet this Farcaster account verified.`);
+ }
+ return provider.request({ method: 'personal_sign', params: [message, address] });
+}
+
+/**
+ * Mount the panel into `host` for one agent.
+ * Returns a `refresh()` the caller can use to re-read status.
+ */
+export function mountFarcasterSeed(host, { agentId }) {
+ const base = `/api/agents/${encodeURIComponent(agentId)}/memory/seed/farcaster`;
+ let challenge = null;
+
+ const render = (html) => {
+ host.innerHTML = html;
+ };
+
+ const setBusy = (button, busyLabel) => {
+ const original = button.textContent;
+ button.disabled = true;
+ button.setAttribute('aria-busy', 'true');
+ button.textContent = busyLabel;
+ return () => {
+ button.disabled = false;
+ button.removeAttribute('aria-busy');
+ button.textContent = original;
+ };
+ };
+
+ const showError = (message) => {
+ const slot = host.querySelector('[data-slot="fc-error"]');
+ if (slot) {
+ slot.textContent = message;
+ slot.hidden = false;
+ } else {
+ toast(message);
+ }
+ };
+
+ // ── Views ────────────────────────────────────────────────────────────────
+
+ function loadingView() {
+ render(`
+ <div class="fc-seed" aria-busy="true">
+ <div class="fc-skeleton" style="width:60%"></div>
+ <div class="fc-skeleton" style="width:85%"></div>
+ </div>
+ `);
+ }
+
+ function errorView(message) {
+ render(`
+ <div class="fc-seed">
+ <div style="font-size:12.5px;color:${DANGER};margin-bottom:8px">${esc(message)}</div>
+ <button class="dn-btn" type="button" data-action="fc-retry">Try again</button>
+ </div>
+ `);
+ host.querySelector('[data-action="fc-retry"]').addEventListener('click', refresh);
+ }
+
+ function disconnectedView() {
+ render(`
+ <div class="fc-seed">
+ <div style="font-size:12.5px;color:${DIM};margin-bottom:10px">
+ Give this agent your Farcaster voice. We read only your <strong style="color:${INK}">public profile and casts</strong>,
+ and only after you prove the account is yours by signing with a wallet it has already verified. Nothing is
+ stored before you sign, and revoking deletes every memory this created.
+ </div>
+ <div style="display:grid;grid-template-columns:1fr auto;gap:8px">
+ <label style="display:contents">
+ <span class="fc-sr-only">Farcaster username or FID</span>
+ <input data-slot="fc-handle" type="text" maxlength="64" placeholder="Farcaster username or FID"
+ aria-label="Farcaster username or FID" class="fc-input" />
+ </label>
+ <button class="dn-btn" type="button" data-action="fc-lookup" style="flex-shrink:0">Connect Farcaster</button>
+ </div>
+ <div data-slot="fc-error" role="alert" hidden style="font-size:12.5px;color:${DANGER};margin-top:8px"></div>
+ </div>
+ `);
+
+ const input = host.querySelector('[data-slot="fc-handle"]');
+ const button = host.querySelector('[data-action="fc-lookup"]');
+ button.addEventListener('click', () => lookup(input.value, button));
+ input.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ lookup(input.value, button);
+ }
+ });
+ }
+
+ function consentView(data) {
+ challenge = data;
+ const wallets = [
+ ...(data.wallets?.solana || []).map((address) => ({ address, chain: 'solana' })),
+ ...(data.wallets?.ethereum || []).map((address) => ({ address, chain: 'ethereum' })),
+ ];
+ const profile = data.profile || {};
+ const picker =
+ wallets.length > 1
+ ? `<label style="display:block;margin-top:10px;font-size:12px;color:${DIM}">
+ Sign with
+ <select data-slot="fc-wallet" class="fc-input" style="margin-top:4px;width:100%">
+ ${wallets
+ .map(
+ (w) =>
+ `<option value="${esc(w.address)}" ${w.address === data.address ? 'selected' : ''}>${esc(shortAddress(w.address))} · ${esc(w.chain === 'solana' ? 'Solana' : 'Ethereum')}</option>`,
+ )
+ .join('')}
+ </select>
+ </label>`
+ : '';
+
+ render(`
+ <div class="fc-seed">
+ <div class="fc-card">
+ <div style="display:flex;align-items:center;gap:10px">
+ ${profile.pfp_url ? `<img src="${esc(profile.pfp_url)}" alt="" width="36" height="36" style="border-radius:50%;object-fit:cover;flex-shrink:0" />` : ''}
+ <div style="min-width:0">
+ <div style="font-size:13px;font-weight:600;color:${INK};overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
+ ${esc(profile.display_name || profile.fname || `FID ${profile.fid}`)}
+ </div>
+ <div style="font-size:12px;color:${DIM}">@${esc(profile.fname || profile.fid)} · FID ${esc(String(profile.fid))}</div>
+ </div>
+ </div>
+ ${profile.bio ? `<div style="font-size:12px;color:${DIM};margin-top:8px">${esc(profile.bio)}</div>` : ''}
+ </div>
+
+ <div style="font-size:12.5px;color:${DIM};margin-top:12px">
+ <div style="color:${INK};font-weight:600;margin-bottom:4px">What this grants</div>
+ <ul style="margin:0;padding-left:18px;display:grid;gap:3px">
+ <li>Read your public Farcaster profile and up to ${esc(String(data.cast_limit))} recent casts.</li>
+ <li>Store them as this agent's memory, so it can speak from them.</li>
+ <li>Nothing else. No posting, no signer, no private data.</li>
+ </ul>
+ <div style="margin-top:8px">Scope <code style="color:${INK}">${esc(data.scope)}</code></div>
+ </div>
+
+ ${picker}
+
+ <div style="display:flex;gap:8px;margin-top:12px;flex-wrap:wrap">
+ <button class="dn-btn primary" type="button" data-action="fc-sign">Sign with ${esc(shortAddress(data.address))}</button>
+ <button class="dn-btn ghost" type="button" data-action="fc-cancel">Cancel</button>
+ </div>
+ <div data-slot="fc-error" role="alert" hidden style="font-size:12.5px;color:${DANGER};margin-top:8px"></div>
+ </div>
+ `);
+
+ host.querySelector('[data-action="fc-cancel"]').addEventListener('click', () => {
+ challenge = null;
+ disconnectedView();
+ });
+ host.querySelector('[data-action="fc-sign"]').addEventListener('click', (e) => grant(e.currentTarget));
+
+ const select = host.querySelector('[data-slot="fc-wallet"]');
+ if (select) {
+ select.addEventListener('change', async () => {
+ // The signed text names the wallet, so choosing another one needs a new
+ // challenge rather than a re-labelled button.
+ try {
+ const next = await post(base, {
+ intent: 'challenge',
+ fid: challenge.profile.fid,
+ address: select.value,
+ });
+ consentView(next);
+ } catch (err) {
+ showError(messageFor(err));
+ }
+ });
+ }
+ }
+
+ function connectedView(status) {
+ const consent = status.consent || {};
+ const granted = formatDate(consent.granted_at);
+ const seeded = formatDate(status.seeded_at || consent.last_seeded_at);
+
+ render(`
+ <div class="fc-seed">
+ <div class="fc-card">
+ <div style="display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap">
+ <div style="min-width:0">
+ <div style="font-size:13px;font-weight:600;color:${INK}">@${esc(status.fname || status.fid)}</div>
+ <div style="font-size:12px;color:${DIM}">FID ${esc(String(status.fid))} · ${esc(String(status.memory_count))} ${status.memory_count === 1 ? 'memory' : 'memories'}${seeded ? ` · seeded ${esc(seeded)}` : ''}</div>
+ </div>
+ <span class="fc-pill">Consent active</span>
+ </div>
+ <div style="font-size:12px;color:${DIM};margin-top:8px">
+ Proved with ${esc(consent.proof_chain === 'ethereum' ? 'Ethereum' : 'Solana')} wallet
+ <code style="color:${INK}">${esc(shortAddress(consent.proof_address))}</code>${granted ? ` on ${esc(granted)}` : ''}.
+ </div>
+ </div>
+ <div style="display:flex;gap:8px;margin-top:12px;flex-wrap:wrap">
+ <button class="dn-btn" type="button" data-action="fc-reseed">Refresh memories</button>
+ <button class="dn-btn ghost" type="button" data-action="fc-revoke">Revoke and delete</button>
+ </div>
+ <div data-slot="fc-error" role="alert" hidden style="font-size:12.5px;color:${DANGER};margin-top:8px"></div>
+ </div>
+ `);
+
+ host.querySelector('[data-action="fc-reseed"]').addEventListener('click', (e) => reseed(e.currentTarget));
+ host.querySelector('[data-action="fc-revoke"]').addEventListener('click', (e) => revoke(e.currentTarget));
+ }
+
+ // ── Actions ──────────────────────────────────────────────────────────────
+
+ async function lookup(rawHandle, button) {
+ const handle = String(rawHandle || '').trim().replace(/^@/, '');
+ if (!handle) {
+ showError('Enter a Farcaster username or FID first.');
+ return;
+ }
+ const done = setBusy(button, 'Looking up…');
+ try {
+ const body = /^\d+$/.test(handle)
+ ? { intent: 'challenge', fid: Number(handle) }
+ : { intent: 'challenge', fname: handle };
+ consentView(await post(base, body));
+ } catch (err) {
+ done();
+ if (err instanceof ApiError && err.code === 'no_verified_wallet') {
+ showError(
+ 'That Farcaster account has no verified wallet, so we cannot confirm it is yours. Verify a Solana wallet on Farcaster, then try again.',
+ );
+ return;
+ }
+ showError(messageFor(err));
+ }
+ }
+
+ async function grant(button) {
+ if (!challenge) return;
+ const done = setBusy(button, 'Waiting for wallet…');
+ try {
+ const signature = await signConsent({
+ chain: challenge.chain,
+ address: challenge.address,
+ message: challenge.message,
+ });
+ button.textContent = 'Seeding memories…';
+ const result = await post(base, {
+ intent: 'grant',
+ nonce: challenge.nonce,
+ address: challenge.address,
+ chain: challenge.chain,
+ signature,
+ });
+ challenge = null;
+ toast(`Seeded ${result.seeded} ${result.seeded === 1 ? 'memory' : 'memories'} from ${result.casts_ingested} casts.`);
+ await refresh();
+ } catch (err) {
+ done();
+ // A wallet rejection is the user changing their mind, not a failure.
+ if (err?.code === 4001 || /user rejected|user denied/i.test(err?.message || '')) {
+ showError('Signature declined. Nothing was read or stored.');
+ return;
+ }
+ showError(messageFor(err));
+ }
+ }
+
+ async function reseed(button) {
+ const done = setBusy(button, 'Refreshing…');
+ try {
+ const result = await post(base, { intent: 'reseed' });
+ toast(`Refreshed to ${result.seeded} ${result.seeded === 1 ? 'memory' : 'memories'}.`);
+ await refresh();
+ } catch (err) {
+ done();
+ showError(messageFor(err));
+ }
+ }
+
+ async function revoke(button) {
+ const ok = window.confirm(
+ 'Revoke Farcaster consent? Every memory seeded from your casts will be deleted from this agent.',
+ );
+ if (!ok) return;
+ const done = setBusy(button, 'Deleting…');
+ try {
+ const result = await del(base);
+ toast(`Consent revoked. Deleted ${result.deleted} ${result.deleted === 1 ? 'memory' : 'memories'}.`);
+ await refresh();
+ } catch (err) {
+ done();
+ showError(messageFor(err));
+ }
+ }
+
+ async function refresh() {
+ loadingView();
+ try {
+ const status = await get(base);
+ challenge = null;
+ if (status.connected) connectedView(status);
+ else disconnectedView();
+ } catch (err) {
+ errorView(messageFor(err));
+ }
+ }
+
+ ensureStyles();
+ refresh();
+ return { refresh };
+}
+
+// ── Styles ──────────────────────────────────────────────────────────────────
+
+let stylesMounted = false;
+function ensureStyles() {
+ if (stylesMounted || document.getElementById('fc-seed-styles')) return;
+ stylesMounted = true;
+ const style = document.createElement('style');
+ style.id = 'fc-seed-styles';
+ style.textContent = `
+ .fc-seed .fc-input {
+ padding: 8px 11px; border-radius: 8px; border: 1px solid var(--nxt-stroke);
+ background: rgba(255, 255, 255, 0.04); color: var(--nxt-ink);
+ font: inherit; font-size: 13px; transition: border-color 140ms ease, box-shadow 140ms ease;
+ }
+ .fc-seed .fc-input:hover { border-color: var(--nxt-stroke-strong, rgba(255, 255, 255, 0.24)); }
+ .fc-seed .fc-input:focus-visible {
+ outline: none; border-color: var(--nxt-accent, #6ea8fe);
+ box-shadow: 0 0 0 3px rgba(110, 168, 254, 0.25);
+ }
+ .fc-seed .fc-card {
+ border: 1px solid var(--nxt-stroke); border-radius: 10px; padding: 12px;
+ background: rgba(255, 255, 255, 0.03);
+ }
+ .fc-seed .fc-pill {
+ font-size: 11px; font-weight: 600; letter-spacing: 0.02em; padding: 3px 8px;
+ border-radius: 999px; color: var(--nxt-ok, #4ade80);
+ background: color-mix(in srgb, var(--nxt-ok, #4ade80) 14%, transparent);
+ border: 1px solid color-mix(in srgb, var(--nxt-ok, #4ade80) 32%, transparent);
+ }
+ .fc-seed .fc-skeleton {
+ height: 12px; border-radius: 6px; margin-bottom: 8px;
+ background: linear-gradient(90deg, rgba(255,255,255,0.05), rgba(255,255,255,0.12), rgba(255,255,255,0.05));
+ background-size: 200% 100%; animation: fc-shimmer 1.3s ease-in-out infinite;
+ }
+ .fc-seed .fc-sr-only {
+ position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
+ overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0;
+ }
+ @keyframes fc-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }
+ @media (prefers-reduced-motion: reduce) {
+ .fc-seed .fc-skeleton { animation: none; }
+ }
+ `;
+ document.head.appendChild(style);
+}
diff --git a/src/dashboard-next/pages/analytics.js b/src/dashboard-next/pages/analytics.js
index 9698511e0..8421bd0c2 100644
--- a/src/dashboard-next/pages/analytics.js
+++ b/src/dashboard-next/pages/analytics.js
@@ -56,12 +56,16 @@ async function loadAndRender(root) {
const from = new Date(Date.now() - range.days * 86400_000).toISOString();
const to = new Date().toISOString();
- const [revenue, agents, widgets, summary, monRevenue] = await Promise.all([
+ const [revenue, agents, widgets, summary, monRevenue, retention] = await Promise.all([
safe(() => get(`/api/billing/revenue?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}&granularity=${range.granularity}`)),
safe(() => get('/api/agents?limit=50')),
safe(() => get('/api/widgets')),
safe(() => get('/api/billing/summary')),
safe(() => get(`/api/monetization/revenue?period=${range.key}`)),
+ // Platform-wide week-2 retention on minted agents. Admin-only upstream, so
+ // a non-admin gets a 403 that `safe` turns into null and the panel simply
+ // does not appear — no error, no empty shell.
+ safe(() => get('/api/analytics/retention?metric=week2_converse&weeks=12')),
]);
// Every primary surface (revenue, agents, widgets, summary) failing means the
@@ -125,6 +129,7 @@ async function loadAndRender(root) {
topAgent,
}));
root.appendChild(renderRevenueChart(timeseries));
+ if (retention) root.appendChild(renderRetentionChart(retention));
root.appendChild(renderTwoCol(
renderSkillBreakdown(bySkill),
renderAgentTable(agentList, widgetList, widgetStats)
@@ -355,6 +360,191 @@ function formatPeriod(p) {
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}
+// -- Week-2 retention on minted agents (Canvas 2D column chart) --
+//
+// The README roadmap's phase-2 verification metric. One column per cohort week
+// (owners grouped by the ISO week they minted their first agent on-chain), height
+// = the share of them who came back to converse on days 7..13. The dashed line is
+// the roadmap's 30% bar. Cohorts whose 14-day window is still open are drawn
+// muted and labelled "open", because their number can still move.
+
+function formatPct(rate) {
+ return rate == null ? '--' : `${(rate * 100).toFixed(1)}%`;
+}
+
+function formatCohortWeek(week) {
+ const d = new Date(`${week}T00:00:00Z`);
+ if (isNaN(d)) return String(week);
+ return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });
+}
+
+function renderRetentionChart(data) {
+ const panel = document.createElement('div');
+ panel.className = 'dn-panel ana-chart-panel';
+
+ const cohorts = data.cohorts ?? [];
+ const s = data.summary ?? {};
+ const label = data.metric_label || 'Returned to converse';
+
+ if (!cohorts.length) {
+ panel.innerHTML = `
+ <div class="dn-panel-title">Week-2 Retention · Minted Agents</div>
+ <div class="ana-chart-empty">
+ No cohorts rolled up yet. The weekly rollup fills this in once owners have minted
+ agents and their 14-day window opens.
+ </div>`;
+ return panel;
+ }
+
+ const target = Number(data.target ?? 0.3);
+ const headline = s.latestCompleteWeek
+ ? `Latest closed cohort ${formatCohortWeek(s.latestCompleteWeek)}: <strong>${formatPct(s.latestRate)}</strong>`
+ : 'No cohort has closed its 14-day window yet';
+ const pooled = s.pooledRate != null
+ ? ` · pooled <strong>${formatPct(s.pooledRate)}</strong> across ${s.completeCohorts} closed cohort${s.completeCohorts === 1 ? '' : 's'} (${s.retainedOwners}/${s.mintedOwners} owners)`
+ : '';
+
+ panel.innerHTML = `
+ <div class="dn-panel-title">Week-2 Retention · Minted Agents</div>
+ <div class="ana-ret-summary">${headline}${pooled}</div>
+ <div data-slot="ret" style="position:relative;width:100%;height:220px;margin-top:12px"></div>
+ <div class="ana-ret-legend">
+ <span><i class="ana-ret-swatch is-hit"></i>${esc(label)}, at or above the ${Math.round(target * 100)}% target</span>
+ <span><i class="ana-ret-swatch is-miss"></i>below target</span>
+ <span><i class="ana-ret-swatch is-open"></i>window still open</span>
+ </div>
+ `;
+
+ const host = panel.querySelector('[data-slot="ret"]');
+ requestAnimationFrame(() => paintRetentionColumns(host, cohorts, target, label));
+
+ return panel;
+}
+
+function paintRetentionColumns(host, cohorts, target, label) {
+ host.innerHTML = '';
+ const canvas = document.createElement('canvas');
+ canvas.style.cssText = 'width:100%;height:100%;display:block';
+ canvas.setAttribute('role', 'img');
+ canvas.setAttribute(
+ 'aria-label',
+ `${label} week-2 retention by mint cohort, ${cohorts.length} weeks. ` +
+ cohorts
+ .map(
+ (c) =>
+ `Week of ${c.cohort_week}: ${formatPct(Number(c.retention_rate))} of ${c.minted_owners} owners` +
+ `${c.is_complete ? '' : ', window still open'}`,
+ )
+ .join('. ') +
+ `. Target ${Math.round(target * 100)} percent.`,
+ );
+ host.appendChild(canvas);
+
+ const dpr = window.devicePixelRatio || 1;
+ const rect = host.getBoundingClientRect();
+ canvas.width = Math.round(rect.width * dpr);
+ canvas.height = Math.round(rect.height * dpr);
+ const ctx = canvas.getContext('2d');
+ ctx.scale(dpr, dpr);
+
+ const W = rect.width;
+ const H = rect.height;
+ const PAD = { top: 16, right: 16, bottom: 34, left: 44 };
+ const innerW = W - PAD.left - PAD.right;
+ const innerH = H - PAD.top - PAD.bottom;
+
+ // Always show at least up to the target so the bar is never off-canvas, and
+ // give a headroom cohort room to breathe above it.
+ const peak = cohorts.reduce((m, c) => Math.max(m, Number(c.retention_rate) || 0), 0);
+ const max = Math.min(1, Math.max(target * 1.4, peak * 1.2, 0.1));
+
+ const slot = innerW / cohorts.length;
+ const barW = Math.max(6, Math.min(46, slot * 0.62));
+
+ const duration = 600;
+ const startTime = performance.now();
+
+ function draw(now) {
+ const progress = Math.min(1, (now - startTime) / duration);
+ const eased = 1 - Math.pow(1 - progress, 3);
+
+ ctx.clearRect(0, 0, W, H);
+
+ // Grid + percentage axis
+ ctx.font = '10px Inter, system-ui, sans-serif';
+ for (let i = 0; i <= 4; i++) {
+ const y = PAD.top + (i / 4) * innerH;
+ ctx.strokeStyle = 'rgba(255,255,255,0.05)';
+ ctx.lineWidth = 0.5;
+ ctx.beginPath();
+ ctx.moveTo(PAD.left, y);
+ ctx.lineTo(W - PAD.right, y);
+ ctx.stroke();
+
+ ctx.fillStyle = 'rgba(255,255,255,0.3)';
+ ctx.textAlign = 'right';
+ ctx.fillText(`${Math.round(((4 - i) / 4) * max * 100)}%`, PAD.left - 8, y + 4);
+ }
+
+ // Columns
+ cohorts.forEach((c, i) => {
+ const rate = Number(c.retention_rate) || 0;
+ const h = Math.max(rate > 0 ? 2 : 0, (rate / max) * innerH * eased);
+ const x = PAD.left + i * slot + (slot - barW) / 2;
+ const y = PAD.top + innerH - h;
+
+ ctx.fillStyle = !c.is_complete
+ ? 'rgba(148,163,184,0.45)'
+ : rate >= target
+ ? '#4ade80'
+ : '#fbbf24';
+ ctx.beginPath();
+ ctx.roundRect(x, y, barW, h, [3, 3, 0, 0]);
+ ctx.fill();
+ });
+
+ // Target line, drawn over the columns so the bar is always readable.
+ const targetY = PAD.top + innerH - (Math.min(target, max) / max) * innerH;
+ ctx.save();
+ ctx.setLineDash([4, 4]);
+ ctx.strokeStyle = 'rgba(96,165,250,0.8)';
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ ctx.moveTo(PAD.left, targetY);
+ ctx.lineTo(W - PAD.right, targetY);
+ ctx.stroke();
+ ctx.restore();
+ ctx.fillStyle = 'rgba(96,165,250,0.9)';
+ ctx.textAlign = 'left';
+ ctx.fillText(`${Math.round(target * 100)}% target`, PAD.left + 4, targetY - 4);
+
+ // X labels — thinned so they never collide on a narrow viewport.
+ const showEvery = Math.max(1, Math.ceil(cohorts.length / Math.max(1, Math.floor(innerW / 56))));
+ ctx.fillStyle = 'rgba(255,255,255,0.3)';
+ ctx.textAlign = 'center';
+ cohorts.forEach((c, i) => {
+ if (i % showEvery === 0) {
+ ctx.fillText(formatCohortWeek(c.cohort_week), PAD.left + i * slot + slot / 2, H - 8);
+ }
+ });
+
+ if (progress < 1) requestAnimationFrame(draw);
+ }
+
+ if (prefersReducedMotion()) draw(startTime + duration);
+ else requestAnimationFrame(draw);
+
+ canvas.addEventListener('mousemove', (e) => {
+ const br = canvas.getBoundingClientRect();
+ const idx = Math.floor((e.clientX - br.left - PAD.left) / slot);
+ const c = cohorts[Math.max(0, Math.min(cohorts.length - 1, idx))];
+ canvas.title =
+ `Minted week of ${c.cohort_week}: ${formatPct(Number(c.retention_rate))} ` +
+ `(${c.retained_owners}/${c.minted_owners} owners)` +
+ `${c.is_complete ? '' : ' · window open until ' + c.window_end}`;
+ });
+}
+
// -- Skill breakdown (horizontal bar chart with Canvas) --
function renderSkillBreakdown(bySkill) {
@@ -669,6 +859,15 @@ function injectStyles() {
.ana-chart-empty { padding: 40px 0; text-align: center; color: var(--nxt-ink-dim); font-size: 13px; }
.ana-chart-empty a { color: var(--nxt-success); }
+.ana-ret-summary { font-size: 13px; color: var(--nxt-ink-dim); margin-top: 6px; }
+.ana-ret-summary strong { color: var(--nxt-ink); font-variant-numeric: tabular-nums; }
+.ana-ret-legend { display: flex; flex-wrap: wrap; gap: 14px; margin-top: 10px; font-size: 11px; color: var(--nxt-ink-fade); }
+.ana-ret-legend span { display: inline-flex; align-items: center; gap: 6px; }
+.ana-ret-swatch { width: 10px; height: 10px; border-radius: 2px; display: inline-block; }
+.ana-ret-swatch.is-hit { background: #4ade80; }
+.ana-ret-swatch.is-miss { background: #fbbf24; }
+.ana-ret-swatch.is-open { background: rgba(148,163,184,0.45); }
+
.ana-two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
.ana-tbl-wrap { overflow-x: auto; margin-top: 12px; }
diff --git a/src/voice/voice-setup.js b/src/voice/voice-setup.js
new file mode 100644
index 000000000..3c23e73d0
--- /dev/null
+++ b/src/voice/voice-setup.js
@@ -0,0 +1,625 @@
+// VoiceSetup — capture a voice sample and bind it to an agent.
+//
+// One component, two binding modes, because the two surfaces that need this
+// have opposite timing:
+//
+// bind: 'now' — an agent already exists (the talk-mode clone modal, the
+// editor). Recording or uploading clones immediately.
+// bind: 'later' — the /create-agent wizard, where the agent does not exist
+// until the ship step. The sample is held in memory and the
+// host calls bindTo(agentId) once the agent is real.
+//
+// Credentials. Cloning is a paid ElevenLabs feature and there is no free lane
+// (owner policy 2026-08-06), so the panel resolves which lane is open before it
+// lets anyone record:
+//
+// owner — the user saved an ElevenLabs key at /dashboard/account. Their
+// ElevenLabs account is billed; no $THREE credits are spent.
+// platform — the server has ELEVENLABS_API_KEY. Metered to $THREE credits.
+// none — neither. The panel renders inline key entry (PATCH
+// /api/user/provider-keys, AES-256-GCM encrypted at rest) rather
+// than a dead "not configured" message.
+//
+// Every state here is designed: signed out, no key, recording, sample too short,
+// sample too large, wrong file type, upstream provider failure, and bound.
+
+import { apiFetch } from '../api.js';
+import { log } from '../shared/log.js';
+
+/** ElevenLabs Instant Voice Cloning needs a real sample, not a hello. */
+export const MIN_SAMPLE_SECONDS = 30;
+/** Matches MAX_AUDIO_BYTES in api/agents/_id/voice.js. */
+export const MAX_SAMPLE_BYTES = 10 * 1024 * 1024;
+
+const SCRIPT_LINE =
+ "Hello, I'm building this agent on three.ws. I want it to speak with my own voice so it " +
+ 'can hold a real conversation. I will keep talking for about half a minute so the model has ' +
+ 'enough material to learn from, because the more natural my intonation is, the better the ' +
+ 'clone sounds when it answers someone.';
+
+const KEY_HELP_URL = 'https://elevenlabs.io/app/settings/api-keys';
+
+export class VoiceSetup {
+ /**
+ * @param {HTMLElement} host
+ * @param {object} opts
+ * @param {'now'|'later'} [opts.bind='now']
+ * @param {string} [opts.agentId] required for bind:'now'
+ * @param {string} [opts.agentName] names the cloned voice in ElevenLabs
+ * @param {boolean} [opts.authed=true] false renders the signed-out state
+ * @param {(state: {hasSample:boolean, seconds:number, bound:boolean}) => void} [opts.onChange]
+ */
+ constructor(host, { bind = 'now', agentId = '', agentName = 'Agent', authed = true, onChange } = {}) {
+ this.host = host;
+ this.bindMode = bind;
+ this.agentId = agentId;
+ this.agentName = agentName;
+ this.authed = authed;
+ this.onChange = onChange || (() => {});
+
+ /** @type {{blob: Blob, seconds: number, mimeType: string}|null} */
+ this.sample = null;
+ this.boundVoiceId = null;
+ /** @type {'owner'|'platform'|null} */
+ this.keySource = null;
+ this.keyProbed = false;
+
+ this._recorder = null;
+ this._chunks = [];
+ this._recording = false;
+ this._startedAt = 0;
+ this._timer = null;
+ this._stream = null;
+ this._destroyed = false;
+ this._el = null;
+ }
+
+ async mount() {
+ injectStylesOnce();
+ this._el = document.createElement('div');
+ this._el.className = 'vs-root';
+ this.host.appendChild(this._el);
+ this._render();
+ if (this.authed) await this._probeKey();
+ }
+
+ destroy() {
+ this._destroyed = true;
+ this._stopTimer();
+ this._releaseMic();
+ this._el?.remove();
+ this._el = null;
+ }
+
+ /** True once a usable sample is held (or a voice is already bound). */
+ get ready() {
+ return !!this.boundVoiceId || !!this.sample;
+ }
+
+ /**
+ * Clone the held sample onto a now-existing agent. Used by bind:'later' hosts
+ * after the agent is created.
+ * @param {string} agentId
+ * @returns {Promise<{voice_id:string, billing:string}>}
+ * @throws {Error & { code?: string }} with a user-facing message on failure.
+ */
+ async bindTo(agentId) {
+ if (!this.sample) throw new Error('No voice sample was recorded.');
+ this.agentId = agentId;
+ return this._clone(this.sample);
+ }
+
+ // ── Credential probe ─────────────────────────────────────────────────────
+
+ async _probeKey() {
+ try {
+ const r = await apiFetch('/api/tts/eleven/voices', { allowAnonymous: true });
+ if (r.status === 401) {
+ this.authed = false;
+ } else if (r.ok) {
+ const j = await r.json().catch(() => ({}));
+ this.keySource = j.enabled ? j.key_source || 'platform' : null;
+ }
+ } catch (err) {
+ log.warn('[voice-setup] key probe failed', err?.message);
+ }
+ this.keyProbed = true;
+ if (!this._destroyed) this._render();
+ }
+
+ async _saveKey(key) {
+ const r = await apiFetch('/api/user/provider-keys', {
+ method: 'PATCH',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ elevenlabs: key }),
+ });
+ if (!r.ok) {
+ const j = await r.json().catch(() => ({}));
+ throw new Error(j.error_description || j.error || `Could not save the key (${r.status}).`);
+ }
+ this.keySource = 'owner';
+ }
+
+ // ── Rendering ────────────────────────────────────────────────────────────
+
+ _render() {
+ if (!this._el) return;
+ // The previous render's preview URL is about to be detached with its
+ // <audio> element; release it so repeated re-renders can't leak blobs.
+ if (this._sampleUrl) {
+ URL.revokeObjectURL(this._sampleUrl);
+ this._sampleUrl = null;
+ }
+ this._el.innerHTML = `
+ ${this._credentialHtml()}
+ ${this._captureHtml()}
+ <p class="vs-status" data-ref="status" role="status" aria-live="polite"></p>
+ `;
+ this._wire();
+ }
+
+ _credentialHtml() {
+ if (!this.authed) {
+ return `
+ <div class="vs-note vs-note-info">
+ <strong>Sign in to add a voice.</strong>
+ Cloning runs against a real ElevenLabs account, so it needs to know whose.
+ Everything else in this wizard keeps working while signed out, and your agent
+ starts on the built-in voice.
+ </div>`;
+ }
+ if (!this.keyProbed) {
+ return `<div class="vs-note vs-note-info vs-skeleton">Checking which voice provider is available…</div>`;
+ }
+ if (this.keySource === 'owner') {
+ return `
+ <div class="vs-note vs-note-ok">
+ <strong>Using your ElevenLabs key.</strong>
+ Clones land in your own ElevenLabs account and are billed there, so no $THREE
+ credits are spent. <a href="/dashboard/account">Manage key</a>
+ </div>`;
+ }
+ if (this.keySource === 'platform') {
+ return `
+ <div class="vs-note vs-note-ok">
+ <strong>Using the three.ws voice provider.</strong>
+ Cloning is metered to your credit balance. Top up with $THREE at
+ <a href="/credits">/credits</a>, or
+ <button type="button" class="vs-link" data-ref="show-key">use your own ElevenLabs key</button>.
+ </div>`;
+ }
+ return this._keyFormHtml();
+ }
+
+ _keyFormHtml() {
+ return `
+ <div class="vs-note vs-note-warn">
+ <strong>Bring your ElevenLabs key.</strong>
+ Voice cloning runs on ElevenLabs. Paste an API key from
+ <a href="${KEY_HELP_URL}" target="_blank" rel="noopener">your ElevenLabs dashboard</a>
+ and your agent speaks in the cloned voice everywhere on three.ws. The key is
+ encrypted at rest and never shown again.
+ <div class="vs-key-row">
+ <input class="vs-key-input" data-ref="key" type="password" autocomplete="off"
+ spellcheck="false" placeholder="sk_…" aria-label="ElevenLabs API key" />
+ <button type="button" class="vs-btn primary" data-ref="save-key">Save key</button>
+ </div>
+ </div>`;
+ }
+
+ _captureHtml() {
+ const canCapture = this.authed && !!this.keySource;
+ if (this.boundVoiceId) {
+ return `
+ <div class="vs-note vs-note-ok">
+ <strong>Voice bound.</strong> This agent now speaks in the cloned voice.
+ <button type="button" class="vs-btn ghost" data-ref="reset">Record a different one</button>
+ </div>`;
+ }
+ if (this.sample) {
+ this._sampleUrl = URL.createObjectURL(this.sample.blob);
+ return `
+ <div class="vs-sample">
+ <div class="vs-sample-head">
+ <span class="vs-dot"></span>
+ <strong>Sample ready</strong>
+ <span class="vs-sample-meta">${formatSeconds(this.sample.seconds)} · ${formatBytes(this.sample.blob.size)}</span>
+ </div>
+ <audio class="vs-audio" controls src="${this._sampleUrl}"></audio>
+ <div class="vs-controls">
+ <button type="button" class="vs-btn ghost" data-ref="reset">Discard and redo</button>
+ ${this.bindMode === 'now' ? '<button type="button" class="vs-btn primary" data-ref="clone-now">Clone this voice</button>' : ''}
+ </div>
+ ${this.bindMode === 'later' ? '<p class="vs-hint">Your voice is cloned and bound the moment the agent is created.</p>' : ''}
+ </div>`;
+ }
+ return `
+ <div class="vs-capture" ${canCapture ? '' : 'data-disabled="true"'}>
+ <p class="vs-script-label">Read this out loud, at your normal pace:</p>
+ <blockquote class="vs-script">${SCRIPT_LINE}</blockquote>
+ <div class="vs-controls">
+ <button type="button" class="vs-btn primary" data-ref="record" ${canCapture ? '' : 'disabled'}>
+ Record ${MIN_SAMPLE_SECONDS}s
+ </button>
+ <button type="button" class="vs-btn danger" data-ref="stop" disabled hidden>Stop</button>
+ <span class="vs-timer" data-ref="timer" hidden>0:00</span>
+ <span class="vs-or">or</span>
+ <label class="vs-btn ghost ${canCapture ? '' : 'is-disabled'}">
+ Upload audio
+ <input type="file" accept="audio/*" data-ref="file" ${canCapture ? '' : 'disabled'} hidden />
+ </label>
+ </div>
+ <p class="vs-hint">
+ At least ${MIN_SAMPLE_SECONDS} seconds, under ${Math.round(MAX_SAMPLE_BYTES / 1024 / 1024)} MB.
+ Quiet room, one speaker, no music.
+ </p>
+ </div>`;
+ }
+
+ _wire() {
+ const ref = (name) => this._el?.querySelector(`[data-ref="${name}"]`);
+
+ ref('save-key')?.addEventListener('click', async () => {
+ const input = /** @type {HTMLInputElement|null} */ (ref('key'));
+ const value = input?.value.trim();
+ if (!value) {
+ this._status('err', 'Paste your ElevenLabs API key first.');
+ input?.focus();
+ return;
+ }
+ const btn = /** @type {HTMLButtonElement} */ (ref('save-key'));
+ btn.disabled = true;
+ btn.textContent = 'Saving…';
+ try {
+ await this._saveKey(value);
+ this._render();
+ this._status('ok', 'Key saved. You can record your voice now.');
+ } catch (err) {
+ btn.disabled = false;
+ btn.textContent = 'Save key';
+ this._status('err', err.message);
+ }
+ });
+
+ ref('show-key')?.addEventListener('click', () => {
+ this.keySource = null;
+ this._render();
+ });
+
+ ref('record')?.addEventListener('click', () => this._startRecording());
+ ref('stop')?.addEventListener('click', () => this._stopRecording());
+ ref('file')?.addEventListener('change', (e) => {
+ const file = /** @type {HTMLInputElement} */ (e.target).files?.[0];
+ if (file) this._acceptFile(file);
+ });
+ ref('reset')?.addEventListener('click', () => {
+ this.sample = null;
+ this.boundVoiceId = null;
+ this._render();
+ this._emit();
+ });
+ ref('clone-now')?.addEventListener('click', () => this._cloneHeldSample());
+ }
+
+ _status(kind, text) {
+ const el = this._el?.querySelector('[data-ref="status"]');
+ if (!el) return;
+ el.className = `vs-status ${kind}`;
+ el.textContent = text;
+ }
+
+ _emit() {
+ this.onChange({
+ hasSample: !!this.sample,
+ seconds: this.sample?.seconds || 0,
+ bound: !!this.boundVoiceId,
+ });
+ }
+
+ // ── Recording ────────────────────────────────────────────────────────────
+
+ async _startRecording() {
+ if (this._recording) return;
+ let stream;
+ try {
+ stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ } catch {
+ this._status(
+ 'err',
+ 'Microphone blocked. Allow mic access in your browser, or upload an audio file instead.',
+ );
+ return;
+ }
+ this._stream = stream;
+ this._chunks = [];
+
+ const mimeType = ['audio/webm;codecs=opus', 'audio/webm', 'audio/mp4'].find(
+ (t) => window.MediaRecorder?.isTypeSupported?.(t),
+ );
+ this._recorder = mimeType
+ ? new MediaRecorder(stream, { mimeType })
+ : new MediaRecorder(stream);
+ this._recorder.ondataavailable = (e) => {
+ if (e.data.size > 0) this._chunks.push(e.data);
+ };
+ this._recorder.start(250);
+ this._recording = true;
+ this._startedAt = Date.now();
+
+ const ref = (n) => this._el?.querySelector(`[data-ref="${n}"]`);
+ const record = /** @type {HTMLButtonElement} */ (ref('record'));
+ const stop = /** @type {HTMLButtonElement} */ (ref('stop'));
+ record.hidden = true;
+ stop.hidden = false;
+ stop.disabled = false;
+ /** @type {HTMLElement} */ (ref('timer')).hidden = false;
+ this._status('info', 'Recording. Speak naturally until the timer turns green.');
+ this._startTimer();
+ }
+
+ _startTimer() {
+ const el = this._el?.querySelector('[data-ref="timer"]');
+ const tick = () => {
+ if (!this._recording || !el) return;
+ const elapsed = (Date.now() - this._startedAt) / 1000;
+ el.textContent = formatSeconds(elapsed);
+ el.classList.toggle('is-enough', elapsed >= MIN_SAMPLE_SECONDS);
+ this._timer = requestAnimationFrame(tick);
+ };
+ this._timer = requestAnimationFrame(tick);
+ }
+
+ _stopTimer() {
+ if (this._timer) cancelAnimationFrame(this._timer);
+ this._timer = null;
+ }
+
+ _releaseMic() {
+ try {
+ this._stream?.getTracks().forEach((t) => t.stop());
+ } catch {
+ // The tracks are already gone; nothing left to release.
+ }
+ this._stream = null;
+ }
+
+ async _stopRecording() {
+ if (!this._recorder || !this._recording) return;
+ const seconds = (Date.now() - this._startedAt) / 1000;
+ this._recording = false;
+ this._stopTimer();
+
+ await new Promise((resolve) => {
+ this._recorder.onstop = resolve;
+ this._recorder.stop();
+ });
+ const mimeType = this._recorder.mimeType || 'audio/webm';
+ this._releaseMic();
+
+ const blob = new Blob(this._chunks, { type: mimeType });
+ this._accept({ blob, seconds, mimeType });
+ }
+
+ // ── Upload ───────────────────────────────────────────────────────────────
+
+ async _acceptFile(file) {
+ if (!file.type.startsWith('audio/')) {
+ this._status('err', `That is a ${file.type || 'non-audio'} file. Upload an audio recording.`);
+ return;
+ }
+ if (file.size > MAX_SAMPLE_BYTES) {
+ this._status(
+ 'err',
+ `That file is ${formatBytes(file.size)}. Trim it under ${Math.round(MAX_SAMPLE_BYTES / 1024 / 1024)} MB and try again.`,
+ );
+ return;
+ }
+ const seconds = await audioDuration(file);
+ this._accept({ blob: file, seconds, mimeType: file.type });
+ }
+
+ /**
+ * Shared validation gate for both capture paths. Every rejection re-renders
+ * back to a clean capture panel first, so a bad sample leaves the recorder
+ * usable instead of stranded mid-recording, and the message survives.
+ */
+ _accept({ blob, seconds, mimeType }) {
+ const reject = (message) => {
+ this._render();
+ this._status('err', message);
+ };
+ const maxMb = Math.round(MAX_SAMPLE_BYTES / 1024 / 1024);
+
+ if (blob.size === 0) return reject('That recording came back empty. Try again.');
+ if (blob.size > MAX_SAMPLE_BYTES)
+ return reject(`That sample is ${formatBytes(blob.size)}. Keep it under ${maxMb} MB.`);
+ if (seconds > 0 && seconds < MIN_SAMPLE_SECONDS)
+ return reject(
+ `That is ${formatSeconds(seconds)}. ElevenLabs needs at least ${MIN_SAMPLE_SECONDS} seconds to build a usable voice.`,
+ );
+ // A duration of 0 means the browser could not decode a length; fall back to
+ // the byte-size floor the server uses so we never block a valid upload.
+ if (!seconds && blob.size < 50_000)
+ return reject(`That sample is too short. Record at least ${MIN_SAMPLE_SECONDS} seconds.`);
+
+ this.sample = { blob, seconds, mimeType };
+ this._render();
+ this._status(
+ 'ok',
+ this.bindMode === 'later'
+ ? 'Sample captured. It gets cloned when you create the agent.'
+ : 'Sample captured. Clone it to bind the voice.',
+ );
+ this._emit();
+ }
+
+ // ── Cloning ──────────────────────────────────────────────────────────────
+
+ async _cloneHeldSample() {
+ const btn = this._el?.querySelector('[data-ref="clone-now"]');
+ if (btn) {
+ btn.setAttribute('disabled', 'true');
+ btn.textContent = 'Cloning…';
+ }
+ this._status('info', 'Cloning your voice. This takes a few seconds.');
+ try {
+ await this._clone(this.sample);
+ this._render();
+ this._status('ok', 'Voice cloned and bound to this agent.');
+ this._emit();
+ } catch (err) {
+ this._render();
+ this._status('err', err.message);
+ }
+ }
+
+ /**
+ * POST the sample to the real clone endpoint.
+ * @param {{blob: Blob, seconds: number, mimeType: string}} sample
+ */
+ async _clone(sample) {
+ if (!this.agentId) throw new Error('No agent to bind this voice to.');
+ const qs = new URLSearchParams({ name: `${this.agentName} voice` });
+ const headers = { 'content-type': sample.mimeType || 'audio/webm' };
+ if (sample.seconds > 0) headers['x-recording-duration'] = String(Math.round(sample.seconds));
+
+ const res = await apiFetch(`/api/agents/${this.agentId}/voice/clone?${qs}`, {
+ method: 'POST',
+ headers,
+ body: sample.blob,
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) throw cloneError(res.status, data);
+
+ this.boundVoiceId = data.voice_id;
+ return data;
+ }
+}
+
+/** Turn a clone failure into a message that names the actual next step. */
+function cloneError(status, data) {
+ const detail = data?.error_description || data?.message || '';
+ if (status === 402) {
+ return Object.assign(
+ new Error('Not enough credits to clone a voice. Top up with $THREE at /credits, or save your own ElevenLabs key.'),
+ { code: 'insufficient_credits' },
+ );
+ }
+ if (status === 429) {
+ return Object.assign(new Error('Voice clone limit reached (3 per day). Try again tomorrow.'), {
+ code: 'rate_limited',
+ });
+ }
+ if (status === 503) {
+ return Object.assign(
+ new Error(detail || 'No ElevenLabs key is available. Save yours at /dashboard/account.'),
+ { code: 'not_configured' },
+ );
+ }
+ return Object.assign(new Error(detail || `Voice cloning failed (${status}).`), {
+ code: data?.error || 'clone_failed',
+ });
+}
+
+// ── Helpers ────────────────────────────────────────────────────────────────
+
+/** Decode an audio file's duration in the browser. Resolves 0 when it can't. */
+export function audioDuration(file) {
+ return new Promise((resolve) => {
+ const url = URL.createObjectURL(file);
+ const audio = new Audio();
+ const done = (value) => {
+ URL.revokeObjectURL(url);
+ resolve(value);
+ };
+ audio.addEventListener('loadedmetadata', () =>
+ done(Number.isFinite(audio.duration) ? audio.duration : 0),
+ );
+ audio.addEventListener('error', () => done(0));
+ audio.src = url;
+ });
+}
+
+export function formatSeconds(total) {
+ const s = Math.max(0, Math.floor(total));
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
+}
+
+export function formatBytes(bytes) {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
+}
+
+function injectStylesOnce() {
+ if (typeof document === 'undefined' || document.getElementById('vs-css')) return;
+ const s = document.createElement('style');
+ s.id = 'vs-css';
+ s.textContent = `
+.vs-root { display: grid; gap: 12px; font-family: inherit; }
+.vs-note {
+ border-radius: 10px; padding: 12px 14px; font-size: 13px; line-height: 1.55;
+ border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.03);
+}
+.vs-note strong { display: block; margin-bottom: 2px; font-weight: 600; }
+.vs-note a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }
+.vs-note-ok { border-color: rgba(74,222,128,0.32); background: rgba(74,222,128,0.07); }
+.vs-note-warn { border-color: rgba(251,191,36,0.32); background: rgba(251,191,36,0.07); }
+.vs-note-info { border-color: rgba(125,211,252,0.28); background: rgba(125,211,252,0.06); }
+.vs-skeleton { opacity: 0.6; }
+.vs-key-row { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; }
+.vs-key-input {
+ flex: 1 1 200px; min-width: 0; padding: 8px 11px; border-radius: 8px;
+ border: 1px solid rgba(255,255,255,0.18); background: rgba(0,0,0,0.35);
+ color: inherit; font: inherit; font-size: 13px;
+}
+.vs-key-input:focus-visible { outline: 2px solid rgba(125,211,252,0.7); outline-offset: 1px; }
+.vs-capture[data-disabled="true"] { opacity: 0.45; }
+.vs-script-label { margin: 0 0 6px; font-size: 12px; opacity: 0.7; }
+.vs-script {
+ margin: 0 0 12px; padding: 12px 14px; border-radius: 10px; font-size: 13px; line-height: 1.6;
+ border: 1px solid rgba(255,255,255,0.1); background: rgba(255,255,255,0.03);
+}
+.vs-controls { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
+.vs-btn {
+ display: inline-flex; align-items: center; gap: 6px; padding: 9px 16px; border: 0;
+ border-radius: 9px; font: inherit; font-size: 13px; font-weight: 600; cursor: pointer;
+ transition: transform 0.12s ease, opacity 0.12s ease, background 0.12s ease;
+}
+.vs-btn:not(:disabled):hover { transform: translateY(-1px); }
+.vs-btn:not(:disabled):active { transform: translateY(0); }
+.vs-btn:focus-visible { outline: 2px solid rgba(125,211,252,0.8); outline-offset: 2px; }
+.vs-btn:disabled, .vs-btn.is-disabled { opacity: 0.45; cursor: not-allowed; }
+.vs-btn.primary { background: #f5f5f5; color: #0a0a0a; }
+.vs-btn.primary:not(:disabled):hover { background: #ffffff; }
+.vs-btn.danger { background: #ef4444; color: #fff; }
+.vs-btn.ghost { background: rgba(255,255,255,0.07); color: inherit; border: 1px solid rgba(255,255,255,0.16); }
+.vs-btn.ghost:not(.is-disabled):hover { background: rgba(255,255,255,0.13); }
+.vs-link {
+ background: none; border: 0; padding: 0; font: inherit; color: inherit; cursor: pointer;
+ text-decoration: underline; text-underline-offset: 2px;
+}
+.vs-or { font-size: 12px; opacity: 0.55; }
+.vs-timer { font: 600 15px/1 ui-monospace, SFMono-Regular, monospace; min-width: 46px; opacity: 0.8; }
+.vs-timer.is-enough { color: #4ade80; opacity: 1; }
+.vs-hint { margin: 10px 0 0; font-size: 12px; line-height: 1.5; opacity: 0.6; }
+.vs-sample {
+ border-radius: 10px; padding: 12px 14px;
+ border: 1px solid rgba(74,222,128,0.3); background: rgba(74,222,128,0.06);
+}
+.vs-sample-head { display: flex; align-items: center; gap: 8px; font-size: 13px; margin-bottom: 10px; }
+.vs-sample-meta { opacity: 0.65; font-size: 12px; }
+.vs-dot { width: 8px; height: 8px; border-radius: 50%; background: #4ade80; flex-shrink: 0; }
+.vs-audio { width: 100%; margin-bottom: 10px; }
+.vs-status { margin: 0; font-size: 12.5px; line-height: 1.5; min-height: 18px; }
+.vs-status.ok { color: #4ade80; }
+.vs-status.err { color: #f87171; }
+.vs-status.info { opacity: 0.7; }
+@media (max-width: 480px) {
+ .vs-controls { gap: 8px; }
+ .vs-btn { flex: 1 1 auto; justify-content: center; }
+ .vs-or { display: none; }
+}
+`;
+ document.head.appendChild(s);
+}