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
Sync workspace: referrals, collectibles, studio, club, and page updates
nirholas5241c85fbe15
diff --git a/agent-payments-sdk/src/solana/program.ts b/agent-payments-sdk/src/solana/program.tsindex e454f5c01..49cdbda79 100644--- a/agent-payments-sdk/src/solana/program.ts+++ b/agent-payments-sdk/src/solana/program.ts@@ -19,8 +19,8 @@ export function getPumpProgram(): Program<PumpAgentPayments> {const dummyWallet = {publicKey: PublicKey.default,- signTransaction: () => Promise.reject(),- signAllTransactions: () => Promise.reject(),+ signTransaction: () => Promise.reject(new Error('offline program cannot sign')),+ signAllTransactions: () => Promise.reject(new Error('offline program cannot sign')),};return new Program(IDL as unknown as PumpAgentPayments,diff --git a/agent-payments-sdk/src/x402/evm-client.ts b/agent-payments-sdk/src/x402/evm-client.tsindex acf0cdf33..9fa554617 100644--- a/agent-payments-sdk/src/x402/evm-client.ts+++ b/agent-payments-sdk/src/x402/evm-client.ts@@ -40,6 +40,10 @@ export interface EvmWalletClient {value: bigint;chainId: number;}) => Promise<`0x${string}`>;+ /** Wait for a tx to be included in a block. Provide this (e.g. viem's+ * `waitForTransactionReceipt`) to guarantee the ERC-20 approval is confirmed+ * on-chain before the bridge tx is submitted. */+ confirmTransaction?: (txHash: `0x${string}`) => Promise<void>;}export interface EvmX402FetchOptions {@@ -102,14 +106,18 @@ export function createEvmX402Fetch(opts: EvmX402FetchOptions) {sender: opts.walletClient.address,});- // Send approval if needed+ // Send approval if needed; confirm before submitting the bridge tx so the+ // allowance is set on-chain before the bridge contract reads it.if (txs.approval) {- await opts.walletClient.sendTransaction({+ const approvalTxHash = await opts.walletClient.sendTransaction({to: txs.approval.to,data: txs.approval.data,value: txs.approval.value,chainId: opts.walletClient.chainId,});+ if (opts.walletClient.confirmTransaction) {+ await opts.walletClient.confirmTransaction(approvalTxHash);+ }}// Send bridge txdiff --git a/agent-payments-sdk/src/x402/evm-facilitator.ts b/agent-payments-sdk/src/x402/evm-facilitator.tsindex 2c72e29f6..ea89706af 100644--- a/agent-payments-sdk/src/x402/evm-facilitator.ts+++ b/agent-payments-sdk/src/x402/evm-facilitator.ts@@ -91,11 +91,19 @@ export async function verifyEvmPayment(// The deposit response must echo back the Solana agent mint that the quote// was created against so we can re-verify the payer didn't reuse a deposit// destined for a different agent.+ if (!/^0x[0-9a-fA-F]{64}$/.test(proof.txHash)) {+ return { valid: false, error: "Invalid txHash format" };+ }+ if (!Number.isInteger(proof.chainId) || proof.chainId <= 0) {+ return { valid: false, error: "Invalid chainId" };+ }+let depositId: string;try {- const res = await fetch(- `${PUMP_CROSSCHAIN_API}/deposit?txHash=${proof.txHash}&chainId=${proof.chainId}`- );+ const depositUrl = new URL(`${PUMP_CROSSCHAIN_API}/deposit`);+ depositUrl.searchParams.set("txHash", proof.txHash);+ depositUrl.searchParams.set("chainId", String(proof.chainId));+ const res = await fetch(depositUrl.toString());if (!res.ok) throw new Error(`Deposit lookup failed (${res.status})`);const data: {depositId: string;@@ -128,12 +136,19 @@ export async function verifyEvmPayment(error: `Insufficient amount: got ${confirmedAmount}, need ${minAmountUsdc}`,};}+ } catch (err) {+ return {+ valid: false,+ error: `EVM tx verification failed: ${(err as Error).message}`,+ };+ }++ const replayKey = `${proof.chainId}:${proof.txHash}`;- // Atomically consume the deposit txHash so it can't be redeemed twice.+ if (!params.waitForSolana) {+ // Consume the replay key before returning; no Solana wait requested.if (params.replayStore) {- const claimed = await params.replayStore.claim(- `${proof.chainId}:${proof.txHash}`,- );+ const claimed = await params.replayStore.claim(replayKey);if (!claimed) {return {valid: false,@@ -142,22 +157,24 @@ export async function verifyEvmPayment(};}}- } catch (err) {- return {- valid: false,- error: `EVM tx verification failed: ${(err as Error).message}`,- };- }-- if (!params.waitForSolana) {return { valid: true, depositId };}- // Wait for Solana arrival+ // Wait for Solana arrival, then consume the replay key on success only.try {const status: CrossChainPaymentStatusResult = await waitWithTimeout(depositId);if (status.status === "arrived_on_solana") {+ if (params.replayStore) {+ const claimed = await params.replayStore.claim(replayKey);+ if (!claimed) {+ return {+ valid: false,+ depositId,+ error: "Duplicate payment: this EVM deposit was already redeemed",+ };+ }+ }return {valid: true,depositId,diff --git a/agent-protocol-sdk/src/index.ts b/agent-protocol-sdk/src/index.tsindex f82622de2..e0a8a74ae 100644--- a/agent-protocol-sdk/src/index.ts+++ b/agent-protocol-sdk/src/index.ts@@ -81,10 +81,10 @@ export async function invokeSkill({const program = new Program<AgentInvocation>(idl, provider);const instruction = await program.methods- .invoke_skill(skillName, parameters)+ .invokeSkill(skillName, parameters).accounts({- invoker_authority: invokerAuthority.publicKey,- target_authority: targetAuthority,+ invokerAuthority: invokerAuthority.publicKey,+ targetAuthority: targetAuthority,}).instruction();diff --git a/api/_lib/credits.js b/api/_lib/credits.jsindex 00a5bd44e..e5b29262e 100644--- a/api/_lib/credits.js+++ b/api/_lib/credits.js@@ -263,17 +263,36 @@ export async function refundCredits({});}-/** Keyset-paginated ledger history (newest first) for a user. */+/** Keyset-paginated ledger history (newest first) for a user.+ * Cursor is the `id` of the last-seen row (UUID). Stable even when two rows+ * share the same `created_at` timestamp. */export async function listLedger({ userId, limit = 25, before = null } = {}) {if (!userId) throw badRequest('userId is required');const cap = Math.min(Math.max(Number(limit) || 25, 1), 100);+ // before is the id of the last item on the previous page. We look up its+ // (created_at, id) pair so we can use a compound keyset condition that is+ // stable across rows with identical timestamps.+ let beforeTs = null;+ let beforeId = null;+ if (before) {+ const [anchor] = await sql`+ select created_at from credit_ledger+ where id = ${before} and user_id = ${userId}+ limit 1+ `;+ if (anchor) { beforeTs = anchor.created_at; beforeId = before; }+ }const rows = await sql`select id, kind, amount_usd, balance_after, action, ref_type, ref_id,tx_signature, asset, asset_amount, price_usd, created_atfrom credit_ledgerwhere user_id = ${userId}- and (${before}::timestamptz is null or created_at < ${before})- order by created_at desc+ and (+ ${beforeTs}::timestamptz is null+ or created_at < ${beforeTs}::timestamptz+ or (created_at = ${beforeTs}::timestamptz and id < ${beforeId}::uuid)+ )+ order by created_at desc, id desclimit ${cap + 1}`;const hasMore = rows.length > cap;@@ -291,5 +310,5 @@ export async function listLedger({ userId, limit = 25, before = null } = {}) {price_usd: r.price_usd == null ? null : Number(r.price_usd),created_at: r.created_at,}));- return { items, next_cursor: hasMore ? items[items.length - 1].created_at : null };+ return { items, next_cursor: hasMore ? items[items.length - 1].id : null };}diff --git a/api/_lib/migrations/20260621210000_referral_code_upper_index.sql b/api/_lib/migrations/20260621210000_referral_code_upper_index.sqlnew file mode 100644index 000000000..25af7d56e--- /dev/null+++ b/api/_lib/migrations/20260621210000_referral_code_upper_index.sql@@ -0,0 +1,26 @@+-- Functional index on UPPER(referral_code) for case-insensitive referral lookups.+--+-- Every hot query on the referral system matches on UPPER(referral_code) = $code:+-- • api/users/referral-claim.js — attribute a referral at claim time+-- • api/_lib/referrals.js — getReferralCodeAvailability, setReferralCode+-- • api/auth/[action].js — resolve referrer at email signup+-- • api/marketplace/purchase.js — resolve referrer at purchase+-- • api/marketplace/buy-asset.js — resolve referrer at asset purchase+--+-- Without a functional index, PostgreSQL cannot use the plain B-tree index on+-- the raw referral_code column for these queries and falls back to a sequential+-- scan on users — a full table scan on every referral lookup.+--+-- The existing UNIQUE constraint (from 001_add_referrals.sql) stays in place. It+-- enforces exact-case uniqueness on the stored value, which is fine because all+-- codes are stored UPPERCASE by the application. This functional index is an+-- additional performance index only.+--+-- CONCURRENTLY: users is auth-critical and must not be write-locked during the+-- build. CREATE INDEX CONCURRENTLY cannot run inside a transaction, so this file+-- intentionally has NO begin/commit wrapper and contains only this statement.+-- Apply: node scripts/apply-migrations.mjs --apply --file 20260621210000_referral_code_upper_index.sql++CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_referral_code_upper+ ON users (UPPER(referral_code))+ WHERE deleted_at IS NULL;diff --git a/api/_lib/migrations/20260621210001_referral_earnings_bigint.sql b/api/_lib/migrations/20260621210001_referral_earnings_bigint.sqlnew file mode 100644index 000000000..001f6c510--- /dev/null+++ b/api/_lib/migrations/20260621210001_referral_earnings_bigint.sql@@ -0,0 +1,35 @@+-- Fix referral_earnings_total column type: DECIMAL(12,2) → BIGINT.+--+-- The column stores atomic USDC units (6-decimal integers), written by+-- api/_lib/referrals.js creditReferralCommission:+--+-- UPDATE users+-- SET referral_earnings_total = COALESCE(referral_earnings_total, 0) + <atomics>+--+-- and read back as an integer by getMembershipCard and getReferredUsers.+-- DECIMAL(12,2) has a maximum integer magnitude of 10 digits (9,999,999,999),+-- which equals only $9,999.99 in atomic USDC units. A referrer earning more+-- than ~$10k overflows silently.+--+-- BIGINT (8-byte signed, max ~9.2 × 10^18) safely stores lifetime earnings+-- up to ~$9.2 trillion in atomics — effectively unbounded for this use case.+-- The existing DEFAULT 0.00 becomes DEFAULT 0; any stored decimal values+-- (they will all be whole numbers since the writer never fractionalises atomics)+-- are preserved exactly.+--+-- Wrapped in a transaction because ALTER COLUMN TYPE on a live table takes a+-- brief ACCESS EXCLUSIVE lock. On Postgres 14+ this is fast when no rewrite is+-- needed (integer coercion of whole-number DECIMAL requires no rewrite).++BEGIN;++ALTER TABLE users+ ALTER COLUMN referral_earnings_total+ TYPE BIGINT+ USING ROUND(referral_earnings_total)::BIGINT;++ALTER TABLE users+ ALTER COLUMN referral_earnings_total+ SET DEFAULT 0;++COMMIT;diff --git a/api/_lib/pump-launch.js b/api/_lib/pump-launch.jsindex 139b199a7..2dcd3091e 100644--- a/api/_lib/pump-launch.js+++ b/api/_lib/pump-launch.js@@ -18,6 +18,7 @@ import { env } from './env.js';import { solanaConnection } from './agent-pumpfun.js';import { submitProtected } from './execution-engine.js';import { grindMintKeypair } from './pump-vanity.js';+import { fetchSafePublicUrlPinned, SsrfBlockedError } from './ssrf-guard.js';const PUMP_IPFS_ENDPOINT = 'https://pump.fun/api/ipfs';@@ -96,20 +97,13 @@ export async function uploadPumpMetadata({website = '',showName = true,}) {- let parsed;- try {- parsed = new URL(imageUrl);- } catch {- throw launchError(400, 'invalid_image_url', 'imageUrl is not a valid URL');- }- if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {- throw launchError(400, 'invalid_image_url', 'imageUrl must be http(s)');- }-let imgRes;try {- imgRes = await fetch(parsed, { redirect: 'follow' });+ imgRes = await fetchSafePublicUrlPinned(imageUrl, {}, { allowHttp: false });} catch (err) {+ if (err instanceof SsrfBlockedError) {+ throw launchError(400, 'invalid_image_url', `imageUrl blocked: ${err.message}`);+ }throw launchError(502, 'image_fetch_failed', `could not fetch imageUrl: ${err.message}`);}if (!imgRes.ok) {diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 7d2cfc733..65087dd63 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -282,6 +282,12 @@ export const limits = {// writes a public rarity entry — bound per IP so one caller can't carpet the// gallery, but generous enough for a real owner publishing a few grinds.// Reads (gallery list / leaderboard / appraisal) are cheap and CDN-cacheable.+ // Referral-code availability check (GET /api/users/referral-code?code=…).+ // Debounced at 280 ms client-side; a 20-char code produces ~20 checks. Use a+ // dedicated bucket (not authIp) so typing a vanity code doesn't consume the+ // login/auth budget and lock out shared-IP users (offices, shared NAT).+ referralCodeCheckIp: (ip) =>+ getLimiter('referral:code:check:ip', { limit: 120, window: '5 m' }).limit(ip),vanityGalleryPublishIp: (ip) =>getLimiter('vanity:gallery:publish:ip', { limit: 12, window: '10 m' }).limit(ip),vanityGalleryReadIp: (ip) =>diff --git a/api/_lib/referrals.js b/api/_lib/referrals.jsindex 4eb287d46..26e443572 100644--- a/api/_lib/referrals.js+++ b/api/_lib/referrals.js@@ -209,7 +209,7 @@ export async function setReferralCode(userId, desired) {// @param {string|number} userId// @returns {Promise<string>} the user's referral codeexport async function ensureReferralCode(userId) {- const [existing] = await sql`SELECT referral_code, display_name, username FROM users WHERE id = ${userId}`;+ const [existing] = await sql`SELECT referral_code, display_name, username FROM users WHERE id = ${userId} AND deleted_at IS NULL`;if (existing?.referral_code) return existing.referral_code;// Default the code to the member's name (then name+suffix, then random) so the@@ -450,7 +450,8 @@ export async function getMembershipCard(userId) {`;const [{ position }] = await sql`SELECT COUNT(*)::int AS position FROM users- WHERE id <= ${userId} AND deleted_at IS NULL+ WHERE created_at <= (SELECT created_at FROM users WHERE id = ${userId})+ AND deleted_at IS NULL`;// Platform-wide member count: a full-table COUNT(*) that is identical for// every viewer and grows monotonically — cache for 60s instead of scanningdiff --git a/api/_lib/x402.js b/api/_lib/x402.jsindex c788cc0ae..99a0795b4 100644--- a/api/_lib/x402.js+++ b/api/_lib/x402.js@@ -137,6 +137,8 @@ export async function emit402(res, { agent, skill, amount, currency, validForSec* @returns {Promise<null | { intentId: string, amount: string, currency: string, paidAt: Date }>}*/export async function verifyPaid(req, { agentId, skill, expectedAmount, expectedCurrency }) {+ if (!expectedAmount) throw new Error('verifyPaid: expectedAmount is required');+ if (!expectedCurrency) throw new Error('verifyPaid: expectedCurrency is required');const intentId = (req.headers['x-payment-intent'] || '').toString().trim();if (!intentId) return null;diff --git a/api/_lib/x402/access-control.js b/api/_lib/x402/access-control.jsindex 2de76a0c6..99194c935 100644--- a/api/_lib/x402/access-control.js+++ b/api/_lib/x402/access-control.js@@ -210,9 +210,9 @@ export function installAccessControl({ requiredScope, resolveCaller } = {}) {granted: false,meta,});- // Don't 403 — fall through to payment flow. The caller may- // simply have an unrelated user token they sent along.- return null;+ // An invalid/expired token is a clear auth failure — reject+ // with 401 rather than silently billing the caller.+ return { abort: true, status: 401, reason: 'invalid_token' };}if (!hasScope(claims.scope, requiredScope)) {logAccess({@@ -222,7 +222,8 @@ export function installAccessControl({ requiredScope, resolveCaller } = {}) {granted: false,meta: { ...meta, granted_scope: claims.scope },});- // Same — let them pay normally.+ // Wrong scope — fall through to payment flow so callers with a+ // valid session token can still pay for access to the endpoint.return null;}logAccess({diff --git a/api/agent-actions.js b/api/agent-actions.jsindex aeec4db99..75a39dfa2 100644--- a/api/agent-actions.js+++ b/api/agent-actions.js@@ -32,7 +32,10 @@ async function handleList(req, res) {const url = new URL(req.url, 'http://x');const agentId = url.searchParams.get('agent_id');const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 200);- const cursor = url.searchParams.get('cursor'); // bigserial id cursor+ const cursorRaw = url.searchParams.get('cursor');+ if (cursorRaw != null && !/^\d+$/.test(cursorRaw))+ return error(res, 400, 'validation_error', 'cursor must be a numeric id');+ const cursor = cursorRaw || null; // bigserial id cursorif (!agentId) return error(res, 400, 'validation_error', 'agent_id is required');diff --git a/api/agent-strategy.js b/api/agent-strategy.jsindex fccda32a0..83db82f18 100644--- a/api/agent-strategy.js+++ b/api/agent-strategy.js@@ -60,6 +60,9 @@ export default wrap(async (req, res) => {if (!body || body.strategy === undefined) {return error(res, 400, 'validation_error', 'request body must include `strategy`');}+ if (typeof body.strategy === 'string' && body.strategy.length > 64_000) {+ return error(res, 413, 'payload_too_large', 'strategy exceeds 64 KB limit');+ }const nextMeta = { ...(agent.meta || {}), strategy: body.strategy };await sql`diff --git a/api/agent-wallet-bridge.js b/api/agent-wallet-bridge.jsindex 058c9e17e..9be985110 100644--- a/api/agent-wallet-bridge.js+++ b/api/agent-wallet-bridge.js@@ -21,6 +21,7 @@import { cors, wrap, error, setRateLimitHeaders } from './_lib/http.js';import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';+import { requireCsrf } from './_lib/csrf.js';import { limits, clientIp } from './_lib/rate-limit.js';import { createSolanaSigner } from './_lib/x402/a2a-client.js';import { enforceCap, commit, rollbackReservation } from './_lib/x402-spending-cap.js';@@ -303,6 +304,8 @@ export default wrap(async (req, res) => {if (!sessionUser && !bearerUser) {return error(res, 401, 'unauthorized', 'Sign in to let your agent wallet make a real payment.');}+ const callerUserId = (sessionUser || bearerUser).userId ?? (sessionUser || bearerUser).id;+ if (!(await requireCsrf(req, res, callerUserId))) return;const rl = await limits.publicIp(clientIp(req));if (!rl.success) {diff --git a/api/agents/_id/memory-seed.js b/api/agents/_id/memory-seed.jsindex 9dec1ed24..e3a3e98c1 100644--- a/api/agents/_id/memory-seed.js+++ b/api/agents/_id/memory-seed.js@@ -178,13 +178,15 @@ export default async function handleMemorySeed(req, res, agentId) {return json(res, 200, { seeded: 0, facts: [], seeded_at: new Date().toISOString() });}- // Replace previous github memories with fresh distillation- await sql`DELETE FROM agent_memories WHERE agent_id = ${agentId} AND 'github' = ANY(tags)`;-+ // Replace previous github memories with the fresh distillation atomically, so+ // a mid-loop failure can't leave the agent with its old memories deleted and+ // only a partial new set (the 24h rate limit would then block a retry).const seededAt = new Date().toISOString();const ctx = JSON.stringify({ source: 'github_seed', seeded_at: seededAt });- for (const fact of facts) {- await sql`+ await sql.transaction([+ sql`DELETE FROM agent_memories WHERE agent_id = ${agentId} AND 'github' = ANY(tags)`,+ ...facts.map(+ (fact) => sql`INSERT INTO agent_memories (agent_id, type, content, tags, context, salience)VALUES (${agentId},@@ -194,8 +196,9 @@ export default async function handleMemorySeed(req, res, agentId) {${ctx}::jsonb,0.7)- `;- }+ `,+ ),+ ]);return json(res, 200, { seeded: facts.length, facts, seeded_at: seededAt });}diff --git a/api/agents/eth-vanity.js b/api/agents/eth-vanity.jsindex 1d084f80a..eef3de110 100644--- a/api/agents/eth-vanity.js+++ b/api/agents/eth-vanity.js@@ -29,6 +29,7 @@// }import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { requireCsrf } from '../_lib/csrf.js';import { sql } from '../_lib/db.js';import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -141,6 +142,10 @@ export default async function handler(req, res, id, action) {let meta = { ...(row.meta || {}) };+ if (req.method !== 'GET') {+ if (!(await requireCsrf(req, res, auth.userId))) return;+ }+if (req.method === 'DELETE') {delete meta.eth_vanity;await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;diff --git a/api/agents/identity-check.js b/api/agents/identity-check.jsindex 25a2be306..f9a3d8832 100644--- a/api/agents/identity-check.js+++ b/api/agents/identity-check.js@@ -50,8 +50,10 @@ export default wrap(async (req, res) => {const tags = Array.isArray(body.persona_tone_tags)? body.persona_tone_tags.map((t) => String(t).trim()).filter(Boolean).slice(0, 12): [];+ // Only honor excludeAgentId when the caller is authenticated — an unauthenticated+ // caller has no standing to exclude an arbitrary agent from the similarity check.const excludeAgentId =- typeof body.agent_id === 'string' && isUuid(body.agent_id) ? body.agent_id : null;+ userId && typeof body.agent_id === 'string' && isUuid(body.agent_id) ? body.agent_id : null;if (!name && !description) {return error(res, 400, 'validation_error', 'name or description is required');diff --git a/api/agents/payments/[action].js b/api/agents/payments/[action].jsindex a61a1ccab..539ea1aba 100644--- a/api/agents/payments/[action].js+++ b/api/agents/payments/[action].js@@ -434,9 +434,11 @@ async function handlePayConfirm(req, res) {const [updated] = await sql`update agent_payment_intentsset status = 'paid', tx_signature = ${body.tx_signature}, paid_at = now()- where id = ${intent.id}+ where id = ${intent.id} and status = 'pending'returning id, agent_id, amount, currency_mint, paid_at`;+ // Concurrent request already marked this paid — idempotent success.+ if (!updated) return json(res, 200, { ok: true, intent_id: intent.id, status: 'paid' });// Fire-and-forget: notify the agent owner that they received a payment.sql`select user_id from agent_identities where id = ${updated.agent_id} and deleted_at is null limit 1`diff --git a/api/agents/sns.js b/api/agents/sns.jsindex a92c4251d..99a90859e 100644--- a/api/agents/sns.js+++ b/api/agents/sns.js@@ -25,6 +25,7 @@// (the user owns the domain; we only store the alias against the agent).import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { requireCsrf } from '../_lib/csrf.js';import { sql } from '../_lib/db.js';import { submitProtected } from '../_lib/execution-engine.js';import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';@@ -128,6 +129,7 @@ async function handleCheck(req, res) {// ── Option A: agent wallet pays + auto-attach ─────────────────────────────async function handleRegisterAgent(req, res, id, auth) {if (!method(req, res, ['POST'])) return;+ if (!(await requireCsrf(req, res, auth.userId))) return;const body = await readJson(req).catch(() => ({}));const domain = normalizeDomain(body?.domain);if (!domain) return error(res, 400, 'validation_error', 'domain required (a–z, 0–9, hyphen)');@@ -169,6 +171,7 @@ async function handleRegisterAgent(req, res, id, auth) {// ── Option B step 1: build unsigned tx for user wallet ────────────────────async function handleRegisterPrep(req, res, id, auth) {if (!method(req, res, ['POST'])) return;+ if (!(await requireCsrf(req, res, auth.userId))) return;const body = await readJson(req).catch(() => ({}));const domain = normalizeDomain(body?.domain);if (!domain) return error(res, 400, 'validation_error', 'domain required');@@ -225,6 +228,7 @@ async function handleRegisterPrep(req, res, id, auth) {// ── Option B step 2: confirm and attach ───────────────────────────────────async function handleRegisterConfirm(req, res, id, auth) {if (!method(req, res, ['POST'])) return;+ if (!(await requireCsrf(req, res, auth.userId))) return;const body = await readJson(req).catch(() => ({}));const domain = normalizeDomain(body?.domain);const signature = String(body?.signature || '').trim();diff --git a/api/auth/[action].js b/api/auth/[action].jsindex 833a41b97..1869f43e9 100644--- a/api/auth/[action].js+++ b/api/auth/[action].js@@ -106,7 +106,13 @@ async function insertUserWithUniqueReferralCode({ email, passwordHash, displayNa`;return row;} catch (err) {- if (err && err.code === '23505' && /referral_code/.test(err.message || '')) continue;+ if (err?.code === '23505') {+ // Referral code collision → try next candidate.+ if (/referral_code/.test(err.message || '')) continue;+ // Email / display_name collision from a concurrent registration that+ // slipped past the pre-check — surface as a proper 409 instead of 500.+ throw Object.assign(new Error('email or username already in use'), { status: 409, code: 'conflict' });+ }throw err;}}@@ -148,12 +154,18 @@ async function handleRegister(req, res) {}const hash = await hashPassword(passwordVal);- const user = await insertUserWithUniqueReferralCode({- email: email_val,- passwordHash: hash,- displayName: displayName_val,- referredById: referred_by_id,- });+ let user;+ try {+ user = await insertUserWithUniqueReferralCode({+ email: email_val,+ passwordHash: hash,+ displayName: displayName_val,+ referredById: referred_by_id,+ });+ } catch (err) {+ if (err?.status === 409) return error(res, 409, err.code || 'conflict', err.message);+ throw err;+ }// Fire-and-forget: every new account gets a starter draft agent so the// marketplace's "My Agents" tab and onboarding flow have something to show.queueMicrotask(() => seedDefaultAgent(user.id));diff --git a/api/auth/github/[action].js b/api/auth/github/[action].jsindex 358069964..358ed2308 100644--- a/api/auth/github/[action].js+++ b/api/auth/github/[action].js@@ -124,6 +124,13 @@ async function handleCallback(req, res) {return error(res, 400, 'state_expired', 'OAuth state has expired — please try again');}+ // Session-bind: if a session is active it must match the state's userId so a+ // state token can't be replayed by a different user in their browser session.+ const callbackSession = await getSessionUser(req).catch(() => null);+ if (callbackSession && callbackSession.id !== stateData.userId) {+ return error(res, 403, 'session_mismatch', 'OAuth state does not match the current session');+ }+// Exchange code for access tokenconst tokenRes = await fetch('https://github.com/login/oauth/access_token', {method: 'POST',diff --git a/api/club/tips-stream.js b/api/club/tips-stream.jsindex 3384106e3..61288ebf4 100644--- a/api/club/tips-stream.js+++ b/api/club/tips-stream.js@@ -27,7 +27,12 @@ import { cors, method } from '../_lib/http.js';// Each registered listener is a function: (event, data) => void.const clients = new Set();let pollTimer = null;+// Compound cursor (created_at, ticket_id). A plain `created_at >` cursor drops+// tips that share an identical timestamp at the LIMIT boundary — realistic under+// the bursts this stream exists for. The unique ticket_id breaks ties so the+// cursor is strictly monotonic and lossless. Empty id sorts before any ticket.let sharedCursor = new Date();+let sharedCursorId = '';let idleTicks = 0;const HEARTBEAT_MS = 15_000;@@ -52,16 +57,17 @@ async function runSharedPoll() {select ticket_id, dancer, dance, clip, label, payer, network,amount_atomics, asset, started_at, ends_at, created_atfrom club_tips- where created_at > ${sharedCursor.toISOString()}- order by created_at asc+ where (created_at, ticket_id) > (${sharedCursor.toISOString()}::timestamptz, ${sharedCursorId})+ order by created_at asc, ticket_id asclimit ${MAX_ROWS_PER_TICK}`;if (rows.length > 0) {idleTicks = 0;- for (const row of rows) {- const ts = row.created_at instanceof Date ? row.created_at : new Date(row.created_at);- if (ts > sharedCursor) sharedCursor = ts;- }+ // Rows are ordered by (created_at, ticket_id); advance the cursor to the+ // last one so a same-timestamp tie split across batches isn't skipped.+ const last = rows[rows.length - 1];+ sharedCursor = last.created_at instanceof Date ? last.created_at : new Date(last.created_at);+ sharedCursorId = last.ticket_id;// Fan out to all connected clients.for (const send of clients) {for (const row of rows) {diff --git a/api/dad/generate.js b/api/dad/generate.jsnew file mode 100644index 000000000..9e00dfa22--- /dev/null+++ b/api/dad/generate.js@@ -0,0 +1,158 @@+/**+ * /api/dad/generate — headless photo → rigged 3D avatar for the /dad page.+ *+ * POST /api/dad/generate { image_url: string }+ * → 202 { job_id, status, eta_seconds, backend }+ *+ * GET /api/dad/generate?job=<id>+ * → 200 { job_id, status, glb_url?, error? }+ *+ * Isolated from the forge pipeline: it reuses the shared, platform-configured+ * reconstruct provider (Replicate Hunyuan3D → GCP → HF, resolved by env) via+ * getRegenProvider(), which returns an image→textured-GLB on a humanoid rig.+ * No forge routing, tiers, or providers are touched.+ *+ * No auth — this is a public, shareable feature. Spend is bounded by a per-IP+ * limiter PLUS the platform-wide cost circuit breaker whenever the resolved+ * lane bills real money (the same breaker the forge endpoint uses).+ */++import { cors, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { assertPublicHttpsUrl, SsrfError } from '../_lib/ssrf.js';+import { getRegenProvider } from '../_lib/regen-provider.js';++// Replicate prediction ids, GCP packed base64url envelopes, etc. — bounded.+const JOB_ID_RE = /^[A-Za-z0-9_=:.-]{8,512}$/;+// Lanes that bill real GPU money per generation — gated behind the+// platform-wide breaker on top of the per-IP cap.+const PAID_LANES = new Set(['replicate', 'gcp']);++function unconfigured(res) {+ return json(res, 503, {+ error: 'unconfigured',+ message:+ 'The 3D avatar engine is not available right now. Set a reconstruct provider ' ++ '(REPLICATE_API_TOKEN + REPLICATE_RECONSTRUCT_MODEL, or GCP_RECONSTRUCTION_URL).',+ });+}++async function startJob(req, res) {+ const ip = clientIp(req);+ const rl = await limits.mcp3dGenerate(ip);+ if (!rl.success) return rateLimited(res, rl);++ // Let wrap() surface a genuine 413 (too large) / 415 (not JSON) instead of+ // masking either as an "invalid_image_url" 400.+ const body = await readJson(req, 8_000).catch((e) => {+ if (e?.status === 413 || e?.status === 415) throw e;+ return null;+ });++ let imageUrl;+ try {+ const raw = typeof body?.image_url === 'string' ? body.image_url.trim() : '';+ imageUrl = await assertPublicHttpsUrl(raw);+ } catch (err) {+ return json(res, 400, {+ error: 'invalid_image_url',+ message:+ err instanceof SsrfError+ ? `image_url rejected: ${err.message}`+ : 'image_url must be a public https URL.',+ });+ }++ let resolved;+ try {+ resolved = await getRegenProvider();+ if (!resolved.instance || !resolved.instance.supportsMode('reconstruct')) {+ return unconfigured(res);+ }+ } catch {+ return unconfigured(res);+ }++ // Cost circuit breaker: this endpoint is unauthenticated, so the per-IP cap+ // alone doesn't bound total spend on the shared paid GPU budget.+ if (PAID_LANES.has(resolved.name)) {+ const g = await limits.mcp3dGenerateGlobal();+ if (!g.success) {+ return rateLimited(res, g, 'Paid 3D generation is at capacity right now — please try again shortly.');+ }+ }++ try {+ const job = await resolved.instance.submit({+ mode: 'reconstruct',+ sourceUrl: imageUrl,+ params: { images: [imageUrl], name: 'dad avatar' },+ });+ return json(res, 202, {+ job_id: job.extJobId,+ status: 'queued',+ eta_seconds: job.eta ?? 60,+ backend: job.backend || resolved.name || null,+ });+ } catch (err) {+ const status = err?.status >= 400 && err?.status < 600 ? err.status : 502;+ return json(res, status, {+ error: err?.code || 'reconstruct_failed',+ message: err?.message || 'The avatar job could not start.',+ });+ }+}++async function pollJob(req, res, jobId) {+ if (!JOB_ID_RE.test(jobId)) {+ return json(res, 400, { error: 'invalid_job', message: 'Malformed job id.' });+ }++ const rl = await limits.mcp3dStatus(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let provider;+ try {+ const resolved = await getRegenProvider();+ provider = resolved.instance;+ if (!provider) return unconfigured(res);+ } catch {+ return unconfigured(res);+ }++ // A transient status() throw must not 500 + ops-alert on every 2.5s poll —+ // report still-running so the client keeps polling toward its own timeout.+ let result;+ try {+ result = await provider.status(jobId);+ } catch {+ return json(res, 200, { job_id: jobId, status: 'running', glb_url: null, error: null });+ }+ result = result || {};++ // Some lanes emit a terminal "done" with no GLB + a precise error. Normalize+ // it to "failed" so the client fails fast with the real message rather than+ // waiting out its full timeout.+ const glb = result.resultGlbUrl || null;+ let status = result.status;+ if (status === 'done' && !glb) status = 'failed';++ return json(res, 200, {+ job_id: jobId,+ status,+ glb_url: glb,+ error: result.error || null,+ });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ if (req.method === 'POST') return startJob(req, res);++ const url = new URL(req.url, 'http://localhost');+ const jobId = (url.searchParams.get('job') || '').trim();+ if (!jobId) return json(res, 400, { error: 'missing_job', message: 'Pass ?job=<id> to poll.' });+ return pollJob(req, res, jobId);+});diff --git a/api/marketplace/[action].js b/api/marketplace/[action].jsindex ae74bc331..d2968185e 100644--- a/api/marketplace/[action].js+++ b/api/marketplace/[action].js@@ -1177,7 +1177,7 @@ async function handleFork(req, res, id) {`;if (!src) return error(res, 404, 'not_found', 'agent not found');- const [created] = await sql.transaction([+ const [createdRows] = await sql.transaction([sql`INSERT INTO agent_identities (user_id, name, description, avatar_id, skills, meta,@@ -1202,6 +1202,8 @@ async function handleFork(req, res, id) {sql`UPDATE agent_identities SET forks_count = forks_count + 1 WHERE id = ${id}`,]);+ const created = createdRows[0];+ if (!created) return error(res, 500, 'db_error', 'Fork failed');return json(res, 201, { data: { agent: created } });}@@ -1274,7 +1276,7 @@ async function handlePublish(req, res, id) {FROM agent_versions WHERE agent_id = ${id}`;- const [updated] = await sql.transaction([+ const [updatedRows] = await sql.transaction([sql`UPDATE agent_identitiesSET is_published = true,@@ -1299,6 +1301,8 @@ async function handlePublish(req, res, id) {`,]);+ const updated = updatedRows[0];+ if (!updated) return error(res, 404, 'not_found', 'agent not found');return json(res, 200, { data: { agent: toDetail(updated, {}, auth.userId), version: next_version } });}diff --git a/api/marketplace/buy-asset.js b/api/marketplace/buy-asset.jsindex 3afc7d2ec..44bee1ba0 100644--- a/api/marketplace/buy-asset.js+++ b/api/marketplace/buy-asset.js@@ -409,7 +409,11 @@ async function handleEvmAssetConfirm(req, res, pur) {const txHash = body?.tx_hash || body?.txHash || null;if (!txHash) return error(res, 400, 'tx_hash_required', 'tx_hash is required to confirm an EVM purchase');- // Idempotency: one settlement tx can confirm at most one purchase.+ // Idempotency guard: check already-settled rows AND atomically lock this+ // purchase by writing tx_signature before we hit the payment verifier.+ // Without this, two concurrent confirms of different pending purchases with+ // the same tx_hash could both pass the old read-only dupe check and both+ // call finalizeAssetConfirm (one tx → two confirmed rows).const [dupe] = await sql`SELECT id FROM asset_purchasesWHERE tx_signature = ${txHash} AND status IN ('confirmed', 'tipped') AND id != ${pur.id}@@ -417,6 +421,27 @@ async function handleEvmAssetConfirm(req, res, pur) {`;if (dupe) return error(res, 409, 'transfer_mismatch', 'this transaction has already been used for another purchase');+ // Atomically claim this tx_hash on this purchase row before hitting the+ // payment verifier. This prevents a concurrent confirm of a *different*+ // pending purchase from using the same hash while this request is in flight+ // (the unique constraint + IS NULL guard block the other row's claim).+ // Retries of this same purchase with the same hash match the second condition+ // and proceed normally (idempotent).+ const claimed = await sql`+ UPDATE asset_purchases+ SET tx_signature = ${txHash}, updated_at = now()+ WHERE id = ${pur.id} AND status = 'pending'+ AND (tx_signature IS NULL OR tx_signature = ${txHash})+ RETURNING id+ `;+ if (claimed.length === 0) {+ // Another concurrent request already claimed a different tx_hash for this+ // purchase, or the purchase moved out of pending. Re-read current state.+ const [current] = await sql`SELECT status, tx_signature FROM asset_purchases WHERE id = ${pur.id}`;+ if (current?.status === 'confirmed') return json(res, 200, { data: { status: 'confirmed', tx_signature: current.tx_signature } });+ return error(res, 409, 'transfer_mismatch', 'a different transaction is already being confirmed for this purchase');+ }+const result = await verifyEvmUsdcPayment({txHash,chain: pur.chain,diff --git a/api/og/agent.js b/api/og/agent.jsindex 16b03da4e..fb37f860d 100644--- a/api/og/agent.js+++ b/api/og/agent.js@@ -90,10 +90,18 @@ export default wrap(async (req, res) => {try {const imgResp = await fetch(imgUrl, { signal: AbortSignal.timeout(3000) });if (imgResp.ok) {- const ct = imgResp.headers.get('content-type') || 'image/jpeg';- const ab = await imgResp.arrayBuffer();- const b64 = Buffer.from(ab).toString('base64');- avatarData = { ct, b64 };+ // Cap the inlined avatar so a large/corrupt thumbnail can't bloat the+ // SVG (and this function's memory). Thumbnails are small JPEGs/PNGs.+ const MAX_AVATAR_BYTES = 2 * 1024 * 1024;+ const declared = Number(imgResp.headers.get('content-length') || 0);+ if (!declared || declared <= MAX_AVATAR_BYTES) {+ const ct = imgResp.headers.get('content-type') || 'image/jpeg';+ const ab = await imgResp.arrayBuffer();+ if (ab.byteLength <= MAX_AVATAR_BYTES) {+ const b64 = Buffer.from(ab).toString('base64');+ avatarData = { ct, b64 };+ }+ }}} catch { /* non-fatal — use gradient fallback */ }}diff --git a/api/payments/evm/[action].js b/api/payments/evm/[action].jsindex 108efc4d2..d07768c83 100644--- a/api/payments/evm/[action].js+++ b/api/payments/evm/[action].js@@ -112,17 +112,26 @@ async function handleConfirm(req, res) {const [dupe] = await sql`select id from plan_payment_intents where chain_type = 'evm' and tx_hash = ${tx_hash} and status = 'confirmed' limit 1`;if (dupe) return error(res, 409, 'tx_already_used', 'this transaction has already been used to confirm a payment');+ // All three writes are in a single transaction so a crash between intent-claim+ // and the subscription/user grant can't leave the user paid but unsubscribed.+ // The intent UPDATE uses status='pending' (not != 'confirmed') so an already-+ // expired intent can't slip through a race between the expiry check above and+ // this write. On a unique-index violation (concurrent confirm with same tx_hash)+ // the entire transaction rolls back and we return 409.+ const planConfig = PLANS[intent.plan];+ const activeUntil = new Date(Date.now() + planConfig.duration_days * 86400 * 1000);+ let claimed;try {- await sql`update plan_payment_intents set status='confirmed', tx_hash=${tx_hash}, confirmed_at=now() where id=${intent_id} and status != 'confirmed'`;+ [claimed] = await sql.transaction([+ sql`update plan_payment_intents set status='confirmed', tx_hash=${tx_hash}, confirmed_at=now() where id=${intent_id} and status = 'pending' returning id`,+ sql`insert into subscriptions (user_id, plan, chain_type, chain_id, token_address, tx_hash, amount_usd, status, active_until) values (${user.id}, ${intent.plan}, 'evm', ${chainId}, ${usdcAddress}, ${tx_hash}, ${intent.amount_usdc}, 'active', ${activeUntil}) on conflict (user_id) where status='active' do update set plan=excluded.plan, chain_type=excluded.chain_type, chain_id=excluded.chain_id, token_address=excluded.token_address, tx_hash=excluded.tx_hash, amount_usd=excluded.amount_usd, active_until=excluded.active_until, updated_at=now()`,+ sql`update users set plan=${intent.plan} where id=${user.id}`,+ ]);} catch (e) {- // Unique-index violation: a concurrent confirm claimed this tx first.if (e?.code === '23505') return error(res, 409, 'tx_already_used', 'this transaction has already been used to confirm a payment');throw e;}- const planConfig = PLANS[intent.plan];- const activeUntil = new Date(Date.now() + planConfig.duration_days * 86400 * 1000);- await sql`insert into subscriptions (user_id, plan, chain_type, chain_id, token_address, tx_hash, amount_usd, status, active_until) values (${user.id}, ${intent.plan}, 'evm', ${chainId}, ${usdcAddress}, ${tx_hash}, ${intent.amount_usdc}, 'active', ${activeUntil}) on conflict (user_id) where status='active' do update set plan=excluded.plan, chain_type=excluded.chain_type, chain_id=excluded.chain_id, token_address=excluded.token_address, tx_hash=excluded.tx_hash, amount_usd=excluded.amount_usd, active_until=excluded.active_until, updated_at=now()`;- await sql`update users set plan=${intent.plan} where id=${user.id}`;+ if (!claimed?.[0]) return error(res, 409, 'already_confirmed', 'payment already confirmed');queueMicrotask(() => sendSubscriptionConfirmEmail({ to: user.email, plan: intent.plan, chain: `EVM chain ${chainId}`, txId: tx_hash }).catch(() => {}));return json(res, 200, { ok: true, plan: intent.plan, active_until: activeUntil.toISOString(), tx_hash });}diff --git a/api/payments/intent.js b/api/payments/intent.jsindex 1ad7c3069..e6da53d07 100644--- a/api/payments/intent.js+++ b/api/payments/intent.js@@ -24,7 +24,8 @@ export default wrap(async (req, res) => {const rl = await limits.authIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const body = await readJson(req).catch(() => null);+ let body;+ try { body = await readJson(req); } catch { return error(res, 400, 'invalid_json', 'request body is not valid JSON'); }const agent_id = body?.agent_id;const skill = typeof body?.skill === 'string' ? body.skill.trim() : null;if (!agent_id || !skill) {diff --git a/api/payments/solana/[action].js b/api/payments/solana/[action].jsindex 04bb39764..8174286f2 100644--- a/api/payments/solana/[action].js+++ b/api/payments/solana/[action].js@@ -18,7 +18,9 @@ const SOLANA_RPC_DEVNET = process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devconst checkoutSchema = z.object({plan: z.enum(['pro', 'team', 'enterprise']),- network: z.enum(['mainnet', 'devnet']).default('mainnet'),+ // Devnet is only accepted in non-production environments. Accepting devnet+ // USDC (free from faucet) in production would let anyone upgrade for free.+ network: z.enum(process.env.NODE_ENV === 'production' ? ['mainnet'] : ['mainnet', 'devnet']).default('mainnet'),});async function handleCheckout(req, res) {@@ -97,7 +99,10 @@ async function handleConfirm(req, res) {const parsed = ix.parsed;if (parsed?.type !== 'transferChecked' && parsed?.type !== 'transfer') return false;const info = parsed.info;- const mintMatch = !info.mint || info.mint === usdcMint;+ // Require an explicit mint match. `type='transfer'` (legacy Token Program)+ // omits mint from parsed.info — we reject it rather than accepting any token.+ // The balance-delta fallback below correctly requires post.mint === usdcMint.+ const mintMatch = info.mint === usdcMint;const amount = BigInt(info.tokenAmount?.amount ?? info.amount ?? '0');return mintMatch && amount >= expectedAtomics && (info.destination === expectedRecipient || info.destinationOwner === expectedRecipient);});@@ -119,12 +124,17 @@ async function handleConfirm(req, res) {// not in one transaction, so two concurrent confirms for the same intent could// both pass the status guard. The conditional UPDATE lets exactly one win; if// it claims no row, another request already confirmed → 409 (no double grant).- const [claimed] = await sql`update plan_payment_intents set status='confirmed', tx_hash=${tx_signature}, confirmed_at=now() where id=${intent_id} and status <> 'confirmed' returning id`;- if (!claimed) return error(res, 409, 'already_confirmed', 'payment already confirmed');+ // All three writes in one transaction: intent claim + subscription grant + user+ // plan update. A crash between claim and grant can't leave the user paid but+ // unsubscribed (the 409 they'd get on retry would permanently block recovery).const planConfig = PLANS[intent.plan];const activeUntil = new Date(Date.now() + planConfig.duration_days * 86400 * 1000);- await sql`insert into subscriptions (user_id, plan, chain_type, token_address, tx_hash, amount_usd, status, active_until) values (${user.id}, ${intent.plan}, 'solana', ${usdcMint}, ${tx_signature}, ${intent.amount_usdc}, 'active', ${activeUntil}) on conflict (user_id) where status='active' do update set plan=excluded.plan, chain_type=excluded.chain_type, token_address=excluded.token_address, tx_hash=excluded.tx_hash, amount_usd=excluded.amount_usd, active_until=excluded.active_until, updated_at=now()`;- await sql`update users set plan=${intent.plan} where id=${user.id}`;+ const [claimed] = await sql.transaction([+ sql`update plan_payment_intents set status='confirmed', tx_hash=${tx_signature}, confirmed_at=now() where id=${intent_id} and status = 'pending' returning id`,+ sql`insert into subscriptions (user_id, plan, chain_type, token_address, tx_hash, amount_usd, status, active_until) values (${user.id}, ${intent.plan}, 'solana', ${usdcMint}, ${tx_signature}, ${intent.amount_usdc}, 'active', ${activeUntil}) on conflict (user_id) where status='active' do update set plan=excluded.plan, chain_type=excluded.chain_type, token_address=excluded.token_address, tx_hash=excluded.tx_hash, amount_usd=excluded.amount_usd, active_until=excluded.active_until, updated_at=now()`,+ sql`update users set plan=${intent.plan} where id=${user.id}`,+ ]);+ if (!claimed?.[0]) return error(res, 409, 'already_confirmed', 'payment already confirmed');queueMicrotask(() => sendSubscriptionConfirmEmail({ to: user.email, plan: intent.plan, chain: `Solana ${network}`, txId: tx_signature }).catch(() => {}));return json(res, 200, { ok: true, plan: intent.plan, active_until: activeUntil.toISOString(), tx_signature });}diff --git a/api/pump-fun-mcp.js b/api/pump-fun-mcp.jsindex ee5fed7b9..2ffa53e72 100644--- a/api/pump-fun-mcp.js+++ b/api/pump-fun-mcp.js@@ -39,12 +39,12 @@ import {} from './_lib/x402-spec.js';import { getPumpSdk, getConnection, solanaPubkey, getAmmPoolState } from './_lib/pump.js';import { pumpfunMcp, pumpfunBotEnabled } from './_lib/pumpfun-mcp.js';-import { getRadarSignals } from '../src/kol/radar.js';import { TOOLS, resolveToolName, rpcError, rpcEnvelope } from '../src/pump/mcp-tools.js';import { generateVanityKey } from '../src/pump/vanity-keygen.js';import bs58 from 'bs58';import { resolveSnsName, reverseLookupAddress } from '../src/solana/sns.js';import { scanFirstClaims } from './_lib/pump-claims.js';+import { getSolPriceUsd } from '../src/shared/usd-price.js';// ── On-chain handlers ──────────────────────────────────────────────────────@@ -119,10 +119,10 @@ async function handleGetTokenDetails({ mint, network = 'mainnet' }) {const buf = metaInfo.data;let cursor = 1 + 32 + 32;const readStr = (max) => {- const len = buf.readUInt32LE(cursor);+ const len = Math.min(buf.readUInt32LE(cursor), max);cursor += 4;const slice = buf.slice(cursor, cursor + len);- cursor += max;+ cursor += max; // always step the full fixed-width fieldreturn slice.toString('utf8').replace(/\0+$/g, '').trim();};name = readStr(32);@@ -179,12 +179,6 @@ async function handleGetTokenHolders({ mint, limit = 10, network = 'mainnet' })};}-// ── kol_radar handler ──────────────────────────────────────────────────────--async function handleKolRadar({ category = 'pump-fun', limit = 20 }) {- return getRadarSignals({ category, limit });-}-async function handleKolLeaderboard({ window = '7d', limit = 25 }) {const { getLeaderboard } = await import('../src/kol/leaderboard.js');return getLeaderboard({ window, limit });@@ -646,7 +640,7 @@ async function readTradesFromChain({ mint, limit, network }) {import('@coral-xyz/anchor'),import('@pump-fun/pump-sdk'),import('@pump-fun/pump-swap-sdk'),- getSolPriceUsd(),+ getSolPriceUsd().catch(() => 150),]);const { BorshCoder, EventParser } = anchor;@@ -1309,7 +1303,6 @@ const HANDLERS = {get_token_holders: handleGetTokenHolders,get_coin_intel: handleGetCoinIntel,get_oracle_conviction: handleGetOracleConviction,- kol_radar: handleKolRadar,kol_leaderboard: handleKolLeaderboard,search_tokens: indexerOrUnavailable('search_tokens'),get_token_trades: handleGetTokenTrades,@@ -1357,7 +1350,7 @@ const INSTRUCTIONS ='get_token_holders, get_token_details, get_token_trades), creator intelligence ' +'(get_creator_profile, pumpfun_list_claims, pumpfun_watch_claims, ' +'pumpfun_first_claims), Solana Name Service (sns_resolve, sns_reverseLookup), ' +- 'market signals (kol_radar, kol_leaderboard, pumpfun_quote_swap, ' ++ 'market signals (kol_leaderboard, pumpfun_quote_swap, ' +'pumpfun_watch_whales), and social sentiment (social_cashtag_sentiment, ' +'social_x_post_impact). Discovery tools require the indexer backend — call ' +'pumpfun_bot_status (always available) to check. ' +diff --git a/api/pump/[action].js b/api/pump/[action].jsindex 0da4206f9..479e48f9f 100644--- a/api/pump/[action].js+++ b/api/pump/[action].js@@ -474,12 +474,7 @@ async function handleBuyPrep(req, res) {tx_base64,});} catch (e) {- return error(- res,- e.status || 502,- e.code || 'pump_sdk_error',- e.message || 'failed to build buy tx',- );+ return respondError(res, e.status || 502, e.code || 'pump_sdk_error', e);}}@@ -798,12 +793,7 @@ async function handleSellPrep(req, res) {tx_base64,});} catch (e) {- return error(- res,- e.status || 502,- e.code || 'pump_sdk_error',- e.message || 'failed to build sell tx',- );+ return respondError(res, e.status || 502, e.code || 'pump_sdk_error', e);}}@@ -2113,7 +2103,7 @@ async function handleAcceptPaymentConfirm(req, res) {// ── payments-list ──────────────────────────────────────────────────────────async function handlePaymentsList(req, res) {- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET'])) return;const rl = await limits.authIp(clientIp(req));@@ -2123,7 +2113,14 @@ async function handlePaymentsList(req, res) {const mint = url.searchParams.get('mint');const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';const limit = Math.min(Number(url.searchParams.get('limit') || 50), 500);- const includePending = url.searchParams.get('include_pending') === '1';+ const wantsPending = url.searchParams.get('include_pending') === '1';++ // Pending payments expose unconfirmed invoices — require auth.+ if (wantsPending) {+ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required to view pending payments');+ }+ const includePending = wantsPending;if (!mint) return error(res, 400, 'validation_error', 'mint required');@@ -2882,12 +2879,7 @@ async function handleQuote(req, res) {quote,});} catch (err) {- return error(- res,- err.status || 502,- err.code || 'pump_sdk_error',- err.message || 'pump.fun SDK error',- );+ return respondError(res, err.status || 502, err.code || 'pump_sdk_error', err);}}@@ -3084,9 +3076,12 @@ async function resolveStrategyMints(invoke, strategy, explicit, limit) {}async function handleStrategyBacktest(req, res) {- if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;+ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');+const rl = await limits.authIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);@@ -3720,7 +3715,10 @@ const _deliverSchema = _z.object({});async function handleDeliverTelegram(req, res) {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;+ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const botToken = process.env.TELEGRAM_BOT_TOKEN;if (!botToken) return error(res, 500, 'misconfigured', 'TELEGRAM_BOT_TOKEN is not set');const raw = await readJson(req);@@ -3786,11 +3784,13 @@ async function handleFirstClaims(req, res) {// ── vanity-keygen (SSE) ───────────────────────────────────────────────────────async function handleVanityKeygen(req, res) {- if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (req.method !== 'POST') {res.setHeader('allow', 'POST');return error(res, 405, 'method_not_allowed', 'method POST required');}+ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');const rl = await limits.mcpIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);let body;diff --git a/api/pump/helius-webhook.js b/api/pump/helius-webhook.jsindex 877f42ed0..e7e8ff308 100644--- a/api/pump/helius-webhook.js+++ b/api/pump/helius-webhook.js@@ -15,15 +15,19 @@// webhookURL: `${env.APP_ORIGIN}/api/pump/helius-webhook`,// });-import { timingSafeEqual } from 'node:crypto';+import { timingSafeEqual, createHash } from 'node:crypto';import { sql, sqlValues } from '../_lib/db.js';import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';import { parsePumpTrades } from '../_lib/helius.js';import { WSOL_MINT } from '../_lib/pump-quote.js';function safeEqual(a, b) {- if (typeof a !== 'string' || typeof b !== 'string' || a.length !== b.length) return false;- return timingSafeEqual(Buffer.from(a), Buffer.from(b));+ if (typeof a !== 'string' || typeof b !== 'string') return false;+ // Hash both values so the comparison buffers are always equal length — a+ // length pre-check leaks the secret's length as a timing side-channel.+ const ha = createHash('sha256').update(a).digest();+ const hb = createHash('sha256').update(b).digest();+ return timingSafeEqual(ha, hb);}export default wrap(async (req, res) => {diff --git a/api/users/[username].js b/api/users/[username].jsindex e325ce989..9f17c9cac 100644--- a/api/users/[username].js+++ b/api/users/[username].js@@ -340,15 +340,15 @@ export default wrap(async (req, res) => {`.catch(() => [{ followers: 0, following: 0 }]);const stats = {- avatars: statsRow?.avatars_count ?? 0,- agents: statsRow?.agents_count ?? 0,- widgets: statsRow?.widgets_count ?? 0,- skills: statsRow?.skills_count ?? 0,- plugins: statsRow?.plugins_count ?? 0,- coins: statsRow?.coins_count ?? 0,- memories: statsRow?.memories_count ?? 0,+ avatars: statsRow?.[0]?.avatars_count ?? 0,+ agents: statsRow?.[0]?.agents_count ?? 0,+ widgets: statsRow?.[0]?.widgets_count ?? 0,+ skills: statsRow?.[0]?.skills_count ?? 0,+ plugins: statsRow?.[0]?.plugins_count ?? 0,+ coins: statsRow?.[0]?.coins_count ?? 0,+ memories: statsRow?.[0]?.memories_count ?? 0,shop: shop.length,- widget_views: Number(statsRow?.total_widget_views ?? 0),+ widget_views: Number(statsRow?.[0]?.total_widget_views ?? 0),followers: followCounts?.followers ?? 0,following: followCounts?.following ?? 0,};diff --git a/api/users/[username]/collectibles.js b/api/users/[username]/collectibles.jsindex 73763e9d9..e7ff1e5e3 100644--- a/api/users/[username]/collectibles.js+++ b/api/users/[username]/collectibles.js@@ -110,12 +110,18 @@ export default wrap(async (req, res) => {];// Accessories: premium cosmetics any of the user's wallets actually own.- const accessories = await loadAccessories([...sol.keys(), ...evm.keys()]);+ // Pass ORIGINAL-case addresses — cosmetic ownership is keyed on the exact+ // account string the buyer signed with (normalizeAccountId never lowercases),+ // so a lowercased EVM key would miss a checksummed purchase.+ const accessories = await loadAccessories(+ [...sol.values(), ...evm.values()].map((w) => w.address),+ );// NFTs across all wallets. Each cache MISS that reaches a billed provider// must pass the shared Helius DAS ceiling — a hard cost cap independent of// caching (which can't stop enumeration of distinct usernames).let nfts = [];+ let nftFetchBlocked = false;const solWallets = [...sol.keys()].slice(0, MAX_WALLETS_PER_CHAIN);const evmWallets = [...evm.values()].slice(0, MAX_WALLETS_PER_CHAIN);@@ -126,17 +132,23 @@ export default wrap(async (req, res) => {...solWallets.map((w) => fetchSolanaNfts(w).catch(() => [])),...evmWallets.map((w) => fetchEvmNfts(w.address, w.chainId).catch(() => [])),]);+ // Sort models-first across the WHOLE set before capping, so 3D NFTs are+ // never dropped by the cap in favour of plain images.+ const all = batches.flat().filter(Boolean);+ all.sort((a, b) => (b.model ? 1 : 0) - (a.model ? 1 : 0));const seen = new Set();- for (const item of batches.flat()) {- if (!item || seen.has(item.id)) continue;+ for (const item of all) {+ if (seen.has(item.id)) continue;seen.add(item.id);nfts.push(item);if (nfts.length >= NFT_CAP) break;}- // Models first (they render in 3D on the profile), then the rest.- nfts.sort((a, b) => (b.model ? 1 : 0) - (a.model ? 1 : 0));+ } else {+ // Ceiling hit: nfts stays []; the tab shows its empty state. Don't cache+ // this degraded result — a cache write here would pin empty NFTs for the+ // full TTL even after the ceiling resets.+ nftFetchBlocked = true;}- // ceiling hit → nfts stays []; the tab simply shows its empty state.}const payload = {@@ -150,7 +162,7 @@ export default wrap(async (req, res) => {},};- await cacheSet(cacheKey, payload, CACHE_TTL_SECONDS).catch(() => {});+ if (!nftFetchBlocked) await cacheSet(cacheKey, payload, CACHE_TTL_SECONDS).catch(() => {});res.setHeader('Cache-Control', 'public, s-maxage=300, stale-while-revalidate=900');return json(res, 200, payload);diff --git a/api/users/referral-claim.js b/api/users/referral-claim.jsindex 02bf08974..309aee57b 100644--- a/api/users/referral-claim.js+++ b/api/users/referral-claim.js@@ -50,7 +50,7 @@ export default wrap(async (req, res) => {if (!CODE_RE.test(code)) return error(res, 400, 'invalid_code', 'malformed referral code');const [me] = await sql`- SELECT id, referred_by_id, created_at, referral_code+ SELECT id, referred_by_id, created_at, referral_code, display_nameFROM users WHERE id = ${session.id} AND deleted_at IS NULL`;if (!me) return error(res, 404, 'not_found', 'user not found');diff --git a/api/users/referral-code.js b/api/users/referral-code.jsindex 1c824ff69..94582fa2a 100644--- a/api/users/referral-code.js+++ b/api/users/referral-code.js@@ -34,8 +34,20 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET', 'PUT'])) return;- const rl = await limits.authIp(clientIp(req));- if (!rl.success) return rateLimited(res, rl);+ const ip = clientIp(req);++ // GET (availability check) gets its own lighter bucket — typing a 20-char+ // vanity code produces ~20 debounced requests and must not eat the shared+ // authIp budget that login/registration use, which would lock out all users+ // from the same IP (offices, shared NAT) for up to 10 minutes.+ // PUT (set code) is a mutation → strict authIp.+ if (req.method === 'GET') {+ const rl = await limits.referralCodeCheckIp(ip);+ if (!rl.success) return rateLimited(res, rl);+ } else {+ const rl = await limits.authIp(ip);+ if (!rl.success) return rateLimited(res, rl);+ }const auth = await resolveAuth(req);if (!auth) return error(res, 401, 'unauthorized', 'sign in required');diff --git a/api/x402-checkout.js b/api/x402-checkout.jsindex 8156405d0..c6c81933b 100644--- a/api/x402-checkout.js+++ b/api/x402-checkout.js@@ -40,6 +40,7 @@ import { cors, json, method, readJson, wrap, error, rateLimited } from './_lib/himport { parse } from './_lib/validate.js';import { limits, clientIp } from './_lib/rate-limit.js';import { NETWORK_SOLANA_MAINNET, NETWORK_SOLANA_DEVNET } from './_lib/x402-spec.js';+import { confirmSolanaPayment } from './_lib/x402-solana-confirm.js';import { env } from './_lib/env.js';// Routed through env.* so the `api-mainnet.helius-rpc.com` misconfig is repaired@@ -378,6 +379,21 @@ async function handleEncode(req, res) {const body = parse(encodeSchema, await readJson(req));const { accept, signed_tx_base64, resource_url, builder_code } = body;++ // Defense-in-depth: verify the signed transaction actually pays the declared+ // amount to the declared recipient before wrapping it into the X-PAYMENT+ // header. The downstream facilitator /verify also checks, but a bad tx caught+ // here gives the user a clear error before the payment even hits the wire.+ if (accept.asset && accept.payTo && accept.amount) {+ const check = confirmSolanaPayment({+ paymentPayload: { payload: { transaction: signed_tx_base64 } },+ requirement: { asset: accept.asset, payTo: accept.payTo, amount: accept.amount },+ });+ if (check.confirmed === false) {+ return error(res, 400, 'invalid_payment', check.reason || 'transaction does not meet payment requirements');+ }+ }+const payload = {x402Version: 2,scheme: 'exact',diff --git a/api/x402/did.js b/api/x402/did.jsindex 1ff26a8bb..a91f5898e 100644--- a/api/x402/did.js+++ b/api/x402/did.js@@ -24,7 +24,8 @@ export default async function handler(req, res) {try {built = await getIssuer();} catch (err) {- return error(res, 500, 'issuer_misconfigured', err.message);+ console.error('[x402/did] issuer error:', err?.message);+ return error(res, 500, 'issuer_misconfigured', 'signing key configuration error');}if (!built) {return error(diff --git a/avatar-sdk/src/viewer.js b/avatar-sdk/src/viewer.jsindex 6f484f15d..aaa2ed9ba 100644--- a/avatar-sdk/src/viewer.js+++ b/avatar-sdk/src/viewer.js@@ -80,9 +80,11 @@ class ThreeWsViewerElement extends HTMLElement {this._renderer.forceContextLoss?.();this._renderer = null;}+ this._envTex?.dispose();+ this._envTex = null;+ if (this._model) { this._disposeModel(this._model); this._model = null; }this._scene = null;this._camera = null;- this._model = null;}attributeChangedCallback(name, _old, value) {@@ -115,7 +117,9 @@ class ThreeWsViewerElement extends HTMLElement {this._renderer.toneMappingExposure = 1.0;const pmrem = new PMREMGenerator(this._renderer);- this._scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;+ this._envTex = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;+ this._scene.environment = this._envTex;+ pmrem.dispose();this._scene.add(new AmbientLight(0xffffff, 0.55));const key = new DirectionalLight(0xffffff, 1.1);@@ -148,7 +152,7 @@ class ThreeWsViewerElement extends HTMLElement {try {const gltf = await loader.loadAsync(url);if (token !== this._loadToken || !this._scene) return;- if (this._model) this._scene.remove(this._model);+ if (this._model) { this._scene.remove(this._model); this._disposeModel(this._model); }this._model = gltf.scene;this._scene.add(this._model);this._frameModel(this._model);@@ -210,6 +214,18 @@ class ThreeWsViewerElement extends HTMLElement {this._label.textContent = text;}+ _disposeModel(obj) {+ obj?.traverse?.((n) => {+ n.geometry?.dispose?.();+ const mats = Array.isArray(n.material) ? n.material : [n.material];+ mats.forEach((m) => {+ if (!m) return;+ for (const v of Object.values(m)) if (v?.isTexture) v.dispose();+ m.dispose?.();+ });+ });+ }+_render() {if (!this._renderer) return;this._raf = requestAnimationFrame(this._render);diff --git a/chat/src/tools.js b/chat/src/tools.jsindex 91ece12fe..6d887d1b5 100644--- a/chat/src/tools.js+++ b/chat/src/tools.js@@ -1944,24 +1944,6 @@ export const pumpToolSchema = {},},},- {- clientDefinition: {- id: 'pump-kol-012',- name: 'kol_radar',- description: 'Early-detection signals for memecoins from KOL wallets.',- arguments: [{ name: 'limit', type: 'number', description: 'Number of signals (default 20)' }],- body: pumpBody('kol_radar'),- },- type: 'function',- function: {- name: 'kol_radar',- description: 'Get early-detection alpha signals from key opinion leader (KOL) wallets on pump.fun.',- parameters: {- type: 'object',- properties: { limit: { type: 'integer', default: 20, description: 'Number of signals to return' } },- },- },- },],};diff --git a/data/pages.json b/data/pages.jsonindex 06b5ae917..e861f5f3a 100644--- a/data/pages.json+++ b/data/pages.json@@ -424,6 +424,14 @@"priority": 0.7,"changefreq": "monthly","added": "2026-05-29"+ },+ {+ "path": "/dad",+ "title": "Make Dad a 3D Avatar",+ "description": "Turn one photo of your dad into a recognizable, rigged, animated 3D avatar — it idles, walks, and waves — then share a permalink.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-06-21"}]},diff --git a/mcp-bridge/src/x402-axios-client.js b/mcp-bridge/src/x402-axios-client.jsindex ef6e466f3..54d74d7da 100644--- a/mcp-bridge/src/x402-axios-client.js+++ b/mcp-bridge/src/x402-axios-client.js@@ -112,15 +112,18 @@ export function buildSpendingCapHook() {}}- // 3. Cumulative session ceiling. Reserve atomically so concurrent calls- // can't both pass the check and jointly overshoot the cap.- if (sessionSpentAtomic + amount > totalCap) {+ // 3. Cumulative session ceiling. Pre-reserve before any await so two+ // concurrent calls can't both pass the check and jointly overshoot the cap+ // (JavaScript is single-threaded but the check+increment isn't atomic across+ // an await boundary — pre-reserving makes it atomic).+ sessionSpentAtomic += amount;+ if (sessionSpentAtomic > totalCap) {+ sessionSpentAtomic -= amount; // rollback the reservationreturn {abort: true,- reason: `payment refused: would exceed session spend cap (${sessionSpentAtomic + amount} > ${totalCap}; already spent ${sessionSpentAtomic}). Set MCP_BRIDGE_MAX_TOTAL_ATOMIC to raise it.`,+ reason: `payment refused: would exceed session spend cap (would reach ${sessionSpentAtomic + amount} > ${totalCap}; already spent ${sessionSpentAtomic}). Set MCP_BRIDGE_MAX_TOTAL_ATOMIC to raise it.`,};}- sessionSpentAtomic += amount;return undefined;};}diff --git a/packages/pumpfun-mcp/src/index.js b/packages/pumpfun-mcp/src/index.jsindex 78d8b04e5..cebc2afb7 100755--- a/packages/pumpfun-mcp/src/index.js+++ b/packages/pumpfun-mcp/src/index.js@@ -115,7 +115,7 @@ async function main() {'getKingOfTheHill), on-chain analysis (getBondingCurve, getTokenHolders, ' +'getTokenDetails, getTokenTrades), creator intelligence (getCreatorProfile, ' +'pumpfun_list_claims, pumpfun_watch_claims, pumpfun_first_claims), Solana Name ' +- 'Service (sns_resolve, sns_reverseLookup), market signals (kol_radar, ' ++ 'Service (sns_resolve, sns_reverseLookup), market signals (' +'kol_leaderboard, pumpfun_quote_swap, pumpfun_watch_whales), and social ' +'sentiment (social_cashtag_sentiment, social_x_post_impact). All data is live ' +'and on-chain; no API keys required.',diff --git a/packages/pumpfun-mcp/src/tools.js b/packages/pumpfun-mcp/src/tools.jsindex c6d7b66e9..3c86f7b3b 100644--- a/packages/pumpfun-mcp/src/tools.js+++ b/packages/pumpfun-mcp/src/tools.js@@ -100,7 +100,6 @@ export const TOOL_ANNOTATIONS = Object.freeze({get_new_tokens: { title: 'New Tokens', ...LIVE_READ },get_graduated_tokens: { title: 'Graduated Tokens', ...LIVE_READ },get_king_of_the_hill: { title: 'King of the Hill', ...LIVE_READ },- kol_radar: { title: 'KOL Radar', ...LIVE_READ },get_creator_profile: { title: 'Creator Profile', ...LIVE_READ },get_token_holders: { title: 'Token Holders', ...LIVE_READ },pumpfun_vanity_mint: { title: 'Vanity Mint Keypair', ...LOCAL_GENERATIVE },@@ -227,22 +226,6 @@ export const FALLBACK_TOOLS = [description: 'Highest-market-cap token still on the bonding curve.',inputSchema: { type: 'object', properties: {} },},- {- name: 'kol_radar',- description:- 'gmgn radar signals: early-detection patterns filtered by category, sorted by score desc.',- inputSchema: {- type: 'object',- properties: {- category: {- type: 'string',- enum: ['pump-fun', 'new-mints', 'volume-spike'],- default: 'pump-fun',- },- limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 },- },- },- },{name: 'get_creator_profile',description: 'All tokens by a creator wallet, with rug-pull risk flags.',diff --git a/page-agent-sdk/src/narrator.js b/page-agent-sdk/src/narrator.jsindex 7c353b0e6..e7d0a7e37 100644--- a/page-agent-sdk/src/narrator.js+++ b/page-agent-sdk/src/narrator.js@@ -38,8 +38,9 @@ export class SpeechNarrator {this._voices = [];if (hasTTS) {+ this._onVoices = this._loadVoices.bind(this);this._loadVoices();- window.speechSynthesis.addEventListener?.('voiceschanged', this._loadVoices.bind(this));+ window.speechSynthesis.addEventListener?.('voiceschanged', this._onVoices);}}@@ -183,7 +184,7 @@ export class SpeechNarrator {dispose() {this.cancel();this._frameUnsub?.();- if (hasTTS) window.speechSynthesis.removeEventListener?.('voiceschanged', this._loadVoices);+ if (hasTTS) window.speechSynthesis.removeEventListener?.('voiceschanged', this._onVoices);}}diff --git a/page-agent-sdk/src/stage.js b/page-agent-sdk/src/stage.jsindex 75f2eb544..5eabaeeb0 100644--- a/page-agent-sdk/src/stage.js+++ b/page-agent-sdk/src/stage.js@@ -63,7 +63,8 @@ export class AvatarStage {this.renderer.toneMappingExposure = 1.05;const pmrem = new PMREMGenerator(this.renderer);- this.scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;+ this._envTex = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;+ this.scene.environment = this._envTex;pmrem.dispose();this.scene.add(new AmbientLight(0xffffff, 0.6));@@ -118,6 +119,7 @@ export class AvatarStage {this.scene.remove(this.model);this._disposeObject(this.model);}+ if (this.mixer) { this.mixer.stopAllAction(); this.mixer.uncacheRoot(this.model); }this.mixer = null;this._idleAction = null;this._talkAction = null;@@ -261,9 +263,12 @@ export class AvatarStage {_disposeObject(obj) {obj.traverse?.((n) => {n.geometry?.dispose?.();- const m = n.material;- if (Array.isArray(m)) m.forEach((x) => x?.dispose?.());- else m?.dispose?.();+ const mats = Array.isArray(n.material) ? n.material : [n.material];+ mats.forEach((m) => {+ if (!m) return;+ for (const v of Object.values(m)) if (v?.isTexture) v.dispose();+ m.dispose?.();+ });});}@@ -273,6 +278,8 @@ export class AvatarStage {this._resizeObs?.disconnect();this._frameHooks.clear();if (this.model) { this.scene.remove(this.model); this._disposeObject(this.model); }+ this._envTex?.dispose();+ this._envTex = null;this.renderer?.dispose();this.renderer?.forceContextLoss?.();this.renderer = null;diff --git a/pages/dad.html b/pages/dad.htmlnew file mode 100644index 000000000..1060bad21--- /dev/null+++ b/pages/dad.html@@ -0,0 +1,145 @@+<!doctype html>+<html lang="en">+ <head>+ <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.0" />+ <title>Make Dad a 3D Avatar · three.ws</title>+ <meta+ name="description"+ content="Turn one photo into a recognizable, rigged, animated 3D avatar of your dad — then share it. Built on three.ws."+ />+ <meta name="theme-color" content="#000000" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Make Dad a 3D Avatar" />+ <meta+ property="og:description"+ content="Upload one photo, get a recognizable 3D avatar of your dad that walks and waves. Happy Father's Day, from three.ws."+ />+ <meta property="og:url" content="https://three.ws/dad" />+ <meta property="og:image" content="https://three.ws/og-image.png" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" content="Make Dad a 3D Avatar · three.ws" />+ <meta name="twitter:description" content="One photo → a recognizable, animated 3D avatar of your dad. Happy Father's Day." />++ <link rel="canonical" href="https://three.ws/dad" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/mobile.css" />+ </head>+ <body>+ <header><div id="nav-container"></div></header>++ <main>+ <section class="dad" id="dad" data-stage="intro">+ <!-- ── Hero / intro ──────────────────────────────────────────── -->+ <div class="dad-hero" data-region="intro">+ <p class="dad-eyebrow">Father's Day · three.ws</p>+ <h1 class="dad-title">Make Dad a 3D avatar</h1>+ <p class="dad-sub">+ One clear photo becomes a recognizable, rigged 3D avatar — it idles,+ walks, and waves. Share it with the man himself.+ </p>++ <div+ class="dad-drop"+ id="dad-drop"+ role="button"+ tabindex="0"+ aria-label="Upload a photo of your dad. Drag and drop, or press Enter to browse."+ >+ <svg class="dad-drop-icon" viewBox="0 0 24 24" aria-hidden="true">+ <path d="M12 16V4m0 0L7 9m5-5 5 5" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>+ <path d="M4 16v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>+ </svg>+ <p class="dad-drop-strong">Drop a photo of your dad</p>+ <p class="dad-drop-hint">or <span class="dad-link">browse</span> · clear, front-facing works best</p>+ <input+ id="dad-file"+ class="dad-file"+ type="file"+ accept="image/*"+ hidden+ />+ </div>+ <p class="dad-fineprint">+ JPG, PNG, HEIC or WebP · large photos are optimized automatically · your photo is used only to build the avatar.+ </p>+ </div>++ <!-- ── Preprocess preview ────────────────────────────────────── -->+ <div class="dad-stage-box" data-region="preview" hidden>+ <h2 class="dad-h2">Looking good?</h2>+ <p class="dad-stage-help">We centered and cut out the background to get the best likeness. Use this, or pick another photo.</p>+ <div class="dad-preview-frame">+ <img id="dad-preview-img" class="dad-preview-img" alt="Cleaned-up photo of your dad, ready to turn into a 3D avatar" />+ </div>+ <div class="dad-actions">+ <button class="btn btn--primary dad-btn" id="dad-generate" type="button">Make the 3D avatar</button>+ <button class="btn btn--ghost dad-btn" id="dad-reset-1" type="button">Use a different photo</button>+ </div>+ </div>++ <!-- ── Generating ────────────────────────────────────────────── -->+ <div class="dad-stage-box" data-region="generating" hidden>+ <div class="dad-stage" aria-hidden="true">+ <div class="dad-skeleton"></div>+ </div>+ <h2 class="dad-h2">Sculpting your dad…</h2>+ <p class="dad-stage-help" id="dad-progress-text" role="status" aria-live="polite">Reconstructing geometry from the photo. This takes up to a minute.</p>+ <div class="dad-progress" role="progressbar" aria-label="Building avatar" aria-valuemin="0" aria-valuemax="100">+ <div class="dad-progress-bar" id="dad-progress-bar"></div>+ </div>+ </div>++ <!-- ── Result ────────────────────────────────────────────────── -->+ <div class="dad-stage-box dad-result" data-region="result" hidden>+ <div class="dad-viewer-wrap">+ <div id="dad-viewer" class="dad-viewer"></div>+ <div class="dad-viewer-toolbar">+ <button class="dad-chip is-active" id="dad-anim-idle" type="button" aria-pressed="true">Idle</button>+ <button class="dad-chip" id="dad-anim-walk" type="button" aria-pressed="false">Walk</button>+ <button class="dad-chip" id="dad-anim-wave" type="button" aria-pressed="false">Wave</button>+ </div>+ </div>+ <div class="dad-result-side">+ <h2 class="dad-h2">Here's your dad.</h2>+ <p class="dad-stage-help">Drag to spin him around. Happy Father's Day.</p>+ <div class="dad-actions dad-actions-col">+ <button class="btn btn--primary dad-btn" id="dad-share" type="button">Share this avatar</button>+ <a class="btn btn--ghost dad-btn" id="dad-download" download="dad-avatar.glb" href="#">Download GLB</a>+ <button class="btn btn--ghost dad-btn" id="dad-reset-2" type="button">Make another</button>+ </div>+ <p class="dad-share-copied" id="dad-share-copied" hidden>Link copied — paste it anywhere.</p>+ </div>+ </div>++ <!-- ── Error ─────────────────────────────────────────────────── -->+ <div class="dad-stage-box dad-error" data-region="error" hidden>+ <div class="dad-error-icon" aria-hidden="true">!</div>+ <h2 class="dad-h2" id="dad-error-title">That didn't work</h2>+ <p class="dad-stage-help" id="dad-error-msg">Something went wrong building the avatar.</p>+ <div class="dad-actions">+ <button class="btn btn--primary dad-btn" id="dad-retry" type="button">Try again</button>+ <button class="btn btn--ghost dad-btn" id="dad-reset-3" type="button">Use a different photo</button>+ </div>+ </div>+ </section>+ </main>++ <div id="footer-container"></div>++ <script src="/nav.js" defer></script>+ <script type="module" src="/src/dad/index.js"></script>+ <script src="/brand.js" defer></script>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/pages/economy.html b/pages/economy.htmlindex 93483e4a3..b40ad9c5b 100644--- a/pages/economy.html+++ b/pages/economy.html@@ -69,6 +69,23 @@.ae-section-head h2 { font-size: 19px; margin: 0; letter-spacing: -0.01em; }.ae-section-head a { font-size: 13px; color: var(--text-muted, #888); text-decoration: none; }.ae-section-head a:hover { color: var(--text, #e8e8e8); }+ .ae-head-tools { display: flex; align-items: center; gap: 14px; }+ .ae-sort select {+ font: inherit; font-size: 13px;+ background: var(--surface-1, #0a0a0a); color: var(--text, #e8e8e8);+ border: 1px solid var(--border-strong, #2a2a2a); border-radius: 10px;+ padding: 6px 10px; cursor: pointer;+ }+ .ae-sort select:focus-visible { outline: 2px solid var(--text, #fff); outline-offset: 2px; }+ .is-hidden-visually { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }+ .ae-live {+ display: inline-flex; align-items: center; gap: 7px;+ align-self: center; margin-left: auto;+ font-size: 12px; color: var(--text-muted, #888);+ border: 1px solid var(--border, #1a1a1a); border-radius: 999px; padding: 8px 14px;+ }+ .ae-live-dot { width: 8px; height: 8px; border-radius: 50%; background: #6ee7a8; box-shadow: 0 0 0 0 rgba(110, 231, 168, 0.6); animation: ae-pulse 2s ease-out infinite; }+ @keyframes ae-pulse { 0% { box-shadow: 0 0 0 0 rgba(110,231,168,0.5); } 70% { box-shadow: 0 0 0 7px rgba(110,231,168,0); } 100% { box-shadow: 0 0 0 0 rgba(110,231,168,0); } }.ae-muted { color: var(--text-muted, #888); }/* Agent grid */@@ -156,13 +173,24 @@<div class="ae-stat"><div class="ae-stat-num" id="ae-stat-agents">—</div><div class="ae-stat-label">Agents listed</div></div><div class="ae-stat"><div class="ae-stat-num" id="ae-stat-earning">—</div><div class="ae-stat-label">With paying buyers</div></div><div class="ae-stat"><div class="ae-stat-num" id="ae-stat-services">—</div><div class="ae-stat-label">Live x402 services</div></div>+ <div class="ae-live" id="ae-live" hidden><span class="ae-live-dot" aria-hidden="true"></span><span id="ae-live-label">Live</span></div></div></header><section class="ae-section"><div class="ae-section-head"><h2>Agents earning on three.ws</h2>- <a href="/marketplace">Open marketplace →</a>+ <div class="ae-head-tools">+ <label class="ae-sort">+ <span class="is-hidden-visually">Sort agents</span>+ <select id="ae-sort" aria-label="Sort agents">+ <option value="top_rated">Top rated</option>+ <option value="popular">Most popular</option>+ <option value="recent">Newest</option>+ </select>+ </label>+ <a href="/marketplace">Open marketplace →</a>+ </div></div><div class="ae-grid" id="ae-agents"></div></section>diff --git a/pages/hero-demo.html b/pages/hero-demo.htmlindex 5f0dc56ac..fe985e64f 100644--- a/pages/hero-demo.html+++ b/pages/hero-demo.html@@ -456,6 +456,7 @@}function loadAvatar(glb) {+ clearTimeout(revealTimer); // drop any pending reveal from a prior loadsubject.querySelector('.subject-error')?.remove();if (agentEl) agentEl.remove();showSkeleton();diff --git a/pages/home.html b/pages/home.htmlindex 8ad7986c4..9f3420d22 100644--- a/pages/home.html+++ b/pages/home.html@@ -3944,7 +3944,7 @@const io = new IntersectionObserver((entries) => {if (entries[0].isIntersecting) { io.disconnect(); init(); }}, { rootMargin: '200px' });- io.observe(section);+ if (section) io.observe(section);})();</script>diff --git a/pages/profile.html b/pages/profile.htmlindex 67c375d71..73c29b95b 100644--- a/pages/profile.html+++ b/pages/profile.html@@ -991,6 +991,7 @@}.up-nft-media img, .up-nft-media model-viewer {width: 100%; height: 100%; object-fit: cover; background: transparent;+ --poster-color: transparent;}.up-nft-badge {position: absolute;@@ -1377,7 +1378,12 @@c],);- const attr = (s) => esc(s).replace(/"/g, '"');+ const attr = (s) =>+ String(s ?? '').replace(+ /[&<>"']/g,+ (c) =>+ ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );const segments = location.pathname.split('/').filter(Boolean);const slug = segments[1]; // /u/<slug>@@ -1627,10 +1633,10 @@if (e.target === modal) close();});modal.querySelector('#up-pay-close').addEventListener('click', close);- document.addEventListener('keydown', function esc(e) {+ document.addEventListener('keydown', function onPayEscKey(e) {if (e.key === 'Escape') {close();- document.removeEventListener('keydown', esc);+ document.removeEventListener('keydown', onPayEscKey);}});@@ -1944,7 +1950,7 @@// Lazy-load on-chain collectibles (NFTs, accessories, wallets). Kept// out of the main payload because the NFT providers are slow + billed;// the profile paints first, these fill in after.- loadCollectibles(rootEl, user, tabBarEl);+ loadCollectibles(rootEl, user, tabBarEl, activateTab);// Follow / unfollowconst followBtn = rootEl.querySelector('#up-follow-btn');@@ -2017,13 +2023,14 @@];const body = fields.map((f) => {+ const inputId = `up-edit-${attr(f.key)}`;const counter = f.max- ? `<span class="up-field-count" data-count-for="${f.key}">${(f.value || '').length}/${f.max}</span>`+ ? `<span class="up-field-count" data-count-for="${attr(f.key)}">${(f.value || '').length}/${f.max}</span>`: '';const input = f.textarea- ? `<textarea name="${f.key}" maxlength="${f.max}" placeholder="${attr(f.placeholder || '')}">${esc(f.value)}</textarea>`- : `<input name="${f.key}" type="text" maxlength="${f.max}" value="${attr(f.value)}" placeholder="${attr(f.placeholder || '')}">`;- return `<div class="up-field"><label>${esc(f.label)}${counter}</label>${input}</div>`;+ ? `<textarea id="${inputId}" name="${attr(f.key)}" maxlength="${f.max}" placeholder="${attr(f.placeholder || '')}">${esc(f.value)}</textarea>`+ : `<input id="${inputId}" name="${attr(f.key)}" type="text" maxlength="${f.max}" value="${attr(f.value)}" placeholder="${attr(f.placeholder || '')}">`;+ return `<div class="up-field"><label for="${inputId}">${esc(f.label)}${counter}</label>${input}</div>`;}).join('');@@ -2096,6 +2103,7 @@`/api/users/${encodeURIComponent(username)}/follows?type=${type}&limit=100`,{ credentials: 'include' },);+ if (!r.ok) throw new Error(`HTTP ${r.status}`);const j = await r.json();const users = j.users || [];if (!users.length) {@@ -2160,10 +2168,11 @@backdrop.id = 'up-modal-backdrop';backdrop.setAttribute('role', 'dialog');backdrop.setAttribute('aria-modal', 'true');+ backdrop.setAttribute('aria-labelledby', 'up-modal-title');backdrop.innerHTML = `<div class="up-modal"><div class="up-modal-head">- <h3>${esc(title)}</h3>+ <h3 id="up-modal-title">${esc(title)}</h3><button class="up-modal-close" aria-label="Close" data-close>×</button></div><div class="up-modal-body">${innerHtml}</div>@@ -2210,7 +2219,7 @@// Fetches /api/users/:username/collectibles after the main paint and// fills the Wallets row + NFT/Accessories tabs. Failure is silent — the// surfaces just stay absent rather than showing a broken state.- async function loadCollectibles(rootEl, user, tabBarEl) {+ async function loadCollectibles(rootEl, user, tabBarEl, activateTab) {let data;try {const r = await fetch(@@ -2251,17 +2260,23 @@});}- // NFTs + Accessories tabs are revealed only when non-empty.+ // NFTs + Accessories tabs are revealed only when non-empty. If the+ // user has no content in the main tabs (no active tab yet), auto-activate+ // the first deferred tab so the content isn't stuck behind a hidden section.+ const hadActiveTab = Boolean(tabBarEl?.querySelector('.up-tab--active'));if (nfts.length) {rootEl.querySelector('#up-nfts-body').innerHTML = renderNftGrid(nfts);addDeferredTab(tabBarEl, 'nfts', 'Collectibles', nfts.length);addStat(rootEl, 'NFTs', nfts.length);+ if (!hadActiveTab && activateTab) activateTab('nfts');}if (accessories.length) {rootEl.querySelector('#up-accessories-body').innerHTML =renderAccessoriesGrid(accessories);addDeferredTab(tabBarEl, 'accessories', 'Accessories', accessories.length);addStat(rootEl, 'Accessories', accessories.length);+ // Only auto-activate accessories if NFTs didn't already take the active slot.+ if (!hadActiveTab && !nfts.length && activateTab) activateTab('accessories');}}@@ -2276,7 +2291,23 @@btn.setAttribute('aria-selected', 'false');btn.innerHTML = `${esc(label)} <span class="up-tab-badge">${count}</span>`;tabBarEl.appendChild(btn);- if (tabBarEl.querySelectorAll('.up-tab').length > 1) tabBarEl.hidden = false;+ // Reveal the bar whenever at least one tab exists. The >= 1 threshold+ // handles profiles with no static tabs (no avatars/agents/etc.) that+ // still have on-chain collectibles — without this they get a hidden bar+ // and an unreachable NFT section.+ if (tabBarEl.querySelectorAll('.up-tab').length >= 1) tabBarEl.hidden = false;+ // If this is the ONLY tab in the bar, auto-activate it so the section+ // it points to is shown instead of the default "No avatars" empty state.+ if (tabBarEl.querySelectorAll('.up-tab').length === 1) {+ btn.classList.add('up-tab--active');+ btn.setAttribute('aria-selected', 'true');+ const profileRoot = tabBarEl.closest('#profile-root');+ if (profileRoot) {+ profileRoot.querySelectorAll('.up-section').forEach((s) => {+ s.hidden = s.dataset.section !== key;+ });+ }+ }}// Append a read-only stat tile to the strip.@@ -2659,7 +2690,7 @@const url = location.href;const title = document.title.replace(/ — three\.ws$/, '');const xText = `${title} on three.ws`;- const xUrl = `https://twitter.com/intent/tweet?text=${encodeURIComponent(xText)}&url=${encodeURIComponent(url)}`;+ const xUrl = `https://x.com/intent/tweet?text=${encodeURIComponent(xText)}&url=${encodeURIComponent(url)}`;const canNativeShare = typeof navigator.share === 'function';shareMenu.innerHTML = `${diff --git a/pages/three-live.html b/pages/three-live.htmlindex 16dc55fba..c57ad98f9 100644--- a/pages/three-live.html+++ b/pages/three-live.html@@ -263,6 +263,7 @@const STATS_API = '/api/three-token/stats';const TRADES_SSE = `/api/agents/pumpfun-feed?kind=trades&mint=${THREE_MINT}`;const STATS_INTERVAL_MS = 8_000;+ let _solUsd = 0; // refreshed from Jupiter on bootconst FLOW_WINDOW_MS = 60_000;const WHALE_USD = 2_000; // a trade this big sends a shockwaveconst PARTICLE_POOL = 1400; // hard cap on live particles@@ -496,6 +497,7 @@}// momentary core kick + heartbeat feedcoreUniforms.uPulse.value = Math.min(1.2, coreUniforms.uPulse.value + 0.25 + mag * 0.6);+ pGeo.attributes.color.needsUpdate = true;if (value >= WHALE_USD) spawnShockwave(baseColor);}@@ -603,7 +605,7 @@es.addEventListener('trade', (ev) => {let d; try { d = JSON.parse(ev.data); } catch { return; }const isBuy = d.is_buy === true || d.txType === 'buy' || d.tx_type === 'buy';- const usd = Number(d.sol_value_usd) || (Number(d.sol_amount ?? d.solAmount) || 0) * 150; // sol fallback+ const usd = Number(d.sol_value_usd) || (Number(d.sol_amount ?? d.solAmount) || 0) * _solUsd;const now = performance.now();lastTradeAt = now;recentTrades.push({ t: now, isBuy, usd });@@ -663,9 +665,10 @@const baseSz = pSize[i];pGeo.attributes.psize.array[i] = baseSz * (0.3 + f * 0.7);}- pGeo.attributes.position.needsUpdate = true;- pGeo.attributes.color.needsUpdate = true;- pGeo.attributes.psize.needsUpdate = true;+ if (anyAlive) {+ pGeo.attributes.position.needsUpdate = true;+ pGeo.attributes.psize.needsUpdate = true;+ }// shockwavesfor (let i = shockwaves.length - 1; i >= 0; i--) {@@ -702,6 +705,11 @@// ── Boot ──────────────────────────────────────────────────────────────────setHero('connecting', '$THREE · connecting…');+ // Seed the SOL price used for trades that only supply sol_amount.+ fetch('https://api.jup.ag/price/v2?ids=So11111111111111111111111111111111111111112', { signal: AbortSignal.timeout(5000) })+ .then((r) => r.ok ? r.json() : null)+ .then((d) => { const p = Number(d?.data?.So11111111111111111111111111111111111111112?.price); if (p > 0) _solUsd = p; })+ .catch(() => {});pollStats().finally(() => { setTimeout(() => introEl.classList.add('is-hidden'), 350); });statsTimer = setInterval(pollStats, STATS_INTERVAL_MS);connectTrades();diff --git a/public/brain-studio.css b/public/brain-studio.cssindex e8b432030..b2df6ae70 100644--- a/public/brain-studio.css+++ b/public/brain-studio.css@@ -197,6 +197,22 @@ textarea.brainstudio__input { resize: vertical; }.diff-del { color: var(--node-output); text-decoration: line-through; opacity: .8; }.diff-muted { color: var(--ink-faint); }+/* ── Footer: save state + continue ─────────────────────────────────────── */+.brainstudio__footer {+ display: flex; align-items: center; justify-content: flex-end; gap: var(--space-md);+ padding: var(--space-xs) var(--space-sm);+ border-top: 1px solid var(--surface-2);+ background: var(--bg-1);+}+.brainstudio__footer-save {+ font-size: var(--text-sm); color: var(--ink-faint);+ transition: color .2s;+}+.brainstudio__footer-save[data-state="saving"] { color: var(--warn, #fbbf24); }+.brainstudio__footer-save[data-state="saved"] { color: var(--node-market); }+.brainstudio__footer-save[data-state="error"] { color: var(--node-output); }+.brainstudio__footer-continue { padding: 8px 20px; }+/* ── Responsive ─────────────────────────────────────────────────────────── */@media (max-width: 1024px) {.brainstudio__main { grid-template-columns: 1fr; grid-template-rows: minmax(260px, 1fr) auto; }diff --git a/public/memory-studio.css b/public/memory-studio.cssindex c8a7bdb3c..2a2066aa0 100644--- a/public/memory-studio.css+++ b/public/memory-studio.css@@ -194,7 +194,7 @@}.mem-edit-content, .mem-composer-content { resize: vertical; width: 100%; box-sizing: border-box; }.mem-edit-content:focus, .mem-edit-tags:focus, .mem-composer-content:focus, .mem-composer-tags:focus { border-color: var(--mem-working); }-.mem-edit-tools, .mem-composer-tools, .mem-edit-tools { display: flex; gap: 8px; }+.mem-edit-tools, .mem-composer-tools { display: flex; gap: 8px; }/* ── Empty / first-run ───────────────────────────────────────────────────── */.mem-empty, .mem-first { text-align: center; max-width: 460px; margin: clamp(20px, 6vh, 60px) auto; color: var(--ink-dim, #888); }diff --git a/solana-agent-sdk/src/actions/ata.ts b/solana-agent-sdk/src/actions/ata.tsindex 97b7d6aae..f9198bf31 100644--- a/solana-agent-sdk/src/actions/ata.ts+++ b/solana-agent-sdk/src/actions/ata.ts@@ -5,11 +5,11 @@ import {import {getAssociatedTokenAddressSync,createAssociatedTokenAccountInstruction,- TOKEN_PROGRAM_ID,ASSOCIATED_TOKEN_PROGRAM_ID,} from "@solana/spl-token";import type { WalletProvider } from "../wallet/types.js";import { buildAndSend, type BuildAndSendOptions } from "../tx/build.js";+import { resolveTokenProgramId } from "../utils/token-program.js";export interface GetOrCreateAtaParams {mint: PublicKey | string;@@ -35,11 +35,15 @@ export async function getOrCreateAta(: params.owner: wallet.publicKey;+ // Classic SPL vs Token-2022, resolved from the mint owner — a hardcoded+ // classic program derives the wrong ATA for Token-2022 mints (e.g. $THREE).+ const tokenProgramId = await resolveTokenProgramId(connection, mint);+const ata = getAssociatedTokenAddressSync(mint,owner,false,- TOKEN_PROGRAM_ID,+ tokenProgramId,ASSOCIATED_TOKEN_PROGRAM_ID,);@@ -51,7 +55,7 @@ export async function getOrCreateAta(ata,owner,mint,- TOKEN_PROGRAM_ID,+ tokenProgramId,ASSOCIATED_TOKEN_PROGRAM_ID,);diff --git a/solana-agent-sdk/src/actions/stake.ts b/solana-agent-sdk/src/actions/stake.tsindex e9c77fbb3..1b57d86a4 100644--- a/solana-agent-sdk/src/actions/stake.ts+++ b/solana-agent-sdk/src/actions/stake.ts@@ -113,8 +113,10 @@ export async function stakeSOL(if (!isExpired || attempt === maxRetries - 1) throw err;- const slot = await connection.getSlot();- if (slot > lastValidBlockHeight) continue;+ // Compare block HEIGHT to lastValidBlockHeight — not getSlot(), whose slot+ // counter runs ahead of block height (skipped slots) and isn't comparable.+ const blockHeight = await connection.getBlockHeight();+ if (blockHeight > lastValidBlockHeight) continue;throw err;}}diff --git a/solana-agent-sdk/src/actions/transfer-spl.ts b/solana-agent-sdk/src/actions/transfer-spl.tsindex 2f7ea6476..172018426 100644--- a/solana-agent-sdk/src/actions/transfer-spl.ts+++ b/solana-agent-sdk/src/actions/transfer-spl.ts@@ -8,13 +8,13 @@ import {createAssociatedTokenAccountInstruction,createTransferCheckedInstruction,getMint,- TOKEN_PROGRAM_ID,ASSOCIATED_TOKEN_PROGRAM_ID,} from "@solana/spl-token";import type { WalletProvider } from "../wallet/types.js";import { buildAndSend, type BuildAndSendOptions } from "../tx/build.js";import { MissingTokenAccountError } from "../errors.js";import { toUiAmount } from "../utils/format.js";+import { resolveTokenProgramId } from "../utils/token-program.js";export interface TransferSplParams {mint: PublicKey | string;@@ -35,11 +35,15 @@ export async function transferSpl(const mint = typeof params.mint === "string" ? new PublicKey(params.mint) : params.mint;const to = typeof params.to === "string" ? new PublicKey(params.to) : params.to;- const mintInfo = await getMint(connection, mint);+ // Resolve classic SPL vs Token-2022 from the mint owner so $THREE and other+ // Token-2022 mints get the correct ATA derivation and program — not the+ // classic-only default, which derives the wrong address and fails.+ const tokenProgramId = await resolveTokenProgramId(connection, mint);+ const mintInfo = await getMint(connection, mint, undefined, tokenProgramId);const instructions: TransactionInstruction[] = [];- const senderAta = getAssociatedTokenAddressSync(mint, wallet.publicKey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);- const receiverAta = getAssociatedTokenAddressSync(mint, to, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);+ const senderAta = getAssociatedTokenAddressSync(mint, wallet.publicKey, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID);+ const receiverAta = getAssociatedTokenAddressSync(mint, to, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID);const senderInfo = await connection.getAccountInfo(senderAta);if (!senderInfo) {@@ -51,7 +55,7 @@ export async function transferSpl(instructions.push(createAssociatedTokenAccountInstruction(wallet.publicKey, receiverAta, to, mint,- TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID,),);}@@ -59,7 +63,7 @@ export async function transferSpl(instructions.push(createTransferCheckedInstruction(senderAta, mint, receiverAta, wallet.publicKey,- params.amount, mintInfo.decimals, [], TOKEN_PROGRAM_ID,+ params.amount, mintInfo.decimals, [], tokenProgramId,),);diff --git a/solana-agent-sdk/src/tx/build.ts b/solana-agent-sdk/src/tx/build.tsindex 5bc43680d..146b84dad 100644--- a/solana-agent-sdk/src/tx/build.ts+++ b/solana-agent-sdk/src/tx/build.ts@@ -103,8 +103,8 @@ export async function buildAndSend(if (!isExpired || attempt === maxRetries - 1) throw err;- const slot = await connection.getSlot();- if (slot > lastValidBlockHeight) continue;+ const blockHeight = await connection.getBlockHeight();+ if (blockHeight > lastValidBlockHeight) continue;throw err;}}diff --git a/solana-agent-sdk/src/utils/token-program.ts b/solana-agent-sdk/src/utils/token-program.tsnew file mode 100644index 000000000..e546ffa65--- /dev/null+++ b/solana-agent-sdk/src/utils/token-program.ts@@ -0,0 +1,26 @@+import { PublicKey, type Connection } from "@solana/web3.js";+import { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID } from "@solana/spl-token";++/**+ * Resolve which SPL token program owns a mint — classic SPL Token vs Token-2022.+ *+ * Any helper hardcoded to TOKEN_PROGRAM_ID derives the wrong associated-token+ * address and builds against the wrong program for a Token-2022 mint, so the+ * transfer fails (or a balance lookup misses) for tokens that genuinely exist in+ * the wallet — including $THREE, which is a Token-2022 mint. The mint account's+ * owner is the canonical, on-chain way to tell the two programs apart.+ *+ * @throws if the mint account doesn't exist or isn't owned by either SPL program.+ */+export async function resolveTokenProgramId(+ connection: Connection,+ mint: PublicKey,+): Promise<PublicKey> {+ const info = await connection.getAccountInfo(mint);+ if (!info) throw new Error(`Mint not found: ${mint.toBase58()}`);+ if (info.owner.equals(TOKEN_2022_PROGRAM_ID)) return TOKEN_2022_PROGRAM_ID;+ if (info.owner.equals(TOKEN_PROGRAM_ID)) return TOKEN_PROGRAM_ID;+ throw new Error(+ `Not an SPL token mint (owner ${info.owner.toBase58()}): ${mint.toBase58()}`,+ );+}diff --git a/solana-agent-sdk/tests/actions/transfer-spl.test.ts b/solana-agent-sdk/tests/actions/transfer-spl.test.tsindex 7a328a042..2ac8960dc 100644--- a/solana-agent-sdk/tests/actions/transfer-spl.test.ts+++ b/solana-agent-sdk/tests/actions/transfer-spl.test.ts@@ -17,7 +17,7 @@ jest.unstable_mockModule("@solana/spl-token", () => {const { transferSpl } = await import("../../src/actions/transfer-spl.js");const { Keypair } = await import("@solana/web3.js") as typeof import("@solana/web3.js");-const { getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID } =+const { getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID } =await import("@solana/spl-token") as typeof import("@solana/spl-token");const WALLET_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(1)).publicKey;@@ -37,11 +37,21 @@ const MINT_INFO = {decimals: 6, mintAuthority: null, supply: 0n, freezeAuthority: null, isInitialized: true,};-function makeConnection(senderExists: boolean, receiverExists: boolean) {+function makeConnection(+ senderExists: boolean,+ receiverExists: boolean,+ mintProgram: PublicKey = TOKEN_PROGRAM_ID,+) {+ // ATAs are derived with whichever program owns the mint, so a Token-2022 test+ // must look its accounts up under the Token-2022 program.+ const senderAta = getAssociatedTokenAddressSync(MINT_PUBKEY, WALLET_PUBKEY, false, mintProgram, ASSOCIATED_TOKEN_PROGRAM_ID);+ const receiverAta = getAssociatedTokenAddressSync(MINT_PUBKEY, RECIPIENT_PUBKEY, false, mintProgram, ASSOCIATED_TOKEN_PROGRAM_ID);const getAccountInfo = jest.fn<(pubkey: PublicKey) => Promise<AccountInfo<Buffer> | null>>();getAccountInfo.mockImplementation(async (pubkey) => {- if (pubkey.equals(SENDER_ATA)) return senderExists ? (FAKE_ACCOUNT as unknown as AccountInfo<Buffer>) : null;- if (pubkey.equals(RECEIVER_ATA)) return receiverExists ? (FAKE_ACCOUNT as unknown as AccountInfo<Buffer>) : null;+ // resolveTokenProgramId reads the mint account's owner to pick the program.+ if (pubkey.equals(MINT_PUBKEY)) return ({ ...FAKE_ACCOUNT, owner: mintProgram } as unknown as AccountInfo<Buffer>);+ if (pubkey.equals(senderAta)) return senderExists ? (FAKE_ACCOUNT as unknown as AccountInfo<Buffer>) : null;+ if (pubkey.equals(receiverAta)) return receiverExists ? (FAKE_ACCOUNT as unknown as AccountInfo<Buffer>) : null;return null;});return { getAccountInfo } as unknown as Connection;@@ -121,4 +131,21 @@ describe("transferSpl", () => {const [, , , opts] = mockBuildAndSendFn.mock.calls[0]!;expect(opts?.meta?.amountIn?.uiAmount).toBe("1.5");});++ it("uses the Token-2022 program for a Token-2022 mint (e.g. $THREE)", async () => {+ // Mint account owned by Token-2022 → ATAs and the transfer must build against+ // Token-2022, not the classic program (which would derive the wrong ATA).+ await transferSpl(makeWallet(), makeConnection(true, true, TOKEN_2022_PROGRAM_ID), {+ mint: MINT_PUBKEY, to: RECIPIENT_PUBKEY, amount: 1_000_000n,+ });++ const [, , instructions] = mockBuildAndSendFn.mock.calls[0]!;+ const transferIx = instructions[instructions.length - 1]!;+ expect(transferIx.programId.equals(TOKEN_2022_PROGRAM_ID)).toBe(true);+ // And the source ATA is the Token-2022-derived address, not the classic one.+ const expectedSenderAta = getAssociatedTokenAddressSync(+ MINT_PUBKEY, WALLET_PUBKEY, false, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ );+ expect(transferIx.keys[0]!.pubkey.equals(expectedSenderAta)).toBe(true);+ });});diff --git a/src/agent-avatar.js b/src/agent-avatar.jsindex 78a26f0b7..5bc6d00d6 100644--- a/src/agent-avatar.js+++ b/src/agent-avatar.js@@ -259,7 +259,7 @@ export class AgentAvatar {// First-encounter curiosity burstif (this._firstEncounter) {this._firstEncounter = false;- setTimeout(() => {+ this._firstEncounterTimer = setTimeout(() => {this._injectStimulus('curiosity', 0.9);this._injectStimulus('celebration', 0.4);}, 600);@@ -299,6 +299,8 @@ export class AgentAvatar {/** Remove all hooks and listeners */detach() {+ clearTimeout(this._firstEncounterTimer);+ clearTimeout(this._playAmClipTimer);if (this.viewer._afterAnimateHooks) {const idx = this.viewer._afterAnimateHooks.indexOf(this._tickBound);if (idx !== -1) this.viewer._afterAnimateHooks.splice(idx, 1);@@ -455,7 +457,7 @@ export class AgentAvatar {const prev = prevName ?? am.currentName;am.play(clipName);if (prev && am.isLoaded(prev)) {- setTimeout(() => am.crossfadeTo(prev, 0.4), duration * 1000);+ this._playAmClipTimer = setTimeout(() => am.crossfadeTo(prev, 0.4), duration * 1000);}}diff --git a/src/agent-detail.js b/src/agent-detail.jsindex de28c1d82..43c636ed4 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -8,22 +8,6 @@* the requester is the agent's owner — render() tolerates them being absent.*/-import {- Connection,- PublicKey,- Transaction,- SystemProgram,- LAMPORTS_PER_SOL,- clusterApiUrl,-} from '@solana/web3.js';-const solanaWeb3 = {- Connection,- PublicKey,- Transaction,- SystemProgram,- LAMPORTS_PER_SOL,- clusterApiUrl,-};import { onchainBadgeEl } from './shared/onchain-badge.js';import { walletChipEl } from './shared/agent-wallet-chip.js';import { mountValidationBadge } from './shared/validation-badge.js';@@ -1478,7 +1462,7 @@ function renderReputation(r) {? Number(r.average).toFixed(2): '0.00';document.getElementById('ad-rep-count').textContent = String(r.count || 0);- if (r.total_stake_wei && r.total_stake_wei !== '0') {+ if (r.total_stake_wei && r.total_stake_wei !== '0' && /^\d+$/.test(r.total_stake_wei)) {document.getElementById('ad-rep-stake-row').style.display = '';const wei = BigInt(r.total_stake_wei);const eth = Number(wei) / 1e18;@@ -2083,42 +2067,6 @@ async function loadAgent(id) {return { agent: normalize(rec, avatar), error: null };}-// --- Wallet Integration -----const getProvider = () => {- if ('phantom' in window) {- const provider = window.phantom?.solana;- if (provider?.isPhantom) {- return provider;- }- }- window.open('https://phantom.app/', '_blank');- return null;-};--let wallet = null;-// Route through our same-origin proxy. Public devnet RPC is also rate-limited-// from browsers; the proxy keeps both clusters consistent.-const _rpcOrigin = window.location?.origin || 'https://three.ws';-const connection = new solanaWeb3.Connection(- `${_rpcOrigin}/api/solana-rpc?net=devnet`,- 'confirmed',-);-const connectWalletBtn = document.getElementById('connect-wallet-btn');--connectWalletBtn.addEventListener('click', async () => {- const provider = getProvider();- if (provider) {- try {- const resp = await provider.connect();- wallet = resp.publicKey;-- connectWalletBtn.textContent = `${wallet.toString().slice(0, 4)}...${wallet.toString().slice(-4)}`;- } catch (err) {- log.error('Failed to connect to wallet:', err);- }- }-});const id =new URLSearchParams(location.search).get('id') ||diff --git a/src/agent-exchange.js b/src/agent-exchange.jsindex 11af7d48c..e9778baed 100644--- a/src/agent-exchange.js+++ b/src/agent-exchange.js@@ -400,7 +400,7 @@ async function doPurchase() {sayA(LINES.A.settled);} else if (event === 'result') {// result carries { ok, tool, args, result: <intelObj>, payment: <paymentObj>, durations }- intel = data.result ?? data;+ if (data.result != null) intel = data.result;if (data.payment) settled = { ...settled, ...data.payment };} else if (event === 'error') {errored = true;@@ -409,7 +409,7 @@ async function doPurchase() {}}- if (!intel || !settled) throw new Error('incomplete response from payment service');+ if (!intel?.signal || !settled) throw new Error('incomplete response from payment service');// ── Success choreography ──────────────────────────────setStage('done', 'done', 'confirmed');diff --git a/src/agent-skills-pumpfun.js b/src/agent-skills-pumpfun.jsindex 969fa735c..15d61bb33 100644--- a/src/agent-skills-pumpfun.js+++ b/src/agent-skills-pumpfun.js@@ -24,7 +24,6 @@ import { quoteSwap } from './pump/pump-swap-quote.js';import { fetchChannelFeed } from './pump/channel-feed.js';import { listRecentClaims } from './pump/pumpkit-claims.js';import { getWalletPnl } from './kol/wallet-pnl.js';-import { getRadarSignals } from './kol/radar.js';import { resolveSnsName, reverseLookupAddress } from './solana/sns.js';import { correlateXPost } from './social/x-post-impact.js';@@ -948,47 +947,6 @@ export function registerPumpFunSkills(skills) {},});- // ── kol.radar ─────────────────────────────────────────────────────────────- skills.register({- name: 'kol.radar',- description:- 'Return gmgn radar signals: early-detection patterns by category, sorted by score.',- instruction: 'Read-only. Returns fixture data from src/kol/radar-fixture.json.',- animationHint: 'inspect',- voicePattern: 'Checking radar for {{category}} signals…',- mcpExposed: true,- inputSchema: {- type: 'object',- properties: {- category: {- type: 'string',- enum: ['pump-fun', 'new-mints', 'volume-spike'],- default: 'pump-fun',- description: 'Signal category to filter by',- },- limit: {- type: 'integer',- minimum: 1,- maximum: 100,- default: 20,- description: 'Max results (capped at 100)',- },- },- },- handler: async (args, _ctx) => {- const signals = await getRadarSignals({- category: args.category ?? 'pump-fun',- limit: args.limit ?? 20,- });- return {- success: true,- output: `Found ${signals.length} radar signal(s) for "${args.category ?? 'pump-fun'}".`,- sentiment: signals.length > 0 ? 0.6 : 0.1,- data: { signals, category: args.category ?? 'pump-fun', count: signals.length },- };- },- });-// ── pumpfun-accept-payment ────────────────────────────────────────────────skills.register({name: 'pumpfun-accept-payment',@@ -1029,7 +987,7 @@ export function registerPumpFunSkills(skills) {const agentMint = new web3.PublicKey(args.agentMint);const currencyMint = new web3.PublicKey(args.currencyMint);- const env = network === 'devnet' ? 'devnet' : 'mainnet-beta';+ const env = network === 'devnet' ? 'devnet' : 'mainnet';const agent = new pay.PumpAgent(agentMint, env, connection);const now = Math.floor(Date.now() / 1000);diff --git a/src/agent-trade.js b/src/agent-trade.jsindex 7b6468228..2a96ea32a 100644--- a/src/agent-trade.js+++ b/src/agent-trade.js@@ -329,6 +329,17 @@ function updateOverlays() {}}+// ── HTML escaping ────────────────────────────────────────────────────────────+function escHtml(s) {+ return String(s == null ? '' : s)+ .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')+ .replace(/"/g, '"').replace(/'/g, ''');+}+function safeHref(u) {+ const s = String(u || '').trim();+ return /^https?:\/\//i.test(s) ? s : '#';+}+// ── Bubble helpers ──────────────────────────────────────────────────────────function showBubble(side, text) {const el = side === 'buyer' ? els.buyerBubble : els.sellerBubble;@@ -440,11 +451,11 @@ function handleEvent(ev) {showCard(`<div class="c-badge c-badge-402">⟶ 402 Payment Required</div><div class="c-label">x402 Protocol · oracle-market-analysis</div>- <div class="c-price blue">${price.sol ?? '?'} SOL${usdStr}</div>- <div class="c-row">Recipient <span>${fmt(m.recipient)}</span></div>- <div class="c-row">Network <span>${m.network || '—'}</span></div>- <div class="c-row">Memo <span>${m.memo || '—'}</span></div>- <div class="c-row">Currency <span>${m.currency || 'SOL'}</span></div>+ <div class="c-price blue">${escHtml(price.sol ?? '?')} SOL${escHtml(usdStr)}</div>+ <div class="c-row">Recipient <span>${escHtml(fmt(m.recipient))}</span></div>+ <div class="c-row">Network <span>${escHtml(m.network || '—')}</span></div>+ <div class="c-row">Memo <span>${escHtml(m.memo || '—')}</span></div>+ <div class="c-row">Currency <span>${escHtml(m.currency || 'SOL')}</span></div>`);setTimeout(() => setChip('challenged', 'done'), 700);break;@@ -475,11 +486,11 @@ function handleEvent(ev) {const usdStr = ev.usd != null ? ` ≈ $${ev.usd}` : '';showCard(`<div class="c-badge c-badge-ok">✓ Transaction Confirmed</div>- <div class="c-label">On-Chain · ${ev.sol} SOL${usdStr}</div>- <div class="c-price green">${ev.sol} SOL</div>- <div class="c-row">Signature <span>${sigShort}</span></div>- <div class="c-row">Network <span>${ev.network || 'solana'}</span></div>- ${ev.explorer ? `<a class="c-link" href="${ev.explorer}" target="_blank" rel="noopener">View on Solscan →</a>` : ''}+ <div class="c-label">On-Chain · ${escHtml(ev.sol)} SOL${escHtml(usdStr)}</div>+ <div class="c-price green">${escHtml(ev.sol)} SOL</div>+ <div class="c-row">Signature <span>${escHtml(sigShort)}</span></div>+ <div class="c-row">Network <span>${escHtml(ev.network || 'solana')}</span></div>+ ${ev.explorer ? `<a class="c-link" href="${escHtml(safeHref(ev.explorer))}" target="_blank" rel="noopener">View on Solscan →</a>` : ''}`);setTimeout(() => setChip('confirmed', 'done'), 800);break;@@ -504,11 +515,11 @@ function handleEvent(ev) {controls.autoRotate = true;showCard(`<div class="c-badge c-badge-ok">✓ Skill Delivered</div>- <div class="c-label">${ev.provider || 'AI'} · ${ev.topic || ''}</div>- <div class="c-content">${ev.content || ''}</div>+ <div class="c-label">${escHtml(ev.provider || 'AI')} · ${escHtml(ev.topic || '')}</div>+ <div class="c-content">${escHtml(ev.content || '')}</div><div class="c-powered">- Powered by ${ev.model || ev.provider || ''}- ${ev.explorer ? ` · <a class="c-link" style="display:inline" href="${ev.explorer}" target="_blank" rel="noopener">tx →</a>` : ''}+ Powered by ${escHtml(ev.model || ev.provider || '')}+ ${ev.explorer ? ` · <a class="c-link" style="display:inline" href="${escHtml(safeHref(ev.explorer))}" target="_blank" rel="noopener">tx →</a>` : ''}</div>`);setRunning(false);diff --git a/src/animation-manager.js b/src/animation-manager.jsindex 47c5ac347..441f3058b 100644--- a/src/animation-manager.js+++ b/src/animation-manager.js@@ -12,6 +12,7 @@ import { canonicalizeBoneName } from './glb-canonicalize.js';import {canonicalNodeMapFromObject,canonicalRestMapFromObject,+ canonicalWorldRestMapFromObject,clipHipBaselineY,hipRestLocalHeight,hipsParentWorldQuat,@@ -153,6 +154,8 @@ export class AnimationManager {this._overlayClips = new Map();/** @type {Function|null} mixer 'finished' listener for the current one-shot overlay. */this._overlayFinishHandler = null;+ /** @type {Function|null} mixer 'finished' listener for the settle-to-idle after a playOnce. */+ this._settleFinishHandler = null;}/**@@ -190,6 +193,12 @@ export class AnimationManager {// (a Mixamo rig bakes the up-axis as a −90°X Hips rest the clips would// otherwise overwrite, tipping the avatar onto its back).this._canonicalRest = canonicalRestMapFromObject(model);+ // World-frame companion to _canonicalRest, captured in the same bind pose.+ // Supplying it lets the retargeter use the world-delta-preserving correction+ // (L = Rt·WT⁻¹·WS·Rs⁻¹) instead of the local-only premultiply fallback, which+ // skews an A-pose clip's limbs ~30° on a T-pose rig. Matches the server+ // (retargetClipToObject) and rig (retargetClipToRig) paths.+ this._canonicalWorldRest = canonicalWorldRestMapFromObject(model);// World rotation of the Hips' parent (within the model), so root motion is// re-expressed in the rig's own frame and travels the right way on any rig.this._hipsParentWorldQuat = hipsParentWorldQuat(model);@@ -232,6 +241,7 @@ export class AnimationManager {}const { clip: out } = retargetClip(clip, this._canonicalToNode, {targetRest: this._canonicalRest,+ targetWorldRest: this._canonicalWorldRest,hipsParentWorldQuat: this._hipsParentWorldQuat,hipScale,});@@ -301,7 +311,9 @@ export class AnimationManager {this.model = null;this._canonicalToNode = null;this._canonicalRest = null;+ this._canonicalWorldRest = null;this._hipsParentWorldQuat = null;+ this._hipTargetLocalY = 0;this._canonicalClipsSupported = false;this.actions.clear();this.currentAction = null;@@ -375,6 +387,10 @@ export class AnimationManager {* @returns {boolean}*/canPlay(name) {+ // A clip already rejected by the fallen-pose guard must not pass this+ // filter — it would make club.js route a routine step to it, then silently+ // no-op the crossfade, leaving the dancer frozen for the full step duration.+ if (this._fallen.has(name)) return false;if (this.clips.has(name)) return true;if (this._failed.has(name)) return false;return this._animationDefs.some((d) => d.name === name);@@ -575,13 +591,21 @@ export class AnimationManager {this.currentAction = action;this.currentName = name;+ // Tear down any previous settle listener before registering a new one so+ // interrupted one-shots don't accumulate listeners on the mixer.+ if (this._settleFinishHandler && this.mixer) {+ this.mixer.removeEventListener('finished', this._settleFinishHandler);+ this._settleFinishHandler = null;+ }if (settleTo && this.mixer) {const onFinished = (e) => {if (e.action !== action) return;this.mixer.removeEventListener('finished', onFinished);+ if (this._settleFinishHandler === onFinished) this._settleFinishHandler = null;// Only settle if nothing else took over the avatar meanwhile.if (this.currentAction === action) this.crossfadeTo(settleTo, fade);};+ this._settleFinishHandler = onFinished;this.mixer.addEventListener('finished', onFinished);}try { this.onChange?.(name); } catch (e) { log.warn('[AnimationManager] onChange threw:', e); }diff --git a/src/animation-retarget.js b/src/animation-retarget.jsindex da398e92c..f11ae1a00 100644--- a/src/animation-retarget.js+++ b/src/animation-retarget.js@@ -393,7 +393,7 @@ export function hipRestLocalHeight(root) {const worldY = _hipScalePos.y;hips.parent.matrixWorld.decompose(_hipScalePos, _hipScaleQuat, _hipScaleScale);const parentScale = (_hipScaleScale.x + _hipScaleScale.y + _hipScaleScale.z) / 3;- if (!(parentScale > 1e-6) || !Number.isFinite(worldY)) return 0;+ if (!(parentScale > 1e-6) || !(worldY > 0) || !Number.isFinite(worldY)) return 0;return worldY / parentScale;}diff --git a/src/app.js b/src/app.jsindex 3c05e11f1..1a9f9e6ef 100644--- a/src/app.js+++ b/src/app.js@@ -13,6 +13,7 @@ import { ThoughtBubble } from './thought-bubble.js';import { AvatarCreator } from './avatar-creator.js';import { resolveURI, isDecentralizedURI } from './ipfs.js';import { resolveDevR2Url } from './shared/dev-r2-proxy.js';+import { isSafeQueryModelUrl } from './shared/safe-model-url.js';// Resolve a model URL for loading: expand decentralized URIs (ipfs:/ar:) via the// gateway, then route r2.dev assets through the dev /r2-proxy so cross-origin@@ -21,12 +22,6 @@ function resolveModelUrl(url) {const expanded = isDecentralizedURI(url) ? resolveURI(url) : url;return resolveDevR2Url(expanded);}-// Hosts we trust to serve 3D assets when a model URL arrives from an untrusted-// source (the `?model=` query param). Same-origin, decentralized (ipfs:/ar:),-// and these first-party/gateway hosts only — so a crafted link can't make the-// viewer fetch and render an attacker-hosted GLB under the three.ws origin-// (brand-spoof / phishing).-const TRUSTED_ASSET_HOST_RE = /(^|\.)(three\.ws|r2\.dev|mypinata\.cloud|pinata\.cloud|ipfs\.io|dweb\.link|arweave\.net)$/i;// The on-chain deployment agent — the guided flow for deploying 3D assets on// Solana. The "Deploy on Solana" CTA in /app always routes here.const ONCHAIN_DEPLOY_AGENT_ID = '67bf6e67-93bb-40c6-9a6b-91e921696248';@@ -43,20 +38,6 @@ function ensureCornerStack() {(document.head || document.documentElement).appendChild(s);}-function isSafeQueryModelUrl(raw) {- if (!raw || typeof raw !== 'string') return false;- if (raw.startsWith('/') && !raw.startsWith('//')) return true; // same-origin relative- if (isDecentralizedURI(raw)) return true; // ipfs:// / ar://- try {- const u = new URL(raw, location.origin);- if (u.origin === location.origin) return true;- if (u.protocol !== 'https:') return false;- if (u.hostname === 'storage.googleapis.com') return true;- return TRUSTED_ASSET_HOST_RE.test(u.hostname);- } catch {- return false;- }-}import { saveRemoteGlbToAccount, getMe, readAuthHint } from './account.js';import { getWidget } from './widgets.js';import { mountAnimationGallery } from './widgets/animation-gallery.js';@@ -870,7 +851,7 @@ class App {const btn = document.getElementById('save-to-account-btn');if (btn) {btn.setAttribute('disabled', '');- btn.querySelector('span').textContent = 'Preparing…';+ btn.querySelector('span')?.textContent = 'Preparing…';}const stash = {@@ -913,7 +894,7 @@ class App {const btn = document.getElementById('save-to-account-btn');if (btn) {btn.setAttribute('disabled', '');- btn.querySelector('span').textContent = 'Saving…';+ btn.querySelector('span')?.textContent = 'Saving…';}try {let avatarId;@@ -922,7 +903,7 @@ class App {// Nothing to save — reset UI and bailif (btn) {btn.removeAttribute('disabled');- btn.querySelector('span').textContent = 'Save to account';+ btn.querySelector('span')?.textContent = 'Save to account';}return;}@@ -981,7 +962,7 @@ class App {this._flashSaved({ name: 'your account' });if (btn) {btn.removeAttribute('disabled');- btn.querySelector('span').textContent = 'Save to account';+ btn.querySelector('span')?.textContent = 'Save to account';}}}@@ -989,7 +970,7 @@ class App {log.warn('[3d-agent] save failed:', err.message);if (btn) {btn.removeAttribute('disabled');- btn.querySelector('span').textContent = 'Save to account';+ btn.querySelector('span')?.textContent = 'Save to account';}}}diff --git a/src/avatar-embed.js b/src/avatar-embed.jsindex 79e4e5af3..b87ed7f73 100644--- a/src/avatar-embed.js+++ b/src/avatar-embed.js@@ -71,6 +71,7 @@ import {conformanceReport,} from './runtime/arkit52.js';import { log } from './shared/log.js';+import { isSafeQueryModelUrl } from './shared/safe-model-url.js';const BRIDGE_VERSION = '1.0';const CAPABILITIES = [@@ -215,6 +216,7 @@ async function main() {// ── Face mocap (webcam, opt-in) ────────────────────────────────────────let mocap = null;+ let mocapVideo = null;let mocapBindingsReady = false;const findHeadBone = () => {let head = null;@@ -241,12 +243,12 @@ async function main() {mocap.onFaceDetected((has) => {updatePill(true, has);});- const video = await mocap.startWebcam();- video.style.cssText =+ mocapVideo = await mocap.startWebcam();+ mocapVideo.style.cssText ='position:absolute;right:10px;bottom:10px;width:120px;height:90px;' +'object-fit:cover;border-radius:8px;border:1px solid rgba(255,255,255,0.15);' +'transform:scaleX(-1);z-index:4;background:#000;';- document.body.appendChild(video);+ document.body.appendChild(mocapVideo);mocap.start();mocapBindingsReady = true;// Drive per-frame via viewer hook.@@ -275,8 +277,8 @@ async function main() {// Restore idle.if (idleEnabled) idle.setChannels({ saccade: true, blink: true });// Remove the picture-in-picture <video>.- const v = document.querySelector('video');- if (v) v.remove();+ mocapVideo?.remove();+ mocapVideo = null;mocap = null;mocapBindingsReady = false;updatePill(false, false);@@ -812,10 +814,12 @@ async function main() {// ── Resolve which avatar to render from URL params ──────────────────────────async function resolveAvatar(params) {- // Direct model URL — must be same-origin OR a three.ws CDN. Untrusted- // origins are silently rejected to avoid being a CSRF-style open relay.+ // Direct model URL — must be same-origin OR a trusted three.ws asset host.+ // Untrusted origins are rejected so the embed can't be turned into an open+ // relay that renders an attacker-hosted GLB under the three.ws origin.const model = params.get('model');if (model) {+ if (!isSafeQueryModelUrl(model)) throw new Error('untrusted model URL');return { modelUrl: model, name: null, id: null, handle: null };}diff --git a/src/club-camera.js b/src/club-camera.jsindex 25f0cfa06..450aa673e 100644--- a/src/club-camera.js+++ b/src/club-camera.js@@ -169,9 +169,17 @@ export class ClubCamera {// offset vector so pending transitions stay in sync.const nextRadius = Math.max(bounds.min, Math.min(bounds.max, this._autoOrbitRadius * factor));this._autoOrbitRadius = nextRadius;+ // Keep the fallback offset (used only when no dancer is performing) in+ // sync. Scale the HORIZONTAL components to the new radius and leave Y+ // (orbit height) untouched — scaling the full vector by the horizontal+ // ratio would drag the camera height with it.const current = this._pending ? this._pending.offset : this.offset;- const len = current.length();- if (len > 1e-4) current.multiplyScalar(nextRadius / (len > 1e-4 ? Math.hypot(current.x, current.z) || len : len));+ const horiz = Math.hypot(current.x, current.z);+ if (horiz > 1e-4) {+ const s = nextRadius / horiz;+ current.x *= s;+ current.z *= s;+ }return;}diff --git a/src/club-entrance.js b/src/club-entrance.jsindex 9249b8e32..1bd873d91 100644--- a/src/club-entrance.js+++ b/src/club-entrance.js@@ -784,14 +784,15 @@ async function start(canvasEl) {}// Backed out of the cover card without paying — resume walking the alley.- window.addEventListener('club:leave-door', () => {+ const onLeaveDoor = () => {if (phase !== 'walk') return;inputEnabled = true;showHint(true);showJoystick(isTouch);showMinimap(true);showAgentSwitch(true);- });+ };+ window.addEventListener('club:leave-door', onLeaveDoor);// ── State + render loop ──────────────────────────────────────────────────let phase = 'walk'; // walk (any place) → swapOut → swapIn → walk … → arriving → done@@ -1067,11 +1068,22 @@ async function start(canvasEl) {function dispose() {cancelAnimationFrame(raf);+ if (hintFlashTimer) { clearTimeout(hintFlashTimer); hintFlashTimer = 0; }window.removeEventListener('resize', onResize);window.removeEventListener('keydown', onKeyDown);window.removeEventListener('keyup', onKeyUp);window.removeEventListener('blur', onBlur);+ window.removeEventListener('club:leave-door', onLeaveDoor);document.removeEventListener('visibilitychange', onVisibility);+ // Canvas pointer/click + the persistent door-prompt click listener — the+ // prompt outlives the canvas, so its listener would otherwise pin the whole+ // scene graph (scene, rig, crowd, renderer) in memory after teardown.+ canvasEl.removeEventListener('pointerdown', onPointerDown);+ canvasEl.removeEventListener('pointermove', onPointerMove);+ canvasEl.removeEventListener('pointerup', endPointer);+ canvasEl.removeEventListener('pointercancel', endPointer);+ canvasEl.removeEventListener('click', onClick);+ promptEl?.removeEventListener('click', tryEnter);agentSelect?.removeEventListener('change', onAgentChange);agentBrowseBtn?.removeEventListener('click', onBrowseAgents);onAdmit = null;diff --git a/src/club-gate.js b/src/club-gate.jsindex 55990ded4..98ba27699 100644--- a/src/club-gate.js+++ b/src/club-gate.js@@ -73,9 +73,12 @@ function initDoor(root) {window.dispatchEvent(new CustomEvent('club:leave-door'));};backBtn?.addEventListener('click', backToAlley);- window.addEventListener('keydown', (e) => {+ const onKeyDown = (e) => {if (e.key === 'Escape' && root.dataset.state === 'queue') backToAlley();- });+ };+ window.addEventListener('keydown', onKeyDown);+ // Expose cleanup so openDoor can remove the listener when the card is torn down.+ root._removeKeyDown = () => window.removeEventListener('keydown', onKeyDown);}async function payCover(root, { payBtn, msgEl, tierEl }) {@@ -142,7 +145,15 @@ async function payCover(root, { payBtn, msgEl, tierEl }) {function openDoor(root, { silent = false } = {}) {root.classList.add('is-open');root.setAttribute('aria-hidden', 'true');+ // transitionend and the failsafe timer both call remove(); guard so the room+ // is torn down — and `club:admitted` dispatched — exactly once.+ let removed = false;+ let failsafe = null;const remove = () => {+ if (removed) return;+ removed = true;+ if (failsafe) clearTimeout(failsafe);+ try { root._removeKeyDown?.(); } catch {}root.remove();// Send focus into the room.try { document.getElementById('club-stage')?.focus?.({ preventScroll: true }); } catch {}@@ -153,7 +164,7 @@ function openDoor(root, { silent = false } = {}) {} else {root.addEventListener('transitionend', remove, { once: true });// Failsafe if transitionend never fires (reduced-motion / display swap).- setTimeout(remove, 900);+ failsafe = setTimeout(remove, 900);}}diff --git a/src/club-perf.js b/src/club-perf.jsindex 469a26eeb..d429873d0 100644--- a/src/club-perf.js+++ b/src/club-perf.js@@ -48,7 +48,7 @@ export function detectProfile(env = {}) {const isMobile = /(iPhone|iPad|Android|Mobi)/i.test(ua);const lowMem = (nav.deviceMemory ?? 8) < 4;const lowCores = (nav.hardwareConcurrency ?? 8) < 4;- const coarse = !!(win.matchMedia && win.matchMedia('(pointer: coarse)').matches);+ const coarse = !!(win.matchMedia && win.matchMedia('(any-pointer: coarse)').matches);const touchPrimary = !!(win.matchMedia && win.matchMedia('(pointer: coarse)').matches);if (!isMobile && !lowMem && !lowCores) return 'high';diff --git a/src/club.js b/src/club.jsindex ee1654c52..b0b73a3ff 100644--- a/src/club.js+++ b/src/club.js@@ -187,7 +187,7 @@ function renderTipRow(rowLike, { live = false, prepend = true } = {}) {const ticketId = rowLike.ticket_id ?? rowLike.ticketId ?? null;if (ticketId && !rememberTicketId(ticketId)) return;- const dancerId = rowLike.dancer ?? '?';+ const dancerId = String(rowLike.dancer ?? '?').replace(/[<>&"]/g, '');const dancerIdx = parseInt(dancerId, 10) - 1;const dancerName = DANCER_META[dancerIdx]?.name || `Dancer ${dancerId}`;const label = rowLike.label ?? rowLike.dance ?? 'dance';@@ -847,11 +847,27 @@ class PoleStation {// Cancel any in-flight performance: drop to idle, resolve pending// render-clock sleepers so a running playSequence unblocks and exits// (its isCancelled sees performing === false), and re-home the rig.+ const wasPerforming = this.performing;this.performing = false;this.walkPhase = 'idle';while (this._sleepers.length) this._sleepers.pop().resolve();this.activeTicket = null;+ // If a performance was interrupted, release the auto-cam and signal+ // the audio mixer — _endPerformance() won't run because walkPhase is+ // now 'idle', so we duplicate its cam+audio cleanup here.+ if (wasPerforming) {+ if (this._autoCammed && (clubCam.getMode() === 'auto' || clubCam.getMode() === 'vip')) {+ clubCam.setFree();+ }+ this._autoCammed = false;+ try {+ window.dispatchEvent(new CustomEvent('club:performance-end', {+ detail: { dancer: this.id, ticket: null },+ }));+ } catch {}+ }+this.anim?.detach();if (this.skinned) {this.rig.remove(this.skinned);@@ -1476,23 +1492,29 @@ window.addEventListener('club:performance-end', () => {// module finishes evaluating, but module load order and a failed/blocked script// mean we can't assume it's there. Poll briefly for window.X402.pay; resolve the// moment it appears (typically immediately on the first check).+let _x402PollId = null;function whenX402Ready(cb) {if (window.X402?.pay) { cb(); return; }let waited = 0;const POLL_MS = 100;const MAX_WAIT_MS = 15000;- const id = setInterval(() => {+ _x402PollId = setInterval(() => {waited += POLL_MS;if (window.X402?.pay) {- clearInterval(id);+ clearInterval(_x402PollId);+ _x402PollId = null;cb();} else if (waited >= MAX_WAIT_MS) {- clearInterval(id);+ clearInterval(_x402PollId);+ _x402PollId = null;// Widget never loaded — leave tip buttons disabled and tell the user.onTipButtonsUnavailable();}}, POLL_MS);}+window.addEventListener('pagehide', () => {+ if (_x402PollId !== null) { clearInterval(_x402PollId); _x402PollId = null; }+});function enableTipButtons() {for (const card of poleCardEls.values()) {@@ -1815,7 +1837,7 @@ function registerAvatar(entry) {}function escapeText(value) {- return String(value ?? '').replace(/[<>&"]/g, '');+ return String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));}const savedPoleAvatars = (() => {@@ -2551,4 +2573,7 @@ bootstrap()log.error('[club] bootstrap failed', err);setStatus(`Club failed to load: ${err.message}`, { kind: 'error' });})- .finally(() => animate());+ // Guard against a double-start: if the tab was hidden→shown during bootstrap,+ // the visibilitychange handler may have already started the loop. Starting a+ // second rAF chain here would double GPU cost and run the mixer at 2×.+ .finally(() => { if (rafId == null) animate(); });diff --git a/src/coin3d/main.js b/src/coin3d/main.jsindex 10665cd65..272f12dfa 100644--- a/src/coin3d/main.js+++ b/src/coin3d/main.js@@ -128,8 +128,8 @@ function ipfsToHttp(url) {// isn't a known gateway URL (nothing useful to retry).function altIpfsGateway(url) {if (typeof url !== 'string') return null;- if (url.includes('ipfs.io/ipfs/')) return url.replace('ipfs.io/ipfs/', 'cloudflare-ipfs.com/ipfs/');- if (url.includes('cloudflare-ipfs.com/ipfs/')) return url.replace('cloudflare-ipfs.com/ipfs/', 'ipfs.io/ipfs/');+ if (url.includes('ipfs.io/ipfs/')) return url.replace('ipfs.io/ipfs/', 'dweb.link/ipfs/');+ if (url.includes('dweb.link/ipfs/')) return url.replace('dweb.link/ipfs/', 'ipfs.io/ipfs/');return null;}diff --git a/src/create-review-features.js b/src/create-review-features.jsindex 4e44b654c..ff8ed16c7 100644--- a/src/create-review-features.js+++ b/src/create-review-features.js@@ -28,7 +28,7 @@ async function fetchPlatformStats() {const data = await res.json();return data && data.available ? data : null;} catch (err) {- log('[features] home-stats fetch failed:', err?.message || err);+ log.warn('[features] home-stats fetch failed:', err?.message || err);return null;}}@@ -1070,7 +1070,7 @@ async function fetchThreeTokenStats() {const data = await res.json();return data && data.token ? data.token : null;} catch (err) {- log('[features] three-token stats fetch failed:', err?.message || err);+ log.warn('[features] three-token stats fetch failed:', err?.message || err);return null;}}diff --git a/src/dad/dad.css b/src/dad/dad.cssnew file mode 100644index 000000000..28962311f--- /dev/null+++ b/src/dad/dad.css@@ -0,0 +1,348 @@+/* /dad — "Make Dad a 3D avatar" page styles. Consumes the canonical design+ tokens (public/tokens.css) directly; buttons use the shared .btn system. */++.dad {+ max-width: 880px;+ margin: 0 auto;+ padding: var(--space-2xl) var(--space-lg) var(--space-2xl);+ min-height: 70vh;+ display: flex;+ flex-direction: column;+ align-items: center;+ text-align: center;+}++.dad [data-region] {+ width: 100%;+ animation: dad-fade-in 0.4s ease both;+}++/* Headings get programmatic focus on stage change for screen-reader continuity;+ they aren't keyboard targets, so suppress the visible ring (keep the SR move). */+.dad [tabindex='-1']:focus {+ outline: none;+}++@keyframes dad-fade-in {+ from { opacity: 0; transform: translateY(8px); }+ to { opacity: 1; transform: translateY(0); }+}++/* ── Hero / intro ─────────────────────────────────────────────────────────── */++.dad-eyebrow {+ font: 600 var(--text-sm) / 1 var(--font-display);+ letter-spacing: 0.12em;+ text-transform: uppercase;+ color: var(--accent);+ opacity: 0.85;+ margin: 0 0 var(--space-md);+}++.dad-title {+ font: 700 var(--text-2xl) / 1.04 var(--font-display);+ color: var(--ink);+ margin: 0 0 var(--space-md);+ letter-spacing: -0.02em;+}++.dad-sub {+ font: 400 var(--text-lg) / 1.5 var(--font-body);+ color: var(--ink);+ opacity: 0.7;+ max-width: 30ch;+ margin: 0 auto var(--space-xl);+}++.dad-drop {+ width: 100%;+ max-width: 460px;+ margin: 0 auto;+ padding: var(--space-2xl) var(--space-lg);+ background: var(--surface-1);+ border: 1.5px dashed var(--stroke-strong);+ border-radius: var(--radius-lg);+ cursor: pointer;+ transition: border-color 0.18s ease, background 0.18s ease, transform 0.18s ease;+}++.dad-drop:hover,+.dad-drop:focus-visible,+.dad-drop.is-drag {+ border-color: var(--accent);+ background: var(--surface-2);+ outline: none;+}++.dad-drop.is-drag { transform: scale(1.01); }++.dad-drop:focus-visible {+ box-shadow: 0 0 0 var(--focus-ring-width) var(--focus-ring-color);+}++.dad-drop-icon {+ width: 40px;+ height: 40px;+ color: var(--accent);+ opacity: 0.9;+ margin-bottom: var(--space-sm);+}++.dad-drop-strong {+ font: 600 var(--text-lg) / 1.2 var(--font-body);+ color: var(--ink);+ margin: 0 0 var(--space-2xs);+}++.dad-drop-hint {+ font: 400 var(--text-md) / 1.4 var(--font-body);+ color: var(--ink);+ opacity: 0.6;+ margin: 0;+}++.dad-link { color: var(--accent); text-decoration: underline; }++.dad-fineprint {+ font: 400 var(--text-sm) / 1.5 var(--font-body);+ color: var(--ink);+ opacity: 0.45;+ margin: var(--space-md) auto 0;+ max-width: 40ch;+}++/* ── Generic stage boxes ──────────────────────────────────────────────────── */++.dad-stage-box {+ width: 100%;+ max-width: 520px;+ margin: 0 auto;+ display: flex;+ flex-direction: column;+ align-items: center;+}++.dad-h2 {+ font: 700 var(--text-xl) / 1.1 var(--font-display);+ color: var(--ink);+ margin: var(--space-md) 0 var(--space-xs);+ letter-spacing: -0.01em;+}++.dad-stage-help {+ font: 400 var(--text-md) / 1.5 var(--font-body);+ color: var(--ink);+ opacity: 0.65;+ margin: 0 0 var(--space-lg);+ max-width: 38ch;+}++.dad-actions {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-sm);+ justify-content: center;+}++.dad-actions-col {+ flex-direction: column;+ align-items: stretch;+ width: 100%;+ max-width: 260px;+}++.dad-btn { min-width: 160px; }++/* ── Preview ──────────────────────────────────────────────────────────────── */++.dad-preview-frame {+ width: 100%;+ max-width: 320px;+ aspect-ratio: 1 / 1;+ margin: 0 auto var(--space-lg);+ border-radius: var(--radius-lg);+ overflow: hidden;+ background:+ var(--surface-2)+ repeating-conic-gradient(rgba(255, 255, 255, 0.03) 0% 25%, transparent 0% 50%) 50% / 22px 22px;+ border: 1px solid var(--stroke);+ box-shadow: var(--shadow-2);+}++.dad-preview-img {+ width: 100%;+ height: 100%;+ object-fit: contain;+ display: block;+}++/* ── Generating ───────────────────────────────────────────────────────────── */++.dad-stage {+ width: 100%;+ max-width: 320px;+ aspect-ratio: 1 / 1;+ margin: 0 auto var(--space-md);+ border-radius: var(--radius-lg);+ overflow: hidden;+ border: 1px solid var(--stroke);+ background: var(--surface-1);+}++/* Gradient is built from theme-flipping surface tokens so the shimmer stays+ visible in both dark and light themes (the global --skeleton-* tokens don't+ remap for light). */+.dad-skeleton {+ width: 100%;+ height: 100%;+ background: linear-gradient(+ 100deg,+ var(--surface-2) 30%,+ var(--surface-3) 50%,+ var(--surface-2) 70%+ );+ background-size: 200% 100%;+ animation: dad-shimmer 1.4s ease-in-out infinite;+}++@keyframes dad-shimmer {+ from { background-position: 200% 0; }+ to { background-position: -200% 0; }+}++.dad-progress {+ width: 100%;+ max-width: 320px;+ height: 4px;+ border-radius: var(--radius-pill);+ background: var(--surface-3);+ overflow: hidden;+ margin-top: var(--space-sm);+}++/* Indeterminate: the reconstruct API reports no true percent, so the bar+ communicates "working" honestly rather than faking a percentage. */+.dad-progress-bar {+ width: 40%;+ height: 100%;+ border-radius: var(--radius-pill);+ background: var(--accent);+ animation: dad-indeterminate 1.3s ease-in-out infinite;+}++@keyframes dad-indeterminate {+ 0% { transform: translateX(-120%); }+ 100% { transform: translateX(320%); }+}++/* ── Result ───────────────────────────────────────────────────────────────── */++.dad-result {+ max-width: 880px;+ flex-direction: row;+ gap: var(--space-xl);+ align-items: stretch;+ text-align: left;+}++.dad-viewer-wrap {+ position: relative;+ flex: 1 1 60%;+ min-width: 0;+ min-height: 420px;+ border-radius: var(--radius-lg);+ background: radial-gradient(120% 90% at 50% 0%, var(--surface-2), var(--surface-1));+ border: 1px solid var(--stroke);+ overflow: hidden;+}++.dad-viewer { position: absolute; inset: 0; }++.dad-viewer-toolbar {+ position: absolute;+ left: 50%;+ bottom: var(--space-md);+ transform: translateX(-50%);+ display: flex;+ gap: var(--space-2xs);+ padding: var(--space-2xs);+ border-radius: var(--radius-pill);+ background: var(--surface-glass);+ -webkit-backdrop-filter: blur(8px);+ backdrop-filter: blur(8px);+ border: 1px solid var(--stroke);+}++.dad-chip {+ appearance: none;+ border: none;+ background: transparent;+ color: var(--ink);+ opacity: 0.7;+ font: 600 var(--text-sm) / 1 var(--font-body);+ padding: var(--space-xs) var(--space-md);+ border-radius: var(--radius-pill);+ cursor: pointer;+ transition: background 0.16s ease, opacity 0.16s ease, color 0.16s ease;+}++.dad-chip:hover { opacity: 1; background: var(--surface-3); }+.dad-chip:focus-visible {+ outline: none;+ box-shadow: 0 0 0 var(--focus-ring-width) var(--focus-ring-color);+}+.dad-chip.is-active {+ background: var(--accent);+ color: var(--btn-primary-fg);+ opacity: 1;+}++.dad-result-side {+ flex: 1 1 40%;+ display: flex;+ flex-direction: column;+ justify-content: center;+}++.dad-result-side .dad-h2 { margin-top: 0; }++.dad-share-copied {+ font: 500 var(--text-sm) / 1.4 var(--font-body);+ color: var(--success);+ margin: var(--space-sm) 0 0;+}++/* ── Error ────────────────────────────────────────────────────────────────── */++.dad-error-icon {+ width: 48px;+ height: 48px;+ display: grid;+ place-items: center;+ margin: 0 auto;+ border-radius: var(--radius-pill);+ background: var(--badge-danger-bg);+ color: var(--danger);+ border: 1px solid var(--badge-danger-border);+ font: 700 var(--text-xl) / 1 var(--font-display);+}++/* ── Responsive ───────────────────────────────────────────────────────────── */++/* Stack the result before the row gets cramped (viewer + side-panel). */+@media (max-width: 860px) {+ .dad-result { flex-direction: column; }+}++@media (max-width: 720px) {+ .dad { padding: var(--space-xl) var(--space-md); }+ .dad-title { font-size: var(--text-xl); }+ .dad-viewer-wrap { min-height: 340px; }+}++@media (prefers-reduced-motion: reduce) {+ .dad [data-region],+ .dad-skeleton,+ .dad-progress-bar { animation: none; }+ .dad-progress-bar { width: 100%; }+}diff --git a/src/dad/index.js b/src/dad/index.jsnew file mode 100644index 000000000..4a8600006--- /dev/null+++ b/src/dad/index.js@@ -0,0 +1,631 @@+// /dad — "Make Dad a 3D avatar" page controller.+//+// Flow (all real, no mocks):+// pick/drop photo → normalize (downscale / HEIC→JPEG) → /api/forge-upload+// (presigned R2 PUT) → public URL → /api/forge-rembg (human matte; graceful+// skip if unconfigured) → preview → /api/dad/generate (headless+// image→rigged-GLB reconstruct) → poll → <agent-3d> decoration viewer+// (idle/walk/wave) → share permalink.+//+// Isolated feature: imports only shared, generic services (object storage,+// background removal, the reconstruct provider) — never the forge generation+// pipeline. The <agent-3d> element handles canonicalize + retarget so any+// rigged humanoid GLB idles and walks with no per-rig code.++import './dad.css';++// /api/forge-upload caps at 8 MB; anything larger (or any non-accepted type) is+// downscaled + re-encoded to JPEG client-side before upload, so the three.ws+// "up to 8 MB" contract always holds and phone HEIC photos work where decodable.+const UPLOAD_MAX_BYTES = 8 * 1024 * 1024;+// Sanity ceiling on the raw file we'll even attempt to decode.+const MAX_RAW_BYTES = 40 * 1024 * 1024;+// Longest-edge cap for the re-encoded upload — plenty for reconstruction.+const MAX_DIM = 1536;+const ACCEPT = new Set(['image/png', 'image/jpeg', 'image/webp']);+// Heaviest a reconstruct can reasonably take before we stop waiting.+const GEN_TIMEOUT_MS = 4 * 60 * 1000;+const REMBG_TIMEOUT_MS = 60 * 1000;+const POLL_MS = 2500;++// Hosts a shared (?a=) GLB may legitimately come from: our own origin, the R2+// bucket, and the reconstruct providers' delivery CDNs. Anything else is+// refused so a crafted permalink can't make a victim's browser parse arbitrary+// GLB bytes on the three.ws origin.+const ALLOWED_GLB_HOST = /(^|\.)(r2\.dev|replicate\.delivery|storage\.googleapis\.com|googleusercontent\.com|hf\.space)$/i;++// The <agent-3d> decoration runtime is ~3.5 MB — load it only when we actually+// have an avatar to show, not on the upload screen.+const AGENT3D_LOADER = '/agent-3d/latest/agent-3d.js';++const DEV = Boolean(import.meta.env && import.meta.env.DEV);++const root = document.getElementById('dad');+const els = {+ drop: document.getElementById('dad-drop'),+ file: document.getElementById('dad-file'),+ previewImg: document.getElementById('dad-preview-img'),+ generate: document.getElementById('dad-generate'),+ progressText: document.getElementById('dad-progress-text'),+ viewer: document.getElementById('dad-viewer'),+ animIdle: document.getElementById('dad-anim-idle'),+ animWalk: document.getElementById('dad-anim-walk'),+ animWave: document.getElementById('dad-anim-wave'),+ share: document.getElementById('dad-share'),+ shareCopied: document.getElementById('dad-share-copied'),+ download: document.getElementById('dad-download'),+ errorTitle: document.getElementById('dad-error-title'),+ errorMsg: document.getElementById('dad-error-msg'),+ retry: document.getElementById('dad-retry'),+};++const regions = {};+for (const box of root.querySelectorAll('[data-region]')) {+ regions[box.dataset.region] = box;+}++// Monotonic id so a slow upload/matte chain that resolves AFTER the user reset+// or picked a different photo becomes a no-op instead of clobbering fresh state.+let runId = 0;++// Mutable run state for the current photo → avatar attempt.+const state = {+ /** Public URL of the matted (or raw) photo fed to the reconstruct. */+ sourceUrl: null,+ /** ObjectURL we created locally — revoked on reset to avoid leaks. */+ localObjectUrl: null,+ glbUrl: null,+ viewerEl: null,+ viewerReady: false,+ readyFallback: null,+ agent3dReady: null,+};++// ── Stage routing ───────────────────────────────────────────────────────────++function setStage(stage) {+ root.dataset.stage = stage;+ for (const [name, box] of Object.entries(regions)) {+ box.hidden = name !== stage;+ }+ // Move focus to the new stage's heading for screen-reader continuity.+ const heading = regions[stage]?.querySelector('h1, h2');+ if (heading && stage !== 'intro') {+ heading.setAttribute('tabindex', '-1');+ heading.focus({ preventScroll: true });+ }+}++function showError(title, message) {+ els.errorTitle.textContent = title;+ els.errorMsg.textContent = message;+ setStage('error');+}++// ── Upload + preprocess ─────────────────────────────────────────────────────++function validate(file) {+ if (!file) return 'No file selected.';+ const isImage =+ (file.type && file.type.startsWith('image/')) ||+ /\.(jpe?g|png|webp|heic|heif|gif|bmp|tiff?)$/i.test(file.name || '');+ if (!isImage) return 'Please choose an image file (JPG, PNG, HEIC, or WebP).';+ if (file.size > MAX_RAW_BYTES) return 'That image is too large — please use one under 40 MB.';+ return null;+}++function decodeViaImg(file) {+ return new Promise((resolve, reject) => {+ const url = URL.createObjectURL(file);+ const img = new Image();+ img.onload = () => {+ URL.revokeObjectURL(url);+ resolve(img);+ };+ img.onerror = () => {+ URL.revokeObjectURL(url);+ reject(new Error('decode failed'));+ };+ img.src = url;+ });+}++// Return an upload-ready File: accepted type and ≤ 8 MB. Already-fine images+// pass through untouched (no quality loss); everything else (oversized, or a+// HEIC/odd format the browser can decode) is drawn onto a white-matted canvas+// and re-encoded to JPEG so alpha never reaches the reconstruct as ambiguity.+async function prepareImage(file) {+ if (ACCEPT.has(file.type) && file.size <= UPLOAD_MAX_BYTES) return file;++ let bitmap = null;+ try {+ bitmap = await createImageBitmap(file);+ } catch {+ bitmap = await decodeViaImg(file).catch(() => null);+ }+ if (!bitmap) {+ throw new Error(+ 'We couldn’t read that photo. iPhone HEIC photos sometimes fail — set Camera → Formats → “Most Compatible”, or upload a JPG.',+ );+ }++ const iw = bitmap.naturalWidth || bitmap.width;+ const ih = bitmap.naturalHeight || bitmap.height;+ const scale = Math.min(1, MAX_DIM / Math.max(iw, ih));+ const w = Math.max(1, Math.round(iw * scale));+ const h = Math.max(1, Math.round(ih * scale));++ const canvas = document.createElement('canvas');+ canvas.width = w;+ canvas.height = h;+ const ctx = canvas.getContext('2d');+ ctx.fillStyle = '#ffffff';+ ctx.fillRect(0, 0, w, h);+ ctx.drawImage(bitmap, 0, 0, w, h);+ bitmap.close?.();++ const blob = await new Promise((res) => canvas.toBlob(res, 'image/jpeg', 0.9));+ if (!blob) throw new Error('We couldn’t process that photo. Please try a different one.');+ return new File([blob], 'dad.jpg', { type: 'image/jpeg' });+}++async function presignAndPut(file) {+ const presignRes = await fetch('/api/forge-upload', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ content_type: file.type, size_bytes: file.size }),+ });+ if (presignRes.status === 503) {+ throw new Error('Photo uploads are temporarily unavailable. Please try again shortly.');+ }+ if (presignRes.status === 429) {+ throw new Error("You've uploaded a lot just now — give it a minute and try again.");+ }+ const presign = await presignRes.json().catch(() => ({}));+ if (!presignRes.ok || !presign.upload_url || !presign.public_url) {+ throw new Error(presign.message || 'Could not start the upload.');+ }+ const put = await fetch(presign.upload_url, {+ method: presign.method || 'PUT',+ headers: presign.headers || { 'content-type': file.type },+ body: file,+ });+ if (!put.ok) throw new Error('The photo failed to upload. Check your connection and retry.');+ return presign.public_url;+}++// Human-subject background removal. Best-effort: if the service is unconfigured+// or fails, fall back to the raw photo rather than blocking the whole flow.+async function matte(publicUrl) {+ let start;+ try {+ start = await fetch('/api/forge-rembg', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ image_url: publicUrl, model: 'u2net_human_seg' }),+ });+ } catch {+ return publicUrl;+ }+ if (!start.ok) return publicUrl; // 503 unconfigured / 429 / etc. → use raw.+ const { job_id: jobId } = await start.json().catch(() => ({}));+ if (!jobId) return publicUrl;++ const deadline = Date.now() + REMBG_TIMEOUT_MS;+ while (Date.now() < deadline) {+ await sleep(POLL_MS);+ let poll;+ try {+ poll = await fetch(`/api/forge-rembg?job=${encodeURIComponent(jobId)}`);+ } catch {+ return publicUrl;+ }+ const data = await poll.json().catch(() => ({}));+ if (data.result_url) return data.result_url;+ if (isFailed(data.status)) {+ if (DEV) console.warn('[dad] rembg failed, using raw photo:', data.error);+ return publicUrl;+ }+ }+ if (DEV) console.warn('[dad] rembg timed out, using raw photo');+ return publicUrl; // timed out → raw photo is a fine input too.+}++async function handleFile(file) {+ const myRun = ++runId;++ const err = validate(file);+ if (err) {+ showError('That photo won’t work', err);+ return;+ }++ // Instant local preview so the screen never sits empty while we upload.+ revokeLocal();+ state.localObjectUrl = URL.createObjectURL(file);+ els.previewImg.src = state.localObjectUrl;+ setStage('preview');+ els.generate.disabled = true;+ els.generate.textContent = 'Preparing photo…';++ try {+ const prepared = await prepareImage(file);+ if (myRun !== runId) return;+ const publicUrl = await presignAndPut(prepared);+ if (myRun !== runId) return;+ const matted = await matte(publicUrl);+ if (myRun !== runId) return;+ state.sourceUrl = matted;+ // Swap the local preview for the processed (matted) one.+ els.previewImg.src = matted;+ els.generate.disabled = false;+ els.generate.textContent = 'Make the 3D avatar';+ } catch (e) {+ if (myRun !== runId) return;+ showError('Upload trouble', e.message || 'Could not prepare that photo. Try another.');+ }+}++// ── Generate ────────────────────────────────────────────────────────────────++async function generate() {+ if (!state.sourceUrl) {+ showError('No photo yet', 'Pick a photo of your dad first.');+ return;+ }+ setStage('generating');++ let startRes;+ try {+ startRes = await fetch('/api/dad/generate', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ image_url: state.sourceUrl }),+ });+ } catch {+ showError('Network hiccup', 'We couldn’t reach the avatar service. Check your connection and retry.');+ return;+ }++ if (startRes.status === 503) {+ showError(+ 'Avatar engine offline',+ 'The 3D avatar engine isn’t available right now. We’ve been notified — please try again later.',+ );+ return;+ }+ if (startRes.status === 429) {+ showError('Slow down a touch', "You've made a lot of avatars just now. Give it a minute and try again.");+ return;+ }+ const start = await startRes.json().catch(() => ({}));+ if (!startRes.ok || !start.job_id) {+ showError('Couldn’t start', start.message || start.error_description || 'The avatar job failed to start.');+ return;+ }++ els.progressText.textContent = 'Reconstructing geometry from the photo…';++ const deadline = Date.now() + GEN_TIMEOUT_MS;+ let ticks = 0;+ while (Date.now() < deadline) {+ await sleep(POLL_MS);+ ticks += 1;+ // Status copy advances on real elapsed polling — the bar itself is+ // indeterminate (CSS), since the reconstruct API reports no true percent.+ if (ticks === 4) els.progressText.textContent = 'Building textures and rigging the skeleton…';+ if (ticks === 10) els.progressText.textContent = 'Almost there — finishing the mesh…';++ let poll;+ try {+ poll = await fetch(`/api/dad/generate?job=${encodeURIComponent(start.job_id)}`);+ } catch {+ continue; // transient — keep polling until the deadline.+ }+ const data = await poll.json().catch(() => ({}));+ const glb = data.glb_url || data.result_url;+ if (glb && isDone(data.status)) {+ await showResult(glb);+ return;+ }+ if (isFailed(data.status)) {+ showError(+ 'Couldn’t build the avatar',+ data.error || 'The photo couldn’t be turned into a clean 3D model. A brighter, front-facing shot usually fixes it.',+ );+ return;+ }+ }+ showError('Took too long', 'The avatar took longer than expected. Please try again.');+}++// ── Result + viewer ─────────────────────────────────────────────────────────++function loadAgent3d() {+ if (state.agent3dReady) return state.agent3dReady;+ const p = new Promise((resolve, reject) => {+ if (customElements.get('agent-3d')) return resolve();+ // If a previous attempt left a script tag that already errored, remove it+ // so we can inject a fresh one — otherwise attaching a 'load' listener on+ // a dead script hangs the promise forever.+ const existing = document.querySelector(`script[data-agent3d]`);+ if (existing) {+ if (existing.dataset.agent3dFailed) {+ existing.remove();+ } else {+ existing.addEventListener('load', () => resolve());+ existing.addEventListener('error', () => reject(new Error('viewer failed to load')));+ return;+ }+ }+ const s = document.createElement('script');+ s.type = 'module';+ s.src = AGENT3D_LOADER;+ s.dataset.agent3d = '1';+ s.addEventListener('load', () => resolve());+ s.addEventListener('error', () => {+ s.dataset.agent3dFailed = '1';+ reject(new Error('viewer failed to load'));+ });+ document.head.appendChild(s);+ });+ state.agent3dReady = p;+ // Clear the cache on failure so the next showResult() call retries the load+ // rather than immediately re-resolving with a permanently rejected promise.+ p.catch(() => { state.agent3dReady = null; });+ return p;+}++function setChipsEnabled(on) {+ for (const c of [els.animIdle, els.animWalk, els.animWave]) c.disabled = !on;+}++async function showResult(glbUrl) {+ state.glbUrl = glbUrl;+ els.download.href = glbUrl;++ try {+ await loadAgent3d();+ await customElements.whenDefined('agent-3d');+ } catch {+ // Viewer bundle unavailable — still give them the file + share link.+ showError(+ 'Preview unavailable',+ 'Your avatar is ready to download, but the 3D preview couldn’t load here. Try the Download button.',+ );+ return;+ }++ els.viewer.replaceChildren();+ const el = document.createElement('agent-3d');+ el.setAttribute('src', glbUrl);+ el.setAttribute('clip', 'idle');+ el.setAttribute('background', 'transparent');+ el.setAttribute('responsive', '');+ el.style.width = '100%';+ el.style.height = '100%';+ els.viewer.appendChild(el);+ state.viewerEl = el;++ // Chips stay disabled until the scene actually mounts, so a click can't+ // no-op while the avatar is still loading (which would desync the active+ // chip). The avatar idles on its own via the `clip` attribute meanwhile.+ state.viewerReady = false;+ setChipsEnabled(false);+ setActiveChip(els.animIdle);+ const onReady = () => {+ if (state.viewerEl !== el) return; // a newer avatar took over+ clearTimeout(state.readyFallback);+ state.viewerReady = true;+ setChipsEnabled(true);+ };+ el.addEventListener('agent:ready', onReady, { once: true });+ // Defensive: never strand the controls if that event doesn't arrive.+ clearTimeout(state.readyFallback);+ state.readyFallback = setTimeout(onReady, 6000);++ setStage('result');+}++function setActiveChip(active) {+ for (const c of [els.animIdle, els.animWalk, els.animWave]) {+ const on = c === active;+ c.classList.toggle('is-active', on);+ c.setAttribute('aria-pressed', String(on));+ }+}++function playClip(name, chip) {+ const el = state.viewerEl;+ if (!el || !state.viewerReady) return;+ try {+ if (name === 'wave' && typeof el.wave === 'function') el.wave();+ else if (typeof el.playClip === 'function') el.playClip(name, { userInitiated: true });+ else if (typeof el.play === 'function') el.play(name, { loop: name !== 'wave' });+ } catch {+ /* a single clip miss shouldn't break the toolbar */+ }+ // Wave is a one-shot that settles back into idle — reflect that in the UI.+ setActiveChip(name === 'wave' ? els.animIdle : chip);+}++// ── Share ───────────────────────────────────────────────────────────────────++function shareUrl() {+ const u = new URL('/dad', location.origin);+ u.searchParams.set('a', state.glbUrl);+ return u.toString();+}++async function share() {+ if (!state.glbUrl) return; // nothing to share (e.g. preview-unavailable path)+ const url = shareUrl();+ const shareData = {+ title: 'My dad, in 3D',+ text: 'I turned my dad into a 3D avatar on three.ws. Happy Father’s Day.',+ url,+ };+ if (navigator.share) {+ try {+ await navigator.share(shareData);+ return;+ } catch {+ /* user dismissed the sheet — fall through to copy */+ }+ }+ try {+ await navigator.clipboard.writeText(url);+ els.shareCopied.hidden = false;+ clearTimeout(share._t);+ share._t = setTimeout(() => {+ els.shareCopied.hidden = true;+ }, 2600);+ } catch {+ window.prompt('Copy this link to share your dad:', url);+ }+}++function isAllowedGlbUrl(raw) {+ let url;+ try {+ url = new URL(raw, location.origin);+ } catch {+ return false;+ }+ if (!/^https?:$/.test(url.protocol)) return false;+ if (url.origin === location.origin) return true;+ return ALLOWED_GLB_HOST.test(url.hostname);+}++// Render a shared avatar straight from a permalink (?a=<glb url>).+async function maybeRenderShared() {+ const a = new URL(location.href).searchParams.get('a');+ if (!a) return false;+ // Only load GLBs from our origin or known provider CDNs — a crafted ?a= must+ // not make the browser parse arbitrary bytes on the three.ws origin.+ if (!isAllowedGlbUrl(a)) return false;+ setStage('generating');+ els.progressText.textContent = 'Loading the shared avatar…';+ await showResult(new URL(a, location.origin).toString());+ return true;+}++// ── Helpers ─────────────────────────────────────────────────────────────────++function sleep(ms) {+ return new Promise((r) => setTimeout(r, ms));+}++function isDone(status) {+ const s = String(status || '').toLowerCase();+ return s === 'succeeded' || s === 'completed' || s === 'done' || s === 'success';+}++function isFailed(status) {+ const s = String(status || '').toLowerCase();+ return s === 'failed' || s === 'error' || s === 'canceled' || s === 'cancelled';+}++function revokeLocal() {+ if (state.localObjectUrl) {+ URL.revokeObjectURL(state.localObjectUrl);+ state.localObjectUrl = null;+ }+}++function reset() {+ runId += 1; // invalidate any in-flight upload/matte chain+ clearTimeout(state.readyFallback);+ revokeLocal();+ state.sourceUrl = null;+ state.glbUrl = null;+ state.viewerEl = null;+ state.viewerReady = false;+ els.viewer.replaceChildren();+ els.file.value = '';+ els.shareCopied.hidden = true;+ // Drop ?a= so a reset from a shared link returns to the uploader cleanly.+ if (new URL(location.href).searchParams.has('a')) {+ history.replaceState(null, '', '/dad');+ }+ setStage('intro');+}++// ── Wiring ──────────────────────────────────────────────────────────────────++function pickFile() {+ els.file.click();+}++els.drop.addEventListener('click', pickFile);+els.drop.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ pickFile();+ }+});+els.file.addEventListener('change', () => {+ const f = els.file.files?.[0];+ if (f) handleFile(f);+});++for (const evt of ['dragenter', 'dragover']) {+ els.drop.addEventListener(evt, (e) => {+ e.preventDefault();+ els.drop.classList.add('is-drag');+ });+}+for (const evt of ['dragleave', 'drop']) {+ els.drop.addEventListener(evt, (e) => {+ e.preventDefault();+ els.drop.classList.remove('is-drag');+ });+}+els.drop.addEventListener('drop', (e) => {+ const f = e.dataTransfer?.files?.[0];+ if (f) handleFile(f);+});++els.generate.addEventListener('click', generate);+els.retry.addEventListener('click', () => {+ if (state.sourceUrl) generate();+ else reset();+});+els.share.addEventListener('click', share);++// A cross-origin <a download> is ignored by the browser (it navigates to the+// binary instead). Fetch the GLB and download the blob; fall back to opening it+// if the provider CDN blocks the cross-origin fetch.+els.download.addEventListener('click', async (e) => {+ if (!state.glbUrl) return;+ e.preventDefault();+ try {+ const r = await fetch(state.glbUrl);+ if (!r.ok) throw new Error('fetch failed');+ const blob = await r.blob();+ const u = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = u;+ a.download = 'dad-avatar.glb';+ document.body.appendChild(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(u), 1000);+ } catch {+ window.open(state.glbUrl, '_blank', 'noopener');+ }+});++els.animIdle.addEventListener('click', () => playClip('idle', els.animIdle));+els.animWalk.addEventListener('click', () => playClip('walk', els.animWalk));+els.animWave.addEventListener('click', () => playClip('wave', els.animWave));++for (const id of ['dad-reset-1', 'dad-reset-2', 'dad-reset-3']) {+ document.getElementById(id)?.addEventListener('click', reset);+}++window.addEventListener('beforeunload', revokeLocal);++maybeRenderShared().then((shared) => {+ if (!shared) setStage('intro');+});diff --git a/src/dashboard/dashboard.js b/src/dashboard/dashboard.jsindex 2152ffde6..d28b6e71e 100644--- a/src/dashboard/dashboard.js+++ b/src/dashboard/dashboard.js@@ -5972,7 +5972,8 @@ async function renderEarnings(root) {return;}- const { pending_usd, settled_usd, entries } = data;+ const { pending_usd, settled_usd } = data;+ const entries = Array.isArray(data.entries) ? data.entries : [];if (!entries.length) {body.innerHTML = `@@ -6059,6 +6060,21 @@ async function renderPayments(root) {let nextPayCursor = null;+ // wei (integer string) → trimmed ETH string. Defensive: a malformed+ // amount_wei (decimals, hex, empty) would otherwise throw in BigInt and abort+ // rendering every remaining payment row, so bad values degrade to '—'.+ function formatWeiToEth(weiStr) {+ if (!weiStr || !/^\d+$/.test(String(weiStr).trim())) return '—';+ try {+ return (Number(BigInt(String(weiStr).trim())) / 1e18)+ .toFixed(8)+ .replace(/0+$/, '')+ .replace(/\.$/, '.0');+ } catch {+ return '—';+ }+ }+async function loadPayPage(replace) {const params = new URLSearchParams({ direction: 'sent', limit: '20' });if (nextPayCursor) params.set('cursor', nextPayCursor);@@ -6118,12 +6134,7 @@ async function renderPayments(root) {const moreEl = body.querySelector('#pay-more');for (const p of data.payments) {- const amountEth = p.amount_wei- ? (Number(BigInt(p.amount_wei)) / 1e18)- .toFixed(8)- .replace(/0+$/, '')- .replace(/\.$/, '.0')- : '—';+ const amountEth = formatWeiToEth(p.amount_wei);const statusColor =p.status === 'confirmed' ? '#00e5a0' : p.status === 'failed' ? '#ff5c5c' : '#888';const explorerBase =diff --git a/src/economy-live.js b/src/economy-live.jsindex 9ede7d5a2..f1577fd36 100644--- a/src/economy-live.js+++ b/src/economy-live.js@@ -105,12 +105,13 @@ function agentCard(a) {</a>`;}-async function loadAgents() {+async function loadAgents({ quiet = false } = {}) {const host = $('#ae-agents');if (!host) return;- skeleton(host, 6, 'card');+ if (!quiet) skeleton(host, 6, 'card');try {- const params = new URLSearchParams({ sort: 'top_rated', limit: '24' });+ const sort = $('#ae-sort')?.value || 'top_rated';+ const params = new URLSearchParams({ sort, limit: '24' });const r = await fetch(`/api/marketplace/agents?${params}`, { credentials: 'include' });if (!r.ok) throw new Error(`status ${r.status}`);const j = await r.json();@@ -154,10 +155,10 @@ function serviceRow(t) {</a>`;}-async function loadServices() {+async function loadServices({ quiet = false } = {}) {const host = $('#ae-services');if (!host) return;- skeleton(host, 5, 'row');+ if (!quiet) skeleton(host, 5, 'row');try {const params = new URLSearchParams({ type: 'http', maxItems: '40' });const r = await fetch(`/api/agenc/x402-services?${params}`);@@ -183,9 +184,36 @@ function setStat(sel, value) {if (el) el.textContent = value;}+const REFRESH_MS = 45000;+let _refreshTimer = 0;++function scheduleRefresh() {+ clearInterval(_refreshTimer);+ _refreshTimer = window.setInterval(() => {+ if (document.hidden) return; // don't poll a backgrounded tab+ loadAgents({ quiet: true });+ loadServices({ quiet: true });+ pulseLive();+ }, REFRESH_MS);+}++function pulseLive() {+ const live = $('#ae-live');+ if (!live) return;+ live.hidden = false;+ const label = $('#ae-live-label');+ if (label) {+ label.textContent = 'Updated just now';+ setTimeout(() => { label.textContent = 'Live'; }, 2500);+ }+}+export function initEconomyLive() {- loadAgents();+ loadAgents().then(() => pulseLive());loadServices();+ const sortEl = $('#ae-sort');+ if (sortEl) sortEl.addEventListener('change', () => loadAgents());+ scheduleRefresh();}if (typeof document !== 'undefined') {diff --git a/src/face-mocap.js b/src/face-mocap.jsindex cab39d3c1..ee565176e 100644--- a/src/face-mocap.js+++ b/src/face-mocap.js@@ -261,7 +261,7 @@ export class FaceMocap {const wasRunning = this._running;this._running = false; // freeze live capture while playing back- const t0 = performance.now();+ let t0 = performance.now();const frames = clip.frames;let i = 0, raf = 0, stopped = false;@@ -298,7 +298,9 @@ export class FaceMocap {if (i >= frames.length - 1 && t >= clip.duration) {if (opts.loop) {i = 0;- return; // restart on next rAF+ t0 = performance.now();+ raf = requestAnimationFrame(tick);+ return;}stopped = true;this._running = wasRunning;diff --git a/src/forge-studio/lab/lab.js b/src/forge-studio/lab/lab.jsindex 228723798..2ee1e8b49 100644--- a/src/forge-studio/lab/lab.js+++ b/src/forge-studio/lab/lab.js@@ -335,10 +335,15 @@ async function convertToSplats() {sourceLabel = f.name;}if (!source) throw new Error('No model yet — generate one with a mesh tool first, or upload a GLB.');- status('Sampling surface into Gaussians…');- const { buffer, count } = meshToSplatBuffer(source, { count: Number(params.count), seed: Number(params.seed) });+ status('Sampling surface into Gaussians… 0%');+ const { buffer, count, textured } = await meshToSplatBuffer(source, {+ count: Number(params.count),+ seed: Number(params.seed),+ onProgress: (pct) => status(`Sampling surface into Gaussians… ${pct}%`),+ });if (params.source === 'upload') disposeObject(source); // free the uploaded scene- await renderSplatBuffer(buffer, `${count.toLocaleString()} splats from ${sourceLabel}`);+ const colorNote = textured ? ' · textured' : '';+ await renderSplatBuffer(buffer, `${count.toLocaleString()} splats from ${sourceLabel}${colorNote}`);// .splat downloadif (_lastSplatUrl) URL.revokeObjectURL(_lastSplatUrl);_lastSplatUrl = URL.createObjectURL(new Blob([buffer], { type: 'application/octet-stream' }));diff --git a/src/forge-studio/lab/mesh-to-splat.js b/src/forge-studio/lab/mesh-to-splat.jsindex 46224a088..a585e5a3b 100644--- a/src/forge-studio/lab/mesh-to-splat.js+++ b/src/forge-studio/lab/mesh-to-splat.js@@ -6,20 +6,28 @@* gets resampled into a Gaussian-splat radiance field entirely in the browser.** Approach: area-weighted surface sampling. We walk every triangle, sample N- * points proportional to triangle area, read colour from vertex colours (or the- * material base colour as a fallback), and emit each point as one Gaussian in- * the antimatter15 `.splat` layout (32 bytes/splat: center f32×3, scale f32×3,- * colour u8×4, rotation u8×4). The result loads straight into the splat viewer- * and downloads as a real `.splat` file.+ * points proportional to triangle area, and read colour in priority order:+ * 1. the material's texture map, sampled at the point's interpolated UV+ * (so a real textured GLB keeps its true colours, not a flat base tint);+ * 2. per-vertex colours (e.g. the terrain generator);+ * 3. the material base colour.+ * Each point becomes one Gaussian in the antimatter15 `.splat` layout+ * (32 bytes/splat: center f32×3, scale f32×3, colour u8×4, rotation u8×4).+ * Colours are emitted in sRGB so the radiance field matches the lit mesh.+ *+ * The sampler is async and yields between chunks so converting 100k+ splats+ * never freezes the tab, reporting progress as it goes.*/import * as THREE from 'three';+const TEX_MAX = 1024; // cap sampled-texture resolution for speed/memory+const _v = {a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(),- ab: new THREE.Vector3(), ac: new THREE.Vector3(), cross: new THREE.Vector3(),+ ab: new THREE.Vector3(), ac: new THREE.Vector3(),p: new THREE.Vector3(),- ca: new THREE.Color(), cb: new THREE.Color(), cc: new THREE.Color(), cp: new THREE.Color(),+ col: new THREE.Color(),};function collectMeshes(object3d) {@@ -29,16 +37,56 @@ function collectMeshes(object3d) {return meshes;}-// Build a flat list of triangles with world-space positions + per-vertex colours.+// Rasterize a material's base-colour texture to an ImageData once, so we can+// sample it per point. Returns null if the material has no drawable map.+function buildTextureSampler(material) {+ const map = material?.map;+ const img = map?.image;+ if (!img || !(img.width || img.naturalWidth)) return null;+ const iw = img.width || img.naturalWidth;+ const ih = img.height || img.naturalHeight;+ if (!iw || !ih) return null;+ const scale = Math.min(1, TEX_MAX / Math.max(iw, ih));+ const w = Math.max(1, Math.round(iw * scale));+ const h = Math.max(1, Math.round(ih * scale));+ let data;+ try {+ const canvas = document.createElement('canvas');+ canvas.width = w;+ canvas.height = h;+ const ctx = canvas.getContext('2d', { willReadFrequently: true });+ ctx.drawImage(img, 0, 0, w, h);+ data = ctx.getImageData(0, 0, w, h).data;+ } catch {+ return null; // tainted/undrawable image — fall back to vertex/material colour+ }+ const flipY = map.flipY !== false; // glTF textures are flipY:false; default true otherwise+ return (u, vv, out) => {+ // wrap UVs into [0,1)+ let uu = u - Math.floor(u);+ let v = vv - Math.floor(vv);+ const px = Math.min(w - 1, Math.max(0, Math.floor(uu * w)));+ const sampleV = flipY ? 1 - v : v;+ const py = Math.min(h - 1, Math.max(0, Math.floor(sampleV * h)));+ const idx = (py * w + px) * 4;+ out.set(data[idx] / 255, data[idx + 1] / 255, data[idx + 2] / 255); // already sRGB bytes+ return true;+ };+}++// Build a flat triangle list with world positions, per-vertex colours, UVs and+// a per-triangle texture sampler.function gatherTriangles(meshes) {const tris = [];for (const mesh of meshes) {const geo = mesh.geometry;const pos = geo.attributes.position;const colAttr = geo.attributes.color || null;- const matColor = new THREE.Color(1, 1, 1);+ const uvAttr = geo.attributes.uv || null;const m = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material;- if (m?.color) matColor.copy(m.color);+ const matColorSRGB = new THREE.Color(1, 1, 1);+ if (m?.color) matColorSRGB.copy(m.color).convertLinearToSRGB();+ const texSampler = buildTextureSampler(m);const index = geo.index;const triCount = index ? index.count / 3 : pos.count / 3;for (let t = 0; t < triCount; t++) {@@ -48,11 +96,15 @@ function gatherTriangles(meshes) {const a = _v.a.fromBufferAttribute(pos, i0).applyMatrix4(mesh.matrixWorld).clone();const b = _v.b.fromBufferAttribute(pos, i1).applyMatrix4(mesh.matrixWorld).clone();const c = _v.c.fromBufferAttribute(pos, i2).applyMatrix4(mesh.matrixWorld).clone();- const ca = colAttr ? new THREE.Color().fromBufferAttribute(colAttr, i0) : matColor.clone();- const cb = colAttr ? new THREE.Color().fromBufferAttribute(colAttr, i1) : matColor.clone();- const cc = colAttr ? new THREE.Color().fromBufferAttribute(colAttr, i2) : matColor.clone();+ // Per-vertex colours are linear in three; convert to sRGB for emission.+ const ca = colAttr ? new THREE.Color().fromBufferAttribute(colAttr, i0).convertLinearToSRGB() : matColorSRGB;+ const cb = colAttr ? new THREE.Color().fromBufferAttribute(colAttr, i1).convertLinearToSRGB() : matColorSRGB;+ const cc = colAttr ? new THREE.Color().fromBufferAttribute(colAttr, i2).convertLinearToSRGB() : matColorSRGB;+ const uv = uvAttr && texSampler+ ? [uvAttr.getX(i0), uvAttr.getY(i0), uvAttr.getX(i1), uvAttr.getY(i1), uvAttr.getX(i2), uvAttr.getY(i2)]+ : null;const area = _v.ab.subVectors(b, a).cross(_v.ac.subVectors(c, a)).length() * 0.5;- tris.push({ a, b, c, ca, cb, cc, area });+ tris.push({ a, b, c, ca, cb, cc, uv, texSampler: uv ? texSampler : null, area });}}return tris;@@ -69,19 +121,23 @@ function mulberry32(seed) {};}+const nextTick = () => new Promise((r) => setTimeout(r, 0));+/*** Convert a THREE.Object3D into a `.splat` ArrayBuffer.* @param {THREE.Object3D} object3d- * @param {{count?:number, seed?:number, scale?:number}} [opts]- * @returns {{buffer: ArrayBuffer, count: number}}+ * @param {{count?:number, seed?:number, scale?:number, onProgress?:(pct:number)=>void}} [opts]+ * @returns {Promise<{buffer: ArrayBuffer, count: number, textured: boolean}>}*/-export function meshToSplatBuffer(object3d, opts = {}) {+export async function meshToSplatBuffer(object3d, opts = {}) {const count = Math.max(500, Math.min(200000, Math.floor(opts.count ?? 30000)));const seed = Math.floor(opts.seed ?? 1);+ const onProgress = typeof opts.onProgress === 'function' ? opts.onProgress : null;const meshes = collectMeshes(object3d);if (!meshes.length) throw new Error('No mesh geometry to convert.');const tris = gatherTriangles(meshes);if (!tris.length) throw new Error('No triangles found in the model.');+ const textured = tris.some((t) => t.texSampler);// Cumulative area table for weighted sampling.const cum = new Float64Array(tris.length);@@ -99,7 +155,6 @@ export function meshToSplatBuffer(object3d, opts = {}) {const dv = new DataView(buf);const pickTri = (r) => {- // binary search the cumulative area tablelet lo = 0, hi = tris.length - 1;const target = r * total;while (lo < hi) {@@ -109,21 +164,26 @@ export function meshToSplatBuffer(object3d, opts = {}) {return tris[lo];};+ const CHUNK = 8192; // must be a power of 2 for the (i & (CHUNK-1)) bitmaskfor (let i = 0; i < count; i++) {const tri = pickTri(rnd());// Uniform barycentric sample.let u = rnd(), v = rnd();if (u + v > 1) { u = 1 - u; v = 1 - v; }const w = 1 - u - v;- _v.p.set(0, 0, 0)- .addScaledVector(tri.a, w)- .addScaledVector(tri.b, u)- .addScaledVector(tri.c, v);- _v.cp.setRGB(- tri.ca.r * w + tri.cb.r * u + tri.cc.r * v,- tri.ca.g * w + tri.cb.g * u + tri.cc.g * v,- tri.ca.b * w + tri.cb.b * u + tri.cc.b * v,- );+ _v.p.set(0, 0, 0).addScaledVector(tri.a, w).addScaledVector(tri.b, u).addScaledVector(tri.c, v);++ if (tri.texSampler) {+ const tu = tri.uv[0] * w + tri.uv[2] * u + tri.uv[4] * v;+ const tv = tri.uv[1] * w + tri.uv[3] * u + tri.uv[5] * v;+ tri.texSampler(tu, tv, _v.col);+ } else {+ _v.col.setRGB(+ tri.ca.r * w + tri.cb.r * u + tri.cc.r * v,+ tri.ca.g * w + tri.cb.g * u + tri.cc.g * v,+ tri.ca.b * w + tri.cb.b * u + tri.cc.b * v,+ );+ }const base = i * 32;dv.setFloat32(base, _v.p.x, true);@@ -132,16 +192,21 @@ export function meshToSplatBuffer(object3d, opts = {}) {dv.setFloat32(base + 12, splatScale, true);dv.setFloat32(base + 16, splatScale, true);dv.setFloat32(base + 20, splatScale, true);- dv.setUint8(base + 24, Math.round(THREE.MathUtils.clamp(_v.cp.r, 0, 1) * 255));- dv.setUint8(base + 25, Math.round(THREE.MathUtils.clamp(_v.cp.g, 0, 1) * 255));- dv.setUint8(base + 26, Math.round(THREE.MathUtils.clamp(_v.cp.b, 0, 1) * 255));+ dv.setUint8(base + 24, Math.round(THREE.MathUtils.clamp(_v.col.r, 0, 1) * 255));+ dv.setUint8(base + 25, Math.round(THREE.MathUtils.clamp(_v.col.g, 0, 1) * 255));+ dv.setUint8(base + 26, Math.round(THREE.MathUtils.clamp(_v.col.b, 0, 1) * 255));dv.setUint8(base + 27, 255);- // identity rotation (w,x,y,z) → bytes- dv.setUint8(base + 28, 255);+ dv.setUint8(base + 28, 255); // identity rotation (w,x,y,z) → bytesdv.setUint8(base + 29, 128);dv.setUint8(base + 30, 128);dv.setUint8(base + 31, 128);++ if ((i & (CHUNK - 1)) === CHUNK - 1) {+ if (onProgress) onProgress(Math.round(((i + 1) / count) * 100));+ await nextTick();+ }}+ if (onProgress) onProgress(100);- return { buffer: buf, count };+ return { buffer: buf, count, textured };}diff --git a/src/forge.js b/src/forge.jsindex 8da2fb0c6..14f9e6a98 100644--- a/src/forge.js+++ b/src/forge.js@@ -1374,6 +1374,9 @@ async function pollUntilDone(jobId) {const res = await fetch(`/api/forge?job=${encodeURIComponent(jobId)}`, {headers: forgeHeaders(),});+ if (!res.ok && res.status >= 500) {+ throw new Error(`Status check failed (HTTP ${res.status}) — please try again.`);+ }const data = await res.json().catch(() => ({}));if (data.error === 'unconfigured') {const e = new Error(data.message || 'unconfigured');@@ -1861,6 +1864,7 @@ function showRateLimited({ retryAfter = 10, unavailable = false, busy = false })// Run a job (text or image/multi-view). `cfg` = { prompt, imageUrls }.async function run(cfg) {+ stopRateLimitCountdown();lastJob = cfg;pollAbort = false;currentCreationId = null;@@ -1936,6 +1940,9 @@ async function run(cfg) {els.genPreview.innerHTML = '';els.genPreview.appendChild(img);};+ img.onerror = () => {+ els.genPreview.innerHTML = '';+ };}// The free draft lane (NVIDIA NIM) completes synchronously — the POSTdiff --git a/src/hero-stage.js b/src/hero-stage.jsindex 7ec217dc6..16b1769ea 100644--- a/src/hero-stage.js+++ b/src/hero-stage.js@@ -99,8 +99,9 @@ export class HeroStage {// Post-processing: bloom is ~70% of the look. Keep it generous on the// emissive rings/stars but the threshold is high enough that only the// genuinely bright geometry blooms.+ // The composer inherits the renderer's pixel ratio on construction and+ // rescales every pass by it on setSize — no separate ratio call needed.this.composer = new EffectComposer(this.renderer);- this.composer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));this.composer.setSize(w, h);this.composer.addPass(new RenderPass(this.scene, this.camera));this.bloom = new UnrealBloomPass(new Vector2(w, h), 0.9, 0.7, 0.2);@@ -268,8 +269,10 @@ export class HeroStage {const h = this._cssHeight();if (!w || !h) return;this.renderer.setSize(w, h, false);+ // composer.setSize already resizes every pass (incl. bloom) by the+ // pixel ratio — calling bloom.setSize again here would override it with+ // the un-scaled CSS size and soften the glow on hi-DPI screens.this.composer.setSize(w, h);- this.bloom.setSize(w, h);this.camera.aspect = w / h;this.camera.updateProjectionMatrix();if (this._reduced) this._composeStatic();diff --git a/src/ibm-galaxy.js b/src/ibm-galaxy.jsindex 5ae1d2931..b8a885872 100644--- a/src/ibm-galaxy.js+++ b/src/ibm-galaxy.js@@ -651,11 +651,16 @@ function applySearchResults(query, data) {applyVisibility();renderResults(query, data.results || []);+ // Clear all search highlights before applying the new best result.+ aHi.fill(0);+ state.selected = -1;+ geometry.attributes.aHi.needsUpdate = true;+const best = data.best && state.byId.get(data.best.id);if (best) {const idx = state.agents.indexOf(best);flyTo(new THREE.Vector3(best.x, best.y, best.z), 64);- if (idx >= 0) { aHi[idx] = 1; state.selected = -1; geometry.attributes.aHi.needsUpdate = true; }+ if (idx >= 0) { aHi[idx] = 1; geometry.attributes.aHi.needsUpdate = true; }}}diff --git a/src/irl.js b/src/irl.jsindex 7b441c6c7..4821e5a94 100644--- a/src/irl.js+++ b/src/irl.js@@ -1350,6 +1350,9 @@ function deviceHeaders(extra = {}) {const glassesBridge = new GlassesBridge();const gpsState = { lat: null, lng: null, ready: false, watchId: null, accuracy: null, altitude: null };+window.addEventListener('pagehide', () => {+ if (gpsState.watchId != null) { navigator.geolocation.clearWatch(gpsState.watchId); gpsState.watchId = null; }+}, { once: true });// DEV-only simulated-location guard (L1). Always false in production — the mock// machinery that flips it lives entirely inside an `import.meta.env.DEV` block and// is tree-shaken out, leaving this as an inert, always-false check. When set, the@@ -3297,7 +3300,7 @@ function setShareGhost(on) {// Compass-referenced facing we report on each heartbeat — the same absolute yaw// placement uses, so a shared ghost is oriented consistently for every viewer.function currentHeadingDeg() {- return ((cameraYaw * 180 / Math.PI) % 360 + 360) % 360;+ return ((-cameraYaw * 180 / Math.PI) % 360 + 360) % 360;}// 15 s heartbeat: proves we're still here (the server's 30 s reaper drops silentdiff --git a/src/kol/radar-fixture.json b/src/kol/radar-fixture.jsondeleted file mode 100644index 050c5c4c9..000000000--- a/src/kol/radar-fixture.json+++ /dev/null@@ -1,82 +0,0 @@-[- {- "mint": "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",- "name": "Mooncat",- "symbol": "MCAT",- "signalType": "pump-fun",- "score": 92,- "ts": 1714300800000- },- {- "mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",- "name": "RocketDoge",- "symbol": "RDOGE",- "signalType": "pump-fun",- "score": 88,- "ts": 1714297200000- },- {- "mint": "So11111111111111111111111111111111111111112",- "name": "SolFloki",- "symbol": "SFLOKI",- "signalType": "pump-fun",- "score": 75,- "ts": 1714293600000- },- {- "mint": "4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R",- "name": "FreshApe",- "symbol": "FAPE",- "signalType": "new-mints",- "score": 85,- "ts": 1714300000000- },- {- "mint": "9n4nbM75f5Ui33ZbPYXn59EwSgE8CGsHtAeTH5YFeJ9E",- "name": "NovaCoin",- "symbol": "NOVA",- "signalType": "new-mints",- "score": 78,- "ts": 1714296400000- },- {- "mint": "2FPyTwcZLUgjTrXjX7sHFxCB2pDV3tNVBUwWnDUZaRqo",- "name": "ZeroGrav",- "symbol": "ZGRAV",- "signalType": "new-mints",- "score": 61,- "ts": 1714292800000- },- {- "mint": "3uetDDizgTtadDHZzyy9yWe3TwFmkpAfwzeut5HkPeRZ",- "name": "TurboVol",- "symbol": "TVOL",- "signalType": "volume-spike",- "score": 97,- "ts": 1714301000000- },- {- "mint": "THREEsynthetic1111111111111111111111111111",- "name": "SpikeKing",- "symbol": "SPKNG",- "signalType": "volume-spike",- "score": 91,- "ts": 1714299500000- },- {- "mint": "mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So",- "name": "PumpBurst",- "symbol": "PBURST",- "signalType": "volume-spike",- "score": 83,- "ts": 1714295000000- },- {- "mint": "7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs",- "name": "AlphaRaid",- "symbol": "ARAID",- "signalType": "volume-spike",- "score": 70,- "ts": 1714291000000- }-]diff --git a/src/kol/radar.js b/src/kol/radar.jsdeleted file mode 100644index f0a9677af..000000000--- a/src/kol/radar.js+++ /dev/null@@ -1,24 +0,0 @@-// Refresh: paste the latest gmgn radar JSON over src/kol/radar-fixture.json.-// Each entry must have: { mint, name, symbol, signalType, score, ts }.--import fixtureData from './radar-fixture.json' with { type: 'json' };--const MAX_LIMIT = 100;-const VALID_CATEGORIES = new Set(['pump-fun', 'new-mints', 'volume-spike']);--/**- * @param {{ category?: string, limit?: number }} opts- * @returns {{ mint: string, name: string, symbol: string, signalType: string, score: number, ts: number }[]}- */-export async function getRadarSignals({ category = 'pump-fun', limit = 20 } = {}) {- if (!VALID_CATEGORIES.has(category)) {- throw new Error(`Unknown category "${category}". Valid: ${[...VALID_CATEGORIES].join(', ')}`);- }-- const cap = Math.min(Math.max(1, limit), MAX_LIMIT);-- return fixtureData- .filter((entry) => entry.signalType === category)- .sort((a, b) => b.score - a.score)- .slice(0, cap);-}diff --git a/src/marketplace.js b/src/marketplace.jsindex e6620c712..29dfcecd7 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -4605,8 +4605,12 @@ async function loadDetail(id) {// Optimistically render from cached list item if available, then refresh from API.const cached = state.items.find((item) => item.id === id);if (cached) {- detailState = { agent: cached, bookmarked: false };- renderDetail(cached, false);+ // Seed the optimistic bookmark state from the client-side source of truth+ // (loaded with the user's bookmarks) so a star click during the refresh+ // window picks the correct DELETE/POST method instead of always adding.+ const bmOn = bookmarkedAgents.has(id);+ detailState = { agent: cached, bookmarked: bmOn };+ renderDetail(cached, bmOn);} else {showDetailState('loading');}@@ -4635,6 +4639,9 @@ async function loadDetail(id) {fetch(`${API}/marketplace/agents/${id}/versions`).then((r) => (r.ok ? r.json() : null)).catch(() => null),fetch(`${API}/marketplace/agents/${id}/similar`).then((r) => (r.ok ? r.json() : null)).catch(() => null),]).then(([versionsRes, similarRes]) => {+ // Guard against a stale response: if the user has since opened a+ // different agent, don't paint this one's versions/similar over it.+ if (detailState?.agent?.id !== id) return;const versions = versionsRes?.data?.items || versionsRes?.data?.versions || [];renderVersions(versions);const similar = similarRes?.data?.items || similarRes?.data?.similar || [];diff --git a/src/payment-modal.js b/src/payment-modal.jsindex 8e7ff1693..98d4f4b25 100644--- a/src/payment-modal.js+++ b/src/payment-modal.js@@ -16,6 +16,12 @@ import { log } from './shared/log.js';const USDC_DECIMALS = 6;+function escHtml(s) {+ return String(s == null ? '' : s)+ .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')+ .replace(/"/g, '"').replace(/'/g, ''');+}+// Lazy-load Solana modules via bundled npm deps. Dynamic import keeps the// Solana SDKs out of the initial chunk; Vite splits them into their own// asset that's only fetched when a payment actually happens.@@ -346,6 +352,10 @@ export class SkillPaymentModal {// Step 2: Build + sign + send the SPL transferthis._setStatus('Building transaction…');const txStartMs = Date.now();+ // Once the transfer is broadcast the money is in flight — any later error+ // (confirm timeout, server mismatch) must NOT re-arm the pay button, or the+ // user pays a second time. Only pre-broadcast failures are retryable.+ let broadcast = false;try {const { web3, spl } = await loadSolana();const { Connection, PublicKey, Transaction } = web3;@@ -383,15 +393,18 @@ export class SkillPaymentModal {const ix = createTransferInstruction(fromAta, toAta, payerKey, BigInt(purchase.amount));ix.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });- const { blockhash } = await this._connection.getLatestBlockhash('confirmed');+ const { blockhash, lastValidBlockHeight } = await this._connection.getLatestBlockhash('confirmed');const tx = new Transaction({ feePayer: payerKey, recentBlockhash: blockhash }).add(ix);this._setStatus('Approve in wallet…');const wallet = this._wallet || window.solana;const txid = await wallet.sendTransaction(tx, this._connection);+ broadcast = true;this._setStatus('Waiting for confirmation…');- await this._connection.confirmTransaction(txid, 'confirmed');+ // Bind confirmation to the blockhash's expiry so a dropped tx fails fast+ // instead of polling the signature for the full default timeout.+ await this._connection.confirmTransaction({ signature: txid, blockhash, lastValidBlockHeight }, 'confirmed');this._setStatus('Verifying with server…');const ok = await this._pollConfirm(purchase.reference);@@ -416,10 +429,18 @@ export class SkillPaymentModal {log.warn('[three.ws] payment-modal purchase error:', e);const msg = e.message || '';const payerAddr = (this._wallet?.publicKey || window.solana?.publicKey)?.toBase58?.() || null;+ // After broadcast the transfer is irreversible — present a terminal state+ // and leave the pay button disabled so the user can't double-pay.+ if (broadcast) {+ if (e?.code === 'mismatch') {+ this._setStatus('Payment was sent but didn\'t match the expected amount or recipient. Don\'t pay again — contact support with this transaction.', 'err');+ } else {+ this._setStatus('Payment was sent but couldn\'t be confirmed in time. Don\'t pay again — check your wallet, and contact support if funds were deducted.', 'err');+ }+ return;+ }if (/reject|denied|cancel|user.*declin/i.test(msg)) {this._setStatus('Transaction cancelled — try again whenever you\'re ready.', 'err');- } else if (msg === 'verification_failed') {- this._setStatus('Payment may have gone through but couldn\'t be verified. Contact support if funds were deducted.', 'err');} else if (/insufficient|balance|funds/i.test(msg)) {this._showInsufficientFunds(payerAddr, purchase?.amount, null, confirm);return;@@ -441,7 +462,13 @@ export class SkillPaymentModal {});const j = await r.json().catch(() => ({}));if (r.ok && j.data?.status === 'confirmed') return true;- if (r.status === 409) throw new Error(j.error_description || 'Transfer mismatch');+ if (r.status === 409) {+ // Definitive server verdict: the on-chain transfer didn't match.+ // Tag it so the caller renders a terminal "don't pay again" state.+ const err = new Error(j.error_description || 'Transfer mismatch');+ err.code = 'mismatch';+ throw err;+ }await delay(2500);}return false;@@ -488,8 +515,8 @@ export class PaymentChip {<div class="pay-chip-head"><span class="pay-chip-label">Payment required</span></div>- <div class="pay-chip-skill">${skill}</div>- <div class="pay-chip-price">${amountUsdc} ${currency}<span class="usd-eq" hidden></span></div>+ <div class="pay-chip-skill">${escHtml(skill)}</div>+ <div class="pay-chip-price">${escHtml(amountUsdc)} ${escHtml(currency)}<span class="usd-eq" hidden></span></div><div class="pay-chip-actions"></div><div class="pay-chip-status"></div></div>@@ -516,7 +543,7 @@ export class PaymentChip {const connected = this._wallet?.isConnected || window.solana?.isConnected;if (connected) {actions.innerHTML = `- <button class="pay-chip-btn pay-chip-btn-pay">Pay ${amountUsdc} ${currency}</button>+ <button class="pay-chip-btn pay-chip-btn-pay">Pay ${escHtml(amountUsdc)} ${escHtml(currency)}</button><button class="pay-chip-btn pay-chip-btn-cancel">Cancel</button>`;actions.querySelector('.pay-chip-btn-pay').addEventListener('click', () => runPurchase());@@ -616,6 +643,9 @@ export class PaymentChip {if (payBtn) payBtn.disabled = false;};+ // Once broadcast, the transfer is irreversible — never re-arm the pay+ // button on a later error, or the user double-pays.+ let broadcast = false;try {const { web3, spl } = await loadSolana();const { Connection, PublicKey, Transaction } = web3;@@ -651,15 +681,16 @@ export class PaymentChip {const ix = createTransferInstruction(fromAta, toAta, payerKey, BigInt(purch.amount));ix.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });- const { blockhash } = await this._connection.getLatestBlockhash('confirmed');+ const { blockhash, lastValidBlockHeight } = await this._connection.getLatestBlockhash('confirmed');const tx = new Transaction({ feePayer: payerKey, recentBlockhash: blockhash }).add(ix);- setStatus('Approve in Phantom…');+ setStatus('Approve in your wallet…');const wallet = this._wallet || window.solana;const txid = await wallet.sendTransaction(tx, this._connection);+ broadcast = true;setStatus('Confirming…');- await this._connection.confirmTransaction(txid, 'confirmed');+ await this._connection.confirmTransaction({ signature: txid, blockhash, lastValidBlockHeight }, 'confirmed');setStatus('Verifying…');const ok = await this._pollConfirm(purch.reference);@@ -685,10 +716,18 @@ export class PaymentChip {} catch (e) {log.warn('[three.ws] payment-chip purchase error:', e);const msg = e.message || '';+ // After broadcast the money is in flight — terminal state, pay+ // button stays disabled so the user can't pay a second time.+ if (broadcast) {+ if (e?.code === 'mismatch') {+ setStatus('Payment was sent but didn\'t match the expected amount or recipient. Don\'t pay again — contact support with this transaction.', 'err');+ } else {+ setStatus('Payment was sent but couldn\'t be confirmed in time. Don\'t pay again — check your wallet, and contact support if funds were deducted.', 'err');+ }+ return;+ }if (/reject|denied|cancel|user.*declin/i.test(msg)) {setStatus('Transaction cancelled — try again whenever you\'re ready.', 'err');- } else if (msg === 'verification_failed') {- setStatus('Payment may have gone through but couldn\'t be verified. Contact support if funds were deducted.', 'err');} else if (/insufficient|balance|funds/i.test(msg)) {showChipAddFunds(purch?.amount, null);return;@@ -716,7 +755,11 @@ export class PaymentChip {});const j = await r.json().catch(() => ({}));if (r.ok && j.data?.status === 'confirmed') return true;- if (r.status === 409) throw new Error(j.error_description || 'Transfer mismatch');+ if (r.status === 409) {+ const err = new Error(j.error_description || 'Transfer mismatch');+ err.code = 'mismatch';+ throw err;+ }await delay(2500);}return false;diff --git a/src/pose-studio.js b/src/pose-studio.jsindex ab7036764..28607b012 100644--- a/src/pose-studio.js+++ b/src/pose-studio.js@@ -572,7 +572,10 @@ function boot() {syncIKHandles();}function clearIKHandles() {- for (const m of state.ikHandles.values()) ikLayer.remove(m);+ for (const m of state.ikHandles.values()) {+ ikLayer.remove(m);+ m.material?.dispose();+ }state.ikHandles.clear();}function syncIKHandles() {@@ -777,20 +780,24 @@ function boot() {await ensureDecoders();setStatus(`Loading ${meta.name || 'avatar'}…`);state.loadingAvatar = true;- const gltf = await new Promise((resolve, reject) => {- gltfLoader.load(- modelUrl,- resolve,- (xhr) => {- if (xhr.total) {- const pct = Math.round((xhr.loaded / xhr.total) * 100);- setStatus(`Loading ${meta.name || 'avatar'}… ${pct}%`);- }- },- reject,- );- });- state.loadingAvatar = false;+ let gltf;+ try {+ gltf = await new Promise((resolve, reject) => {+ gltfLoader.load(+ modelUrl,+ resolve,+ (xhr) => {+ if (xhr.total) {+ const pct = Math.round((xhr.loaded / xhr.total) * 100);+ setStatus(`Loading ${meta.name || 'avatar'}… ${pct}%`);+ }+ },+ reject,+ );+ });+ } finally {+ state.loadingAvatar = false;+ }const scn = gltf.scene || gltf.scenes?.[0];const rig = scn && makeGltfRig(scn);if (!rig) {@@ -1004,6 +1011,14 @@ function boot() {);btn.addEventListener('click', () => {state.prop = id;+ if (state.propGroup) {+ state.propGroup.traverse((n) => {+ n.geometry?.dispose();+ if (Array.isArray(n.material)) n.material.forEach((m) => m.dispose());+ else n.material?.dispose();+ });+ state.propGroup = null;+ }propLayer.clear();if (def.build) {const g = def.build();diff --git a/src/profile-walk-hero.js b/src/profile-walk-hero.jsindex 8325305de..6d9c0a00f 100644--- a/src/profile-walk-hero.js+++ b/src/profile-walk-hero.js@@ -26,7 +26,11 @@ const esc = (s) =>/[&<>"']/g,(c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],);-const attr = (s) => esc(s).replace(/"/g, '"');+const attr = (s) =>+ String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );let stylesInjected = false;diff --git a/src/pump/mcp-tools.js b/src/pump/mcp-tools.jsindex d5b838605..12d098c28 100644--- a/src/pump/mcp-tools.js+++ b/src/pump/mcp-tools.js@@ -82,7 +82,6 @@ export const TOOL_ANNOTATIONS = Object.freeze({get_new_tokens: { title: 'New Tokens', ...LIVE_READ },get_graduated_tokens: { title: 'Graduated Tokens', ...LIVE_READ },get_king_of_the_hill: { title: 'King of the Hill', ...LIVE_READ },- kol_radar: { title: 'KOL Radar', ...LIVE_READ },get_creator_profile: { title: 'Creator Profile', ...LIVE_READ },get_token_holders: { title: 'Token Holders', ...LIVE_READ },pumpfun_vanity_mint: { title: 'Vanity Mint Keypair', ...LOCAL_GENERATIVE },@@ -218,22 +217,6 @@ export const TOOLS = [description: 'Highest-market-cap token still on the bonding curve.',inputSchema: { type: 'object', properties: {} },},- {- name: 'kol_radar',- description:- 'gmgn radar signals: early-detection patterns filtered by category, sorted by score desc.',- inputSchema: {- type: 'object',- properties: {- category: {- type: 'string',- enum: ['pump-fun', 'new-mints', 'volume-spike'],- default: 'pump-fun',- },- limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 },- },- },- },{name: 'get_creator_profile',description: 'All tokens by a creator wallet, with rug-pull risk flags.',diff --git a/src/selfie-pipeline.js b/src/selfie-pipeline.jsindex 20d5f955b..528fabdd8 100644--- a/src/selfie-pipeline.js+++ b/src/selfie-pipeline.js@@ -461,6 +461,19 @@ function fit(w, h, max) {*/function mapApiError(status, payload) {const code = payload.error;+ // BYOK-specific errors must be checked before the generic 401/402 handlers.+ if (status === 401 && (code === 'invalid_key' || code === 'missing_key')) {+ clearStoredByokKey();+ return withMessage(+ new Error(code),+ 'Your API key was rejected. Check the key and try again.',+ );+ }+ if (status === 402 && code === 'insufficient_credits')+ return withMessage(+ new Error(code),+ 'Your API key is out of credits. Top up your account and try again.',+ );if (status === 401) {// Return to /create/selfie so the post-login round-trip resumes on the right page.const here = typeof location !== 'undefined' ? location.pathname : '/create/selfie';@@ -487,18 +500,6 @@ function mapApiError(status, payload) {/** @type {any} */ (e).rateLimited = true;return e;}- if (status === 401 && (code === 'invalid_key' || code === 'missing_key')) {- clearStoredByokKey();- return withMessage(- new Error(code),- 'Your API key was rejected. Check the key and try again.',- );- }- if (status === 402 && code === 'insufficient_credits')- return withMessage(- new Error(code),- 'Your API key is out of credits. Top up your account and try again.',- );if (status === 501)return withMessage(new Error(code || 'not_configured'),diff --git a/src/shared/safe-model-url.js b/src/shared/safe-model-url.jsnew file mode 100644index 000000000..0073a2acf--- /dev/null+++ b/src/shared/safe-model-url.js@@ -0,0 +1,29 @@+import { isDecentralizedURI } from '../ipfs.js';++// Hosts we trust to serve avatar/model GLBs. Anchored so only these domains+// (and their subdomains) match — never a substring like `three.ws.evil.com`.+export const TRUSTED_ASSET_HOST_RE = /(^|\.)(three\.ws|r2\.dev|mypinata\.cloud|pinata\.cloud|ipfs\.io|dweb\.link|arweave\.net)$/i;++/**+ * Whether a `?model=` URL is safe to fetch/render under the three.ws origin.+ * Accepts same-origin relative paths, decentralized URIs (ipfs:// / ar://),+ * and https URLs on the trusted asset hosts. Everything else is rejected so a+ * three.ws page can't be turned into an open relay that renders attacker GLBs.+ *+ * @param {unknown} raw+ * @returns {boolean}+ */+export function isSafeQueryModelUrl(raw) {+ if (!raw || typeof raw !== 'string') return false;+ if (raw.startsWith('/') && !raw.startsWith('//')) return true; // same-origin relative+ if (isDecentralizedURI(raw)) return true; // ipfs:// / ar://+ try {+ const u = new URL(raw, location.origin);+ if (u.origin === location.origin) return true;+ if (u.protocol !== 'https:') return false;+ if (u.hostname === 'storage.googleapis.com') return true;+ return TRUSTED_ASSET_HOST_RE.test(u.hostname);+ } catch {+ return false;+ }+}diff --git a/src/studio/agent-presence.js b/src/studio/agent-presence.jsindex 6af4da290..ac3da7184 100644--- a/src/studio/agent-presence.js+++ b/src/studio/agent-presence.js@@ -274,25 +274,37 @@ class AgentPresenceElement extends HTMLElement {async _refreshBody() {if (!this._viewer || this._disposed) return;- const resolved = await this._resolveBody();- if (this._disposed || !this._viewer) return;- if (!resolved) {- this._handleNoBody();- return;- }- this.hidden = false;- if (resolved === this._currentModelUrl) return;- this._setStatus('loading');+ // Guard against concurrent refresh calls (rapid store patches). If already+ // refreshing, queue one follow-up so the last state wins without piling up.+ if (this._refreshing) { this._pendingRefresh = true; return; }+ this._refreshing = true;try {- const { Viewer } = await import('../viewer.js');- const { AgentAvatar } = await import('../agent-avatar.js');- this._avatar?.detach();- this._avatar = null;- await this._loadModel(resolved, Viewer, AgentAvatar);- this._setStatus('live');- } catch (err) {- log.warn('[agent-presence] body refresh failed', err);- this._setStatus('error');+ const resolved = await this._resolveBody();+ if (this._disposed || !this._viewer) return;+ if (!resolved) {+ this._handleNoBody();+ return;+ }+ this.hidden = false;+ if (resolved === this._currentModelUrl) return;+ this._setStatus('loading');+ try {+ const { Viewer } = await import('../viewer.js');+ const { AgentAvatar } = await import('../agent-avatar.js');+ this._avatar?.detach();+ this._avatar = null;+ await this._loadModel(resolved, Viewer, AgentAvatar);+ this._setStatus('live');+ } catch (err) {+ log.warn('[agent-presence] body refresh failed', err);+ this._setStatus('error');+ }+ } finally {+ this._refreshing = false;+ if (this._pendingRefresh && !this._disposed) {+ this._pendingRefresh = false;+ this._refreshBody();+ }}}@@ -450,7 +462,10 @@ class AgentPresenceElement extends HTMLElement {}status.setAttribute('data-show', '1');if (state === 'no-body') {- inner.innerHTML = `<div>No body yet</div><a class="cta" href="/agent-studio#body">Give it a body →</a>`;+ inner.innerHTML = `<div>No avatar yet</div><button class="cta" type="button">Set up in Body tab →</button>`;+ inner.querySelector('.cta')?.addEventListener('click', () => {+ document.dispatchEvent(new CustomEvent('studio:navigate', { detail: { tab: 'body' } }));+ });} else if (state === 'error') {inner.innerHTML = `<div>Couldn't load the avatar.</div><button class="retry" type="button">Try again</button>`;inner.querySelector('.retry')?.addEventListener('click', () => {diff --git a/src/studio/agent-studio-store.js b/src/studio/agent-studio-store.jsindex fc840db7d..d4e28a40e 100644--- a/src/studio/agent-studio-store.js+++ b/src/studio/agent-studio-store.js@@ -103,11 +103,18 @@ class AgentStudioStore {async load({ agentId = null } = {}) {if (this._loadPromise) return this._loadPromise;this._loadPromise = (async () => {- this.identity = new AgentIdentity({ agentId, autoLoad: false });- await this.identity.load();- this._record = this._snapshotFromIdentity();- this._notify();- return this._record;+ try {+ this.identity = new AgentIdentity({ agentId, autoLoad: false });+ await this.identity.load();+ this._record = this._snapshotFromIdentity();+ this._notify();+ return this._record;+ } catch (err) {+ // Clear so the next load() call retries rather than returning this stale+ // rejected promise forever (which would break the shell's retry button).+ this._loadPromise = null;+ throw err;+ }})();return this._loadPromise;}diff --git a/src/studio/brain/brain-graph.js b/src/studio/brain/brain-graph.jsindex 05df4a3a6..d7a866b24 100644--- a/src/studio/brain/brain-graph.js+++ b/src/studio/brain/brain-graph.js@@ -93,6 +93,7 @@ export class BrainGraphView {const spec = NODE_TYPES[node.type];const list = dir === 'out' ? spec.outputs : spec.inputs;const idx = list.findIndex((p) => p.id === portId);+ if (idx === -1) return null; // stale edge referencing a port removed from the specconst y = node.y + HEADER_H + idx * PORT_ROW + PORT_ROW / 2 + PORT_PAD / 2;const x = dir === 'out' ? node.x + NODE_W : node.x;return { x, y };@@ -160,6 +161,7 @@ export class BrainGraphView {if (!fromNode || !toNode) continue;const a = this._portAnchor(fromNode, e.fromPort, 'out');const b = this._portAnchor(toNode, e.toPort, 'in');+ if (!a || !b) continue; // port removed from spec; normalizeGraph will drop it on next loadparts.push(`<path class="bedge" data-id="${e.id}" d="${this._curve(a, b)}" />`);parts.push(`<path class="bedge-hit" data-id="${e.id}" d="${this._curve(a, b)}" />`);}@@ -186,9 +188,8 @@ export class BrainGraphView {e.stopPropagation();if (portEl.dataset.dir === 'out') this._startLink(e, node, portEl);});- portEl.addEventListener('pointerup', (e) => {- if (portEl.dataset.dir === 'in') this._completeLink(e, node, portEl);- });+ // Connection on in-ports is handled by _startLink's global pointerup via+ // elementFromPoint — no per-port listener needed here.});}@@ -217,6 +218,7 @@ export class BrainGraphView {const a = this._portAnchor(node, portEl.dataset.port, 'out');const ghost = document.createElementNS('http://www.w3.org/2000/svg', 'path');ghost.setAttribute('class', 'bedge bedge--ghost');+ ghost.setAttribute('pointer-events', 'none'); // must not intercept elementFromPoint at releasethis.svg.appendChild(ghost);this._linking = { from: node.id, fromPort: portEl.dataset.port, kind, a, ghost };this.host.querySelector('#bgHint').textContent = `Connecting ${kind} — drop on a matching input`;@@ -227,7 +229,6 @@ export class BrainGraphView {const up = (ev) => {window.removeEventListener('pointermove', move);window.removeEventListener('pointerup', up);- // If released over an input port, _completeLink already ran; clean up ghost.const target = document.elementFromPoint(ev.clientX, ev.clientY);const portTarget = target?.closest?.('.bport--in');if (portTarget) {@@ -242,8 +243,6 @@ export class BrainGraphView {window.addEventListener('pointerup', up);}- _completeLink() { /* handled in _startLink's pointerup via elementFromPoint */ }-_tryConnect(toId, toPort, toKind) {if (!this._linking || !toId) return;const { from, fromPort, kind } = this._linking;diff --git a/src/studio/brain/brain-runtime.js b/src/studio/brain/brain-runtime.jsindex bf125c384..32d926b66 100644--- a/src/studio/brain/brain-runtime.js+++ b/src/studio/brain/brain-runtime.js@@ -52,9 +52,14 @@ export class BrainRuntime {const graph = this.getGraph();const nodeOf = (type) => graph.nodes.find((n) => n.type === type);+ // Create the AbortController up-front so P4 runners (step 3) and the stream+ // (step 4) share the same signal and can all be cancelled together.+ this._abort = new AbortController();+gv.clearActive();const circuit = gv.circuit();gv.setActive(circuit.nodeIds, circuit.edgeIds);+ const circuitIds = new Set(circuit.nodeIds);// 1. Persona lights up first.const personaNode = nodeOf('persona');@@ -85,7 +90,9 @@ export class BrainRuntime {}// 3. Skill / market nodes — P4 runners if registered (reasoning-only otherwise).- for (const node of graph.nodes.filter((n) => n.type === 'skill' || n.type === 'market')) {+ // Only nodes wired into the live circuit: orphaned nodes are inert by design+ // (they contribute nothing to the compiled system prompt either).+ for (const node of graph.nodes.filter((n) => circuitIds.has(n.id) && (n.type === 'skill' || n.type === 'market'))) {const runner = getNodeRunner(node.type);if (!runner) continue;gv.setNodeBusy(node.id, true);@@ -188,7 +195,8 @@ export class BrainRuntime {// ── SSE stream from /api/brain/chat ─────────────────────────────────────────async _stream({ provider, system, messages, maxTokens, onMeta, onFirst, onToken, onDone }) {- this._abort = new AbortController();+ // _abort was already created in run() before step 3, so P4 runners and this+ // stream share the same signal. Don't recreate it here.const resp = await apiFetch('/api/brain/chat', {method: 'POST',headers: { 'content-type': 'application/json' },diff --git a/src/studio/brain/brain-studio.js b/src/studio/brain/brain-studio.jsindex b41dc49be..8313bbfef 100644--- a/src/studio/brain/brain-studio.js+++ b/src/studio/brain/brain-studio.js@@ -53,12 +53,17 @@ class BrainStudio {if (resp.ok) this.providers = (await resp.json()).providers || [];} catch { /* picker falls back to a static list of model ids */ }- const stored = this.studio.brain?.graph;- if (stored) {- this._showEditor();- this.graph.load(normalizeGraph(stored));- } else {- this._showOnboarding();+ // Don't overwrite a graph the user started editing during the async provider+ // fetch above (e.g. they clicked a template while we were awaiting). Only+ // apply the stored state if no editing has begun yet.+ if (this.root?.dataset.view !== 'editor') {+ const stored = this.studio.brain?.graph;+ if (stored) {+ this._showEditor();+ this.graph.load(normalizeGraph(stored));+ } else {+ this._showOnboarding();+ }}}@@ -101,6 +106,10 @@ class BrainStudio {</div></aside></div>+ <div class="brainstudio__footer">+ <span class="brainstudio__footer-save" id="bsFooterSave">Auto-saved</span>+ <button class="studio__btn studio__btn-primary brainstudio__footer-continue" id="bsContinue">Save & continue →</button>+ </div></div><div class="brainstudio__modal" id="bsModal" hidden>@@ -117,6 +126,7 @@ class BrainStudio {this.el.querySelector('#bsTpl').addEventListener('click', () => this._showTemplateModal());this.el.querySelector('#bsSave').addEventListener('click', () => this._saveNow());this.el.querySelector('#bsDone').addEventListener('click', () => this._done());+ this.el.querySelector('#bsContinue').addEventListener('click', () => this._done());this.el.querySelector('#bsCompose').addEventListener('submit', (e) => { e.preventDefault(); this._send(); });const input = this.el.querySelector('#bsInput');input.addEventListener('keydown', (e) => { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); this._send(); } });@@ -141,6 +151,20 @@ class BrainStudio {// means an explicit save/exit captures the latest wiring, not the last tick.this._flushHandler = () => { if (this.graph) this._onGraphChange(this.graph.toGraph(), { immediate: true }); };document.addEventListener('studio:flush', this._flushHandler);++ // Footer save-state indicator — mirrors the shell header but anchored at the+ // bottom of the canvas so it's visible while the user's eyes are on the graph.+ this._unsubFooterPending = this.studio.on('save:pending', () => this._setFooterSave('saving'));+ this._unsubFooterOk = this.studio.on('save:ok', () => this._setFooterSave('saved'));+ this._unsubFooterErr = this.studio.on('error', () => this._setFooterSave('error'));+ }++ _setFooterSave(state) {+ const el = this.el.querySelector('#bsFooterSave');+ if (!el) return;+ const map = { saving: 'Saving…', saved: 'Saved ✓', error: 'Save failed' };+ el.textContent = map[state] || 'Auto-saved';+ el.dataset.state = state;}// True only when the Brain tab is the active (non-hidden) studio panel — keeps@@ -180,12 +204,18 @@ class BrainStudio {}// Save, then hand off to the next studio section so building a brain flows- // naturally into Memory rather than dead-ending on the graph.+ // naturally into Memory rather than dead-ending on the graph. Both the toolbar+ // #bsDone and the footer #bsContinue buttons invoke this, so we disable both+ // during the write to prevent double-submit.async _done() {- // Only advance once the write actually lands — a failed save rolls back in the- // store, so navigating away on failure would silently drop the user's edits.- if (await this._saveNow()) {+ const btns = ['#bsDone', '#bsContinue'].map((s) => this.el.querySelector(s)).filter(Boolean);+ if (btns.some((b) => b.dataset.busy)) return;+ btns.forEach((b) => { b.dataset.busy = '1'; b.disabled = true; b.textContent = 'Saving…'; });+ const ok = await this._saveNow({ silent: true });+ if (ok) {document.dispatchEvent(new CustomEvent('studio:navigate', { detail: { tab: 'memory' } }));+ } else {+ btns.forEach((b) => { b.disabled = false; b.textContent = 'Retry'; delete b.dataset.busy; });}}diff --git a/src/studio/brain/brain-templates.js b/src/studio/brain/brain-templates.jsindex 6dee4f117..f25155797 100644--- a/src/studio/brain/brain-templates.js+++ b/src/studio/brain/brain-templates.js@@ -58,7 +58,7 @@ export const TEMPLATES = [nodes: [{ key: 'p', type: 'persona', x: 60, y: 90, data: { role: 'a meticulous research analyst', tone: 'thorough, neutral, evidence-led', risk: 'cautious', vocabulary: ['evidence', 'tradeoff', 'hypothesis'], avoid: ['hype', 'certainty without basis'], greeting: 'What should we dig into?' } },{ key: 'mem', type: 'memory', x: 60, y: 340, data: { topK: 8, minScore: 0.7, write: true } },- { key: 'm', type: 'model', x: 430, y: 190, data: { provider: 'claude-opus-4-7', maxTokens: 2000 } },+ { key: 'm', type: 'model', x: 430, y: 190, data: { provider: 'claude-opus-4-8', maxTokens: 2000 } },{ key: 'o', type: 'output', x: 800, y: 210, data: { speak: true, emotion: true, lipsync: true } },],edges: [['p', 'identity', 'm', 'identity'], ['mem', 'recall', 'm', 'context'], ['m', 'reply', 'o', 'reply']],diff --git a/src/studio/memory/memory-studio.js b/src/studio/memory/memory-studio.jsindex 3e2f1da0b..5bb89822e 100644--- a/src/studio/memory/memory-studio.js+++ b/src/studio/memory/memory-studio.js@@ -343,7 +343,7 @@ class MemoryStudio {</div><div class="mem-card-content" data-act="expand">${esc(m.content)}</div><div class="mem-card-foot">- <div class="mem-tags">${tags.map((t) => `<span class="mem-tag" data-tag="${esc(t)}">${esc(t)}</span>`).join('')}</div>+ <div class="mem-tags">${tags.map((t) => `<span class="mem-tag" data-act="tag" data-tag="${esc(t)}">${esc(t)}</span>`).join('')}</div><div class="mem-sal"><input class="mem-sal-range" type="range" min="0" max="100" value="${sal}" data-act="salience" aria-label="Salience" /><span class="mem-sal-val">${(m.salience || 0).toFixed(2)}</span>@@ -556,8 +556,6 @@ class MemoryStudio {if (a === 'retry') return this._load();if (a === 'seed') return this._openSeed();if (a === 'add') return this._openAddForm();- if (a === 'search-back') { this.state.search = null; return this._renderBody(); }- if (a === 'entity-back') { this.state.entity = null; return this._renderBody(); }}const act = e.target.closest('[data-act]');if (!act) return;@@ -684,6 +682,8 @@ class MemoryStudio {const n = this.state.selection.size;bar.hidden = !this.state.mergeMode || n < 1;this._q('[data-merge-count]').textContent = `${n} selected`;+ const mergeBtn = bar.querySelector('[data-action="merge-commit"]');+ if (mergeBtn) mergeBtn.disabled = n < 2;}async _commitMerge() {diff --git a/src/studio/studio-shell.js b/src/studio/studio-shell.jsindex 5a7e15907..ca2c12201 100644--- a/src/studio/studio-shell.js+++ b/src/studio/studio-shell.js@@ -181,7 +181,7 @@ class StudioShell {title="Save your progress now — your agent stays a private draft you can keep editing">Save draft</button><a class="studio-btn studio-btn-ghost studio-action" id="studio-exit"href="${agent.id ? `/agent/${encodeURIComponent(agent.id)}` : '/'}"- title="Save and leave the Studio — opens your live agent">Exit ↗</a>+ title="Save and view your live agent page">View agent ↗</a></div></header>@@ -249,7 +249,7 @@ class StudioShell {saveEl.dataset.state = 'pending';});this._unsubSaved = studio.on('save:ok', () => {- if (!saveEl || saveEl.dataset.state === 'error') return;+ if (!saveEl) return;saveEl.textContent = 'Saved';saveEl.dataset.state = 'saved';});diff --git a/src/swap-jupiter.js b/src/swap-jupiter.jsindex be5aa33a0..5e8bcb185 100644--- a/src/swap-jupiter.js+++ b/src/swap-jupiter.js@@ -532,9 +532,9 @@ function updateConfirmButton() {if (!_ctx) { btn.disabled = true; return; }const amount = Number($('sj-from-amount').value);if (!_quote || !amount || amount <= 0) {- btn.disabled = !amount || amount <= 0 ? true : false;- btn.textContent = (amount && amount > 0) ? 'Get quote' : 'Enter amount';- btn.disabled = !(_quote && amount > 0);+ const hasAmount = amount > 0;+ btn.disabled = !hasAmount;+ btn.textContent = hasAmount ? 'Get quote' : 'Enter amount';return;}btn.disabled = false;diff --git a/src/trades.js b/src/trades.jsindex e19db0a85..e115403f5 100644--- a/src/trades.js+++ b/src/trades.js@@ -322,6 +322,7 @@ function cardHtml(t) {const agentName = escapeHtml(t.agent_name || shortAddr(t.agent_id || ''));const traderUrl = `/trader/${escapeHtml(t.agent_id || '')}`;+ const pumpUrl = t.mint ? `https://pump.fun/${escapeHtml(t.mint)}` : null;const coinHref = t.mint && t.oracle_score != null ? `/oracle?mint=${escapeHtml(t.mint)}` : (pumpUrl || '#');const coinTarget = t.oracle_score != null ? '' : ' target="_blank" rel="noopener"';const imgHtml = `<a href="${coinHref}"${coinTarget} class="tf-coin-img-link" aria-label="View ${sym} conviction on Oracle" style="display:block;line-height:0">${imgSrc@@ -352,7 +353,6 @@ function cardHtml(t) {const scoreStr = t.oracle_score != null ? `Score ${Math.round(t.oracle_score)}` : '';- const pumpUrl = t.mint ? `https://pump.fun/${escapeHtml(t.mint)}` : null;const oracleUrl = t.mint && t.oracle_score != null ? `/oracle?mint=${escapeHtml(t.mint)}` : null;const buySig = t.buy_sig ? `https://solscan.io/tx/${escapeHtml(t.buy_sig)}` : null;const sellSig = t.sell_sig ? `https://solscan.io/tx/${escapeHtml(t.sell_sig)}` : null;diff --git a/src/viewer.js b/src/viewer.jsindex 57b017fca..2d6b1b585 100644--- a/src/viewer.js+++ b/src/viewer.js@@ -2,8 +2,10 @@ import {AudioListener,AxesHelper,Box3,+ BufferAttribute,BufferGeometry,Cache,+ CanvasTexture,Color,GridHelper,LoaderUtils,@@ -12,6 +14,7 @@ import {Mesh,PMREMGenerator,PerspectiveCamera,+ Points,PointsMaterial,Scene,SkeletonHelper,@@ -60,6 +63,31 @@ Mesh.prototype.raycast = acceleratedRaycast;Cache.enabled = true;+// Draw a small gold coin sprite on a canvas for the pump.fun trade shower, so the+// effect is self-contained (no external image asset to 404). A fresh texture is+// returned each call; the caller owns disposal.+function makeCoinTexture() {+ const size = 64;+ const canvas = document.createElement('canvas');+ canvas.width = canvas.height = size;+ const ctx = canvas.getContext('2d');+ const r = size / 2;+ const grad = ctx.createRadialGradient(r * 0.7, r * 0.7, r * 0.2, r, r, r);+ grad.addColorStop(0, '#ffe9a8');+ grad.addColorStop(0.6, '#f4b73d');+ grad.addColorStop(1, '#b9791a');+ ctx.beginPath();+ ctx.arc(r, r, r - 2, 0, Math.PI * 2);+ ctx.fillStyle = grad;+ ctx.fill();+ ctx.lineWidth = 3;+ ctx.strokeStyle = 'rgba(255,243,205,0.85)';+ ctx.stroke();+ const tex = new CanvasTexture(canvas);+ tex.needsUpdate = true;+ return tex;+}+/*** @class Viewer*@@ -672,11 +700,14 @@ export class Viewer {}showPumpFunTrades() {+ // Re-entrant guard: a second call while a shower is live would orphan the+ // first's geometry/material/texture and stack animate hooks.+ if (this._pumpFunFx || this._disposed) return;+const particleCount = 1000;- const particles = new THREE.BufferGeometry();+ const particles = new BufferGeometry();const positions = new Float32Array(particleCount * 3);- const textureLoader = new THREE.TextureLoader();- const coinTexture = textureLoader.load('assets/coin.png');+ const coinTexture = makeCoinTexture();for (let i = 0; i < particleCount; i++) {positions[i * 3] = (Math.random() * 2 - 1) * 10;@@ -684,24 +715,24 @@ export class Viewer {positions[i * 3 + 2] = (Math.random() * 2 - 1) * 10;}- particles.setAttribute('position', new THREE.BufferAttribute(positions, 3));+ particles.setAttribute('position', new BufferAttribute(positions, 3));- const particleMaterial = new THREE.PointsMaterial({+ const particleMaterial = new PointsMaterial({map: coinTexture,size: 0.5,transparent: true,alphaTest: 0.5,});- const particleSystem = new THREE.Points(particles, particleMaterial);+ const particleSystem = new Points(particles, particleMaterial);this.scene.add(particleSystem);const animateParticles = () => {- const positions = particleSystem.geometry.attributes.position.array;+ const pos = particleSystem.geometry.attributes.position.array;for (let i = 0; i < particleCount; i++) {- positions[i * 3 + 1] -= 0.1;- if (positions[i * 3 + 1] < -10) {- positions[i * 3 + 1] = 20;+ pos[i * 3 + 1] -= 0.1;+ if (pos[i * 3 + 1] < -10) {+ pos[i * 3 + 1] = 20;}}particleSystem.geometry.attributes.position.needsUpdate = true;@@ -713,13 +744,29 @@ export class Viewer {}this._afterAnimateHooks.push(animateParticles);- setTimeout(() => {- this.scene.remove(particleSystem);- const index = this._afterAnimateHooks.indexOf(animateParticles);- if (index > -1) {- this._afterAnimateHooks.splice(index, 1);- }- }, 10000);+ this._pumpFunFx = { particleSystem, particles, particleMaterial, coinTexture, animateParticles };+ this._pumpFunTimer = setTimeout(() => this._clearPumpFunTrades(), 10000);+ }++ // Tear down the pump.fun coin shower: detach the animate hook, remove from the+ // scene, and dispose every GPU resource it allocated. Idempotent.+ _clearPumpFunTrades() {+ if (this._pumpFunTimer) {+ clearTimeout(this._pumpFunTimer);+ this._pumpFunTimer = null;+ }+ const fx = this._pumpFunFx;+ if (!fx) return;+ this._pumpFunFx = null;+ if (this._afterAnimateHooks) {+ const index = this._afterAnimateHooks.indexOf(fx.animateParticles);+ if (index > -1) this._afterAnimateHooks.splice(index, 1);+ }+ this.scene.remove(fx.particleSystem);+ fx.particles.dispose();+ fx.particleMaterial.dispose();+ fx.coinTexture.dispose();+ this.invalidate();}takeScreenshot() {@@ -2005,6 +2052,7 @@ export class Viewer {window.removeEventListener('message', this._onMessage, false);}if (this._cameraTweenRaf) cancelAnimationFrame(this._cameraTweenRaf);+ this._clearPumpFunTrades();if (this._onAnimHotkey) {document.removeEventListener('keydown', this._onAnimHotkey);this._onAnimHotkey = null;diff --git a/src/walk-companion-click-to-walk.js b/src/walk-companion-click-to-walk.jsindex e94b9043a..56e93cc78 100644--- a/src/walk-companion-click-to-walk.js+++ b/src/walk-companion-click-to-walk.js@@ -647,6 +647,7 @@ export function installClickToWalk({ getInstance, getHostEl, storageKey } = {})// Inject the settings toggle once the host exists (poll briefly after mount),// and re-inject after avatar swaps / playground round-trips replace the host.let tries = 0;+ let wireTimer = null;const tryInject = () => {const host = (() => {try {@@ -656,11 +657,12 @@ export function installClickToWalk({ getInstance, getHostEl, storageKey } = {})}})();if (host) injectToggle(host);- if (tries++ < 600) setTimeout(tryInject, 500); // keep re-asserting on swaps+ if (tries++ < 600) wireTimer = setTimeout(tryInject, 500); // keep re-asserting on swaps};tryInject();return function uninstall() {+ clearTimeout(wireTimer);document.removeEventListener('click', onClickCapture, { capture: true });document.removeEventListener('touchstart', onTouchStart, { capture: true });document.removeEventListener('touchmove', onTouchMove, { capture: true });diff --git a/src/wallet.js b/src/wallet.jsindex 92542a0bf..108f4a7d1 100644--- a/src/wallet.js+++ b/src/wallet.js@@ -102,3 +102,7 @@ export function getConnectedWallet() {export function getConnectedWalletAddress() {return connectedWalletAddress;}++export function connectWallet() {+ return onConnectWallet();+}diff --git a/tests/api/pump-fun-mcp.test.js b/tests/api/pump-fun-mcp.test.jsindex df1bdd55c..9ea08ff22 100644--- a/tests/api/pump-fun-mcp.test.js+++ b/tests/api/pump-fun-mcp.test.js@@ -172,15 +172,15 @@ describe('tools/list', () => {for (const n of INDEXER_TOOL_NAMES) expect(names).not.toContain(n);// …but the always-on metadata tool is.expect(names).toContain('pumpfun_bot_status');- // 26 total declared − 6 indexer tools = 20 advertised.- expect(json.result.tools).toHaveLength(20);+ // 25 total declared − 6 indexer tools = 19 advertised.+ expect(json.result.tools).toHaveLength(19);for (const t of json.result.tools) expect(t.inputSchema.type).toBe('object');});- it('advertises all 26 tools (incl. indexer tools) when the bot is configured', async () => {+ it('advertises all 25 tools (incl. indexer tools) when the bot is configured', async () => {pumpfunBotEnabled.mockReturnValue(true);const { json } = await call({ jsonrpc: '2.0', id: 1, method: 'tools/list' });- expect(json.result.tools).toHaveLength(26);+ expect(json.result.tools).toHaveLength(25);const names = json.result.tools.map((t) => t.name);for (const n of INDEXER_TOOL_NAMES) expect(names).toContain(n);expect(names).toContain('pumpfun_bot_status');diff --git a/tests/kol-radar.test.js b/tests/kol-radar.test.jsdeleted file mode 100644index 036111218..000000000--- a/tests/kol-radar.test.js+++ /dev/null@@ -1,51 +0,0 @@-import { describe, it, expect } from 'vitest';-import { getRadarSignals } from '../src/kol/radar.js';--describe('getRadarSignals', () => {- it('returns default pump-fun category sorted by score desc', async () => {- const results = await getRadarSignals();- expect(results.length).toBeGreaterThan(0);- results.forEach((r) => expect(r.signalType).toBe('pump-fun'));- for (let i = 1; i < results.length; i++) {- expect(results[i - 1].score).toBeGreaterThanOrEqual(results[i].score);- }- });-- it('filters by volume-spike category', async () => {- const results = await getRadarSignals({ category: 'volume-spike' });- expect(results.length).toBeGreaterThan(0);- results.forEach((r) => expect(r.signalType).toBe('volume-spike'));- });-- it('filters by new-mints category', async () => {- const results = await getRadarSignals({ category: 'new-mints' });- expect(results.length).toBeGreaterThan(0);- results.forEach((r) => expect(r.signalType).toBe('new-mints'));- });-- it('caps limit at 100', async () => {- const results = await getRadarSignals({ category: 'pump-fun', limit: 1000 });- expect(results.length).toBeLessThanOrEqual(100);- });-- it('respects explicit limit smaller than available entries', async () => {- const results = await getRadarSignals({ category: 'volume-spike', limit: 2 });- expect(results.length).toBeLessThanOrEqual(2);- });-- it('result entries have required fields', async () => {- const results = await getRadarSignals({ category: 'new-mints' });- results.forEach((r) => {- expect(r).toHaveProperty('mint');- expect(r).toHaveProperty('name');- expect(r).toHaveProperty('symbol');- expect(r).toHaveProperty('signalType');- expect(r).toHaveProperty('score');- expect(r).toHaveProperty('ts');- });- });-- it('throws on unknown category', async () => {- await expect(getRadarSignals({ category: 'unknown' })).rejects.toThrow(/Unknown category/);- });-});diff --git a/tour-sdk/src/chapters.js b/tour-sdk/src/chapters.jsindex 1c816d540..e34829d5e 100644--- a/tour-sdk/src/chapters.js+++ b/tour-sdk/src/chapters.js@@ -106,7 +106,7 @@ export class ChapterPanel {this.trackSeg.innerHTML = tracks.map((t) =>- `<button class="tws-tour-seg__btn" data-val="${t.id}" role="radio" aria-checked="false" title="${esc(t.description || '')}">${esc(t.title.replace(/ tour| highlights/i, ''))}${t.estimatedMinutes ? ` · ~${t.estimatedMinutes}m` : ''}</button>`,+ `<button class="tws-tour-seg__btn" data-val="${t.id}" role="radio" aria-checked="false" title="${esc(t.description || '')}">${esc((t.title || '').replace(/ tour| highlights/i, ''))}${t.estimatedMinutes ? ` · ~${t.estimatedMinutes}m` : ''}</button>`,).join('');this.speedSeg.innerHTML = SPEEDS.map(diff --git a/tour-sdk/src/curriculum.js b/tour-sdk/src/curriculum.jsindex a102e530f..5dc56a3d6 100644--- a/tour-sdk/src/curriculum.js+++ b/tour-sdk/src/curriculum.js@@ -12,22 +12,22 @@// sequencing logic and tests can use them freely. The IO/state surface is bound// to a host's config through createTourState() / loadCurriculum().-let _cache = null;+const _cache = new Map();// Load the curriculum from config.curriculum — either an inline object (used as-// is) or a URL to fetch (cached after the first successful load).+// is) or a URL to fetch (cached per URL after the first successful load).export async function loadCurriculum(config) {const source = config?.curriculum ?? '/tour/curriculum.json';if (source && typeof source === 'object') {assertCurriculum(source);return source;}- if (_cache) return _cache;+ if (_cache.has(source)) return _cache.get(source);const res = await fetch(source, { cache: 'force-cache' });if (!res.ok) throw new Error(`tour curriculum ${res.status}`);const data = await res.json();assertCurriculum(data);- _cache = data;+ _cache.set(source, data);return data;}diff --git a/tour-sdk/src/director.js b/tour-sdk/src/director.jsindex e42e4ee1d..9c2007278 100644--- a/tour-sdk/src/director.js+++ b/tour-sdk/src/director.js@@ -455,8 +455,10 @@ export class TourDirector {await this.avatar.park();this.avatar.point();await this._present(this.config.copy.outro, token);+ if (token !== this._runToken) return;this.state.markCompleted();this.state.clearState();+ document.removeEventListener('keydown', this._onKey);this._showCompletion();}diff --git a/vercel.json b/vercel.jsonindex c63510f45..664b3eab8 100644--- a/vercel.json+++ b/vercel.json@@ -2544,6 +2544,10 @@"src": "/api/users/referrals","dest": "/api/users/referrals.js"},+ {+ "src": "/api/users/referral-code",+ "dest": "/api/users/referral-code.js"+ },{"src": "/api/users/referral-claim","dest": "/api/users/referral-claim.js"@@ -3468,6 +3472,14 @@"src": "/scan/","dest": "/scan.html"},+ {+ "src": "/dad",+ "dest": "/dad.html"+ },+ {+ "src": "/dad/",+ "dest": "/dad.html"+ },{"src": "/worlds/?","dest": "/worlds.html"diff --git a/vite.config.js b/vite.config.jsindex 90c4f3417..8f3c339aa 100644--- a/vite.config.js+++ b/vite.config.js@@ -310,6 +310,7 @@ const appConfig = {create: resolve(__dirname, 'pages/create.html'),'create-agent': resolve(__dirname, 'pages/create-agent.html'),forge: resolve(__dirname, 'pages/forge.html'),+ dad: resolve(__dirname, 'pages/dad.html'),'forge-studio': resolve(__dirname, 'pages/forge-studio.html'),'forge-embed': resolve(__dirname, 'pages/forge-embed.html'),scene: resolve(__dirname, 'pages/scene.html'),@@ -840,6 +841,8 @@ support: resolve(__dirname, 'pages/support.html'),'/pose/': resolve(root, 'pages/pose.html'),'/club': resolve(root, 'pages/club.html'),'/club/': resolve(root, 'pages/club.html'),+ '/dad': resolve(root, 'pages/dad.html'),+ '/dad/': resolve(root, 'pages/dad.html'),'/agenc/embodied': resolve(root, 'pages/agenc/embodied.html'),'/agenc/embodied/': resolve(root, 'pages/agenc/embodied.html'),'/agenc/room': resolve(root, 'pages/agenc/room.html'),diff --git a/walk-sdk/src/companion.js b/walk-sdk/src/companion.jsindex 4d83fffa1..0cccf2c6d 100644--- a/walk-sdk/src/companion.js+++ b/walk-sdk/src/companion.js@@ -588,7 +588,7 @@ export function createWalkCompanion(opts = {}) {emitChange();},toggle() {- if (isEnabled() && instance && instance.mounted) control.disable();+ if (isEnabled()) control.disable();else control.enable();},setAvatar(idOrEntry) {diff --git a/walk-sdk/src/picker.js b/walk-sdk/src/picker.jsindex 529c58c62..18f7f0172 100644--- a/walk-sdk/src/picker.js+++ b/walk-sdk/src/picker.js@@ -104,10 +104,11 @@ export function createAvatarPicker(opts) {const orbStyle = entry.thumb? ` style="background-image:url('${assetBase}${entry.thumb}')"`: '';- btn.innerHTML = `- <span class="walk-picker-orb"${orbStyle}>${entry.thumb ? '' : entry.emoji || '🧍'}</span>- <span class="walk-picker-name">${entry.name}</span>- `;+ btn.innerHTML = `<span class="walk-picker-orb"${orbStyle}>${entry.thumb ? '' : entry.emoji || '🧍'}</span>`;+ const nameSpan = document.createElement('span');+ nameSpan.className = 'walk-picker-name';+ nameSpan.textContent = entry.name;+ btn.appendChild(nameSpan);btn.addEventListener('click', () => choose(entry));return btn;}diff --git a/walk-sdk/src/playground.js b/walk-sdk/src/playground.jsindex 12ed6e339..5422ce2b6 100644--- a/walk-sdk/src/playground.js+++ b/walk-sdk/src/playground.js@@ -328,6 +328,7 @@ class StrollPlayground {this._teardown();return;}+ if (!this.mounted) { this._teardown(); return; }this._placeStart(startScreen, dropIn);this._spawnGuardUntil = performance.now() + SPAWN_GUARD_MS;this._bindEvents();@@ -786,6 +787,7 @@ class PlatformerPlayground {this._teardown();return;}+ if (!this.mounted) { this._teardown(); return; }this._scrollY = window.scrollY || 0;this._scan(true);this._placeStart(startScreen, dropIn);diff --git a/workers/agent-sniper/intel/classify.js b/workers/agent-sniper/intel/classify.jsindex cfbaefb34..966ec33aa 100644--- a/workers/agent-sniper/intel/classify.js+++ b/workers/agent-sniper/intel/classify.js@@ -71,11 +71,14 @@ export function heuristicClassify({ name, symbol, description } = {}) {const SYSTEM = `You are a pump.fun coin classifier. Given a coin's name, symbol, and description, classify it precisely. Be literal and grounded — do not hype. Output ONLY strict JSON, no prose.`;function buildUser({ name, symbol, description, twitter, telegram, website }) {+ // Truncate and XML-delimit each field so a token creator can't inject LLM+ // instructions via a crafted coin name/description and force a mis-classify.+ const safe = (s, max) => String(s || '').slice(0, max);return `Classify this pump.fun coin.-Name: ${name || '(none)'}-Symbol: ${symbol || '(none)'}-Description: ${description || '(none)'}+<name>${safe(name, 64) || '(none)'}</name>+<symbol>${safe(symbol, 10) || '(none)'}</symbol>+<description>${safe(description, 300) || '(none)'}</description>Has socials: ${[twitter && 'twitter', telegram && 'telegram', website && 'website'].filter(Boolean).join(', ') || 'none'}Output strict JSON:diff --git a/workers/agent-sniper/intel/store.js b/workers/agent-sniper/intel/store.jsindex a03c89b01..c6409414e 100644--- a/workers/agent-sniper/intel/store.js+++ b/workers/agent-sniper/intel/store.js@@ -128,10 +128,11 @@ async function persistWallets(sql, mint, creator, walletAgg) {const rows = [...walletAgg.entries()].sort((a, b) => (b[1].buyLamports + b[1].sellLamports) - (a[1].buyLamports + a[1].sellLamports)).slice(0, 200);- try {- for (const [wallet, w] of rows) {- // funder is written by the funding-graph enrichment step in watcher.js- const funder = w.funder || null;+ let failed = 0;+ for (const [wallet, w] of rows) {+ // funder is written by the funding-graph enrichment step in watcher.js+ const funder = w.funder || null;+ try {await sql`insert into pump_coin_wallets (mint, wallet, buy_count, sell_count, buy_lamports, sell_lamports,@@ -150,10 +151,12 @@ async function persistWallets(sql, mint, creator, walletAgg) {last_seen_at = excluded.last_seen_at,funder = coalesce(excluded.funder, pump_coin_wallets.funder)`;+ } catch (err) {+ failed++;+ if (failed === 1) console.warn('[coin-intel] persist wallet row failed:', err?.message);}- } catch (err) {- console.warn('[coin-intel] persist wallets failed:', err?.message);}+ if (failed > 0) console.warn(`[coin-intel] persist wallets: ${failed}/${rows.length} rows failed for mint ${mint}`);}/** Read one coin's intel — cache first, then DB. */diff --git a/workers/oracle/executor.js b/workers/oracle/executor.jsindex 0ce16f0bc..783dd2452 100644--- a/workers/oracle/executor.js+++ b/workers/oracle/executor.js@@ -20,7 +20,7 @@ const JITO_TIP_ACCOUNTS = ['96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5','HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe','Cw8CFyM9FkoMi7K7Crf6HNQqf4uEMzpKw6QNghXLvLkY',- 'ADaUMid9yfUytqMBgopwjb2DTLSokTSzL1zt13UZKZr',+ 'ADaUMid9yfUytqMBgopwjb2DTLSokTSzL1zt13UZKZr1','DfXygSm4jCyNCybVYYK6DwvWqjKee8pbDmJGcLWNDXjh','ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt','DttWaMuVvTiduZRnguLF7jNxTgiMBZ1hyAumKUiL2KRL',@@ -131,7 +131,13 @@ async function buyOnPump({ network, mint, solAmount, payer, useJito = false, jitconst tx = new VersionedTransaction(msg);tx.sign([payer]);const sig = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });- const conf = await connection.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');+ // confirmTransaction can stall indefinitely under cluster congestion — race it+ // against a hard timeout so a stuck confirm never blocks the oracle agent loop.+ const CONFIRM_TIMEOUT_MS = 60_000;+ const conf = await Promise.race([+ connection.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed'),+ new Promise((_, reject) => setTimeout(() => reject(new Error(`oracle tx ${sig} confirm timed out after ${CONFIRM_TIMEOUT_MS}ms`)), CONFIRM_TIMEOUT_MS)),+ ]);// confirmTransaction resolves for a tx that landed-but-reverted; the on-chain// error is in value.err, not a thrown exception. Surface it so the executor// never records a reverted oracle execution as a confirmed one.@@ -174,6 +180,7 @@ async function buyOnPumpJito({ ixs, user, payer, blockhash, jitoTipSol, jitoBundjsonrpc: '2.0', id: 1, method: 'sendBundle',params: [[bs58.encode(tx.serialize())]],}),+ signal: AbortSignal.timeout(15_000),});if (!res.ok) throw new Error(`Jito HTTP ${res.status}`);const json = await res.json();diff --git a/workers/pump-fun-mcp/worker.js b/workers/pump-fun-mcp/worker.jsindex 3aab0207d..c3b24c712 100644--- a/workers/pump-fun-mcp/worker.js+++ b/workers/pump-fun-mcp/worker.js@@ -146,10 +146,10 @@ async function handleGetTokenDetails({ mint, network = 'mainnet' }, env) {const buf = Buffer.from(metaInfo.data);let cursor = 1 + 32 + 32;const readStr = (max) => {- const len = buf.readUInt32LE(cursor);+ const len = Math.min(buf.readUInt32LE(cursor), max);cursor += 4;const slice = buf.slice(cursor, cursor + len);- cursor += max;+ cursor += len;return slice.toString('utf8').replace(/\0+$/g, '').trim();};name = readStr(32);