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
feat: walk landing/leaderboard/analytics, social feed, and lazy-image CI gate
nirholas226987747eb4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 8cb85b8f5..e749be484 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -58,6 +58,10 @@ jobs:# Fail if `npx vercel build` ever clobbered an api/*.js source file with# an esbuild bundle (a documented footgun in this repo).- run: node scripts/check-api-not-bundled.mjs+ # Every JS-rendered <img> must declare loading= so off-fold feed/grid+ # images defer their fetch+decode. Keeps scroll perf from regressing as+ # new components ship. Bulk-fix: node scripts/codemod-lazy-images.mjs+ - run: npm run check:images# Regenerates and validates the public changelog/page index; the script# fails the build on a malformed changelog entry. Run as a validation# gate only — the generated changelog.json is not byte-deterministic, sodiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 37a6f304a..88bb11081 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,7 +10,9 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **$THREE holder leaderboard loads faster from a shared snapshot** — The $THREE holder leaderboard, its share card, and the token stats panel used to rescan every holder on-chain on each page view. They now read from a holder snapshot that refreshes every few minutes, so the board and badges load faster and the same numbers stay consistent across all three surfaces. (`/leaderboard`) `[improvement, infra]`- **Authorize $THREE once, then pay with no wallet popups** — The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set. You can see what your remaining cap covers, get a heads-up when it runs low, top it up, or revoke it in one click anytime. Prefer to sign each payment? Just leave it off. (`/three-token`) `[feature]`- **Authorize $THREE once, then pay with no wallet popups** — The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set, and you can let it expire or revoke it anytime. Set a cap, top it up, or leave it off and keep signing each payment — your choice. (`/three-token`) `[feature]`+- **Clearer empty state on the $THREE live-trades feed** — Before the next trade lands, the live-trades panel on the $THREE token page now reads in plain language — 'Live trades will appear here' — with a short note on what it shows, and the technical detail tucked behind an info tooltip. Screen readers announce new trades as they stream in. (`/three-token`) `[improvement]`- **Discover and character feeds load faster under heavy traffic** — The Discover grid and the published-agents (Characters) feed now serve from the edge cache, so a surge of visitors is absorbed at the CDN instead of re-running a database scan on every request. Pages stay fast and consistent even during a rush, and a stale-while-revalidate window keeps them warm between refreshes. (`/discover`) `[improvement, infra]`+- **Empty pages now guide you instead of going blank** — Across the dashboard and marketplace, anywhere a list can be empty now explains what belongs there, why it's useful, and the next step — instead of a bare 'No data' line. Your Agents, Avatars, Analytics, Brain, embed policies, the marketplace, and My Agents each greet a fresh account with a short plain-language intro and a clear button to create your first one (plus a 'What's an agent?' link). Filtered searches that return nothing now say so and offer to clear the filter. It's the same designed component everywhere, so the whole platform feels consistent and never abandoned. (`/dashboard`) `[improvement]`- **Every Forge quality tier now runs on free engines** — Forge's quality tiers — Draft, Standard, and High — all generate on zero-cost engines now: Draft and Standard on the fast free NVIDIA lane, and High on the higher-fidelity, fully textured free HuggingFace engine. Higher tiers buy you genuinely better geometry and textures, not a different bill behind the scenes. Photo-to-3D at any tier routes straight to a free engine too, so a generation never quietly falls back to a paid lane. The High tier stays a $THREE holder perk (or a one-off pay-per-use) — that's the price of premium quality, not a cost we're passing through. (`/forge`) `[improvement, feature]`- **Forge hardened for a traffic surge — faster loads, protected free lanes** — We scaled Forge for the influx of new users. The engine catalog and live health status now serve from the edge cache, so the page loads instantly even under heavy traffic instead of recomputing on every visit. We also added a platform-wide safety valve on paid generation: if demand ever spikes past the shared paid budget, the free engines (NVIDIA and Hugging Face) stay fully open and you get a clear 'try a free engine' message instead of a hard failure — your own bring-your-own-key engines are never affected. Net result: Forge stays fast and available as we grow, and free 3D generation never gets crowded out. (`/forge`) `[infra, improvement]`- **Forge scales further — duplicate generations collapse, free lane protected, prices shown up front** — More headroom for the influx. Forge now recognizes when the same prompt or photo set is already generating and quietly hands everyone the same result instead of paying to build it twice — so a viral prompt or a double-click no longer multiplies cost or wait. The free Hugging Face engine is now capped to a safe number of simultaneous jobs so a rush can't tie up the servers and stall everyone; over the cap, your generation cleanly falls back to another engine instead of hanging. The composer now shows the real price before you generate — 'Free' for Draft and Standard, the exact dollar amount (or 'Free, you hold $THREE') for High, and 'billed to your own key' for bring-your-own-key engines — so there are no surprises. The engine picker also gained a small legend explaining the badges at a glance — which engines are free, which use your own key, and which are busy or unavailable. And the 3D viewer now shows a loading shimmer instead of a dark void while your model paints in. (`/forge`) `[improvement, infra]`@@ -20,7 +22,9 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Grind an agent's vanity wallet right on its page — with your CPU cores** — Giving an agent a custom wallet address used to run on our servers, so it was capped at short patterns and would time out and error on anything harder. Now the agent's Wallet → Vanity tab grinds the address in your own browser, exactly like the standalone /vanity-wallet tool: choose how many CPU cores to spend, match case-insensitively for a faster find, watch the live tries-per-second and ETA, and pause or resume anytime. Longer, rarer patterns are now possible with no timeouts. When a match is found, any SOL or tokens in the old wallet are still automatically swept to the new address before the key is swapped — funds are never stranded — and the server verifies the new address truly matches your pattern before storing it. `[fix, feature, improvement]`- **Hardened on-chain confirmations and faster profile loads** — Two reliability fixes for everyone trading, launching, and browsing. First: every on-chain action that moves funds — coin launches, buys and sells, buybacks, payouts, transfers — now treats a transaction that lands but reverts as a real failure instead of quietly reporting success. You'll see an accurate error and your spending limit won't be charged for a trade that didn't go through. Second: public profile and creator pages are now cacheable at the edge, so they load noticeably faster under load. No action needed — these apply automatically. `[fix, security, improvement]`- **Live market feed stays up through provider blips** — The trending-tokens feed that powers the home card, communities, the token constellation, and the 3D visualizer is now resilient to upstream outages. If a market data provider goes down or rate-limits us, we transparently fall back to a second source; if both are briefly unavailable, the surfaces keep showing the last good data (clearly marked as a moment stale) instead of going blank. We also added a fast-fail circuit breaker so a slow provider can't drag the feed down during a traffic spike. Net effect: the live market views stay populated and snappy even when a data provider hiccups. `[infra, improvement]`+- **Payment hardening and a steadier holder leaderboard** — Two behind-the-scenes reliability and safety fixes. Agent payment invoices now verify that the wallet paying is actually linked to your account before an invoice is created, closing a gap that let bogus payment requests be generated against any agent. And the $THREE holder leaderboard, its share card, and the token stats panel no longer each kick off a full on-chain holder scan during a traffic spike — one scan now serves everyone and refreshes the shared snapshot, so the leaderboard stays fast and responsive under load. Nothing to do on your end. (`/leaderboard`) `[security, fix, infra]`- **Platform-wide hardening: payment integrity, security, and scale** — A broad reliability pass across the parts of three.ws that move real money and serve heavy traffic. On the money side: bundle purchases and agent payments are now verified on-chain before anything unlocks, each payment is credited exactly once, withdrawals can't be processed twice, and recurring subscriptions can't be double-billed. On the security side: a set of input-handling and link-safety fixes across pages, stronger protection for custodial keys at rest, and tighter checks on outbound agent payments so funds only ever move in the expected asset. On the scale side: the busiest directory, profile, and feed pages now ride a short cache and run far fewer database queries, so they stay fast as the community grows. Most of this is invisible by design — it's the plumbing that keeps the platform correct and quick under load. `[security, improvement, infra]`+- **Profiles you can edit — and follow** — Your three.ws profile at three.ws/u/<your-username> is now a real social home. Edit it in place: add a bio, a profile picture and banner image, your location, and a website link — all from an Edit button on your own profile. You can now follow other creators and agents, and they can follow you; every profile shows live follower and following counts you can tap to browse the lists, with one-tap follow buttons throughout. And there's a new Feed at three.ws/feed that gathers the latest avatars, agents, and coin launches from everyone you follow, newest first. Find your profile and Feed links from your account page. (`/feed`) `[feature]`- **Provably-fair vanity grinder now listed in the x402 bazaar** — The provably-fair Solana vanity grinder — which returns a signed, independently-verifiable receipt proving the key was ground fresh and never kept — is now published in the x402 discovery catalog, so paying agents and bazaar crawlers can find and call it directly. (`/vanity/verify`) `[feature, sdk]`- **Regrinding an agent's vanity wallet no longer risks its funds** — The compact "Vanity address" card on an agent's page used to replace a wallet by deleting the old one and creating the new one separately — so if the old wallet held SOL or tokens, they could be left behind. It now uses the same money-safe path as the rest of the platform: any balance is automatically swept to the new vanity address first, and the switch only completes once the funds have moved (and only after the server confirms the new address really matches your pattern). Same one-click experience, but your funds follow the wallet. `[fix, security]`- **Smoother landing page on hover** — The homepage's parallax hero and 3D stack-card glow used to read the page layout on every pointer move, which could make the cursor feel sticky on the first page new visitors see. Those effects now batch their work to one frame at a time, so hover and tilt stay buttery on any device. (`/`) `[improvement]`diff --git a/api/_lib/migrations/20260621140000_walk_metrics.sql b/api/_lib/migrations/20260621140000_walk_metrics.sqlnew file mode 100644index 000000000..24399f201--- /dev/null+++ b/api/_lib/migrations/20260621140000_walk_metrics.sql@@ -0,0 +1,100 @@+-- Walk metrics, events, and achievements.+--+-- Powers two product surfaces from one ingest pipeline (POST /api/walk/metrics):+-- · /walk-leaderboard — public gamified ranking of walkers by distance, sites+-- visited, and time spent walking, over daily / weekly / all-time windows.+-- · /walk-analytics — per-creator dashboard for the embedded walking avatar:+-- sessions, average duration, distance, unique embed origins, a conversion+-- funnel of creator-defined events, and the top embed locations.+--+-- A "walker" is attributed to the signed-in user when a session/bearer is present+-- and otherwise to a stable anonymous id (anon_id) the client supplies. Either+-- column may be null but never both — enforced by the check constraint below.+--+-- Rollup model: client batches arrive every ~60s (and on pagehide via+-- sendBeacon). Rather than store one row per frame, each batch UPSERTs into a+-- per-(walker, day, environment, embed origin) rollup row, so the leaderboard and+-- analytics aggregate over a compact, indexed table no matter how long anyone+-- walks. `day` is the UTC date the batch landed; period windows are derived from+-- it at read time.+--+-- Fully idempotent — safe to re-run. Mirrored into api/_lib/schema.sql.++-- ── walk_metrics — per-(walker, day, env, origin) rollup ─────────────────────+create table if not exists walk_metrics (+ id bigserial primary key,+ user_id uuid references users(id) on delete cascade,+ anon_id text, -- stable anonymous walker id (client-generated)+ avatar_id uuid references avatars(id) on delete set null,+ day date not null, -- UTC date the batch landed+ env_id text, -- walk environment name (park, void, …)+ embed_origin text, -- iframe host the avatar walked on (server-derived)+ site_hostname text, -- extension-reported host the avatar piloted+ distance_meters double precision not null default 0,+ duration_sec double precision not null default 0,+ sessions integer not null default 0,+ updated_at timestamptz not null default now(),+ created_at timestamptz not null default now(),+ -- A rollup must belong to exactly one walker identity.+ constraint walk_metrics_walker_present check (user_id is not null or anon_id is not null)+);++-- One rollup row per walker identity × day × env × embed origin. The COALESCE'd+-- expression unique index lets the ingest UPSERT target a single row even when+-- some dimensions are null (anonymous walker, no embed origin, etc.) — Postgres+-- treats NULLs as distinct in a plain unique index, which would otherwise spawn a+-- new row per batch and break the rollup.+create unique index if not exists walk_metrics_rollup_uniq+ on walk_metrics (+ coalesce(user_id::text, ''),+ coalesce(anon_id, ''),+ day,+ coalesce(env_id, ''),+ coalesce(embed_origin, ''),+ coalesce(avatar_id::text, '')+ );++-- Leaderboard: sum metrics per walker within a date window.+create index if not exists walk_metrics_user_day on walk_metrics (user_id, day) where user_id is not null;+create index if not exists walk_metrics_anon_day on walk_metrics (anon_id, day) where anon_id is not null;+-- Analytics: per-avatar reads filtered + grouped by day, env, origin.+create index if not exists walk_metrics_avatar_day on walk_metrics (avatar_id, day) where avatar_id is not null;+create index if not exists walk_metrics_origin on walk_metrics (avatar_id, embed_origin) where avatar_id is not null;++-- ── walk_events — creator-defined conversion events fired from the embed SDK ──+-- track('subscribe', { plan:'pro' }) → one row. Aggregated against session counts+-- in the analytics dashboard to compute a conversion rate per event name.+create table if not exists walk_events (+ id bigserial primary key,+ user_id uuid references users(id) on delete set null,+ anon_id text,+ avatar_id uuid references avatars(id) on delete set null,+ event_name text not null,+ value double precision, -- optional numeric value (revenue, plan tier, …)+ embed_origin text, -- server-derived iframe host+ created_at timestamptz not null default now()+);++create index if not exists walk_events_avatar_time on walk_events (avatar_id, created_at desc) where avatar_id is not null;+create index if not exists walk_events_avatar_name on walk_events (avatar_id, event_name) where avatar_id is not null;++-- ── walk_achievements — unlocked badges per walker ───────────────────────────+-- One row per (walker, achievement code). The client fires the toast optimistically+-- on threshold crossing; the server persists the unlock so it is awarded once and+-- can be surfaced on profiles / the leaderboard later.+create table if not exists walk_achievements (+ id bigserial primary key,+ user_id uuid references users(id) on delete cascade,+ anon_id text,+ code text not null, -- distance_1km | sites_10 | all_environments | …+ unlocked_at timestamptz not null default now(),+ constraint walk_achievements_walker_present check (user_id is not null or anon_id is not null)+);++create unique index if not exists walk_achievements_uniq+ on walk_achievements (+ coalesce(user_id::text, ''),+ coalesce(anon_id, ''),+ code+ );+create index if not exists walk_achievements_user on walk_achievements (user_id) where user_id is not null;diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex febdc23ca..40b33851a 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -1783,6 +1783,70 @@ CREATE TABLE IF NOT EXISTS x_scheduled_posts (CREATE INDEX IF NOT EXISTS x_scheduled_posts_pendingON x_scheduled_posts(scheduled_at) WHERE published_at IS NULL;+-- ── walk metrics / events / achievements ────────────────────────────────────+-- See api/_lib/migrations/20260621140000_walk_metrics.sql for the full rationale.+-- Mirrored here so a clean schema.sql apply provisions the walk leaderboard ++-- per-creator analytics pipeline. Ingest: POST /api/walk/metrics. Reads:+-- GET /api/walk/leaderboard and GET /api/walk/analytics.+create table if not exists walk_metrics (+ id bigserial primary key,+ user_id uuid references users(id) on delete cascade,+ anon_id text,+ avatar_id uuid references avatars(id) on delete set null,+ day date not null,+ env_id text,+ embed_origin text,+ site_hostname text,+ distance_meters double precision not null default 0,+ duration_sec double precision not null default 0,+ sessions integer not null default 0,+ updated_at timestamptz not null default now(),+ created_at timestamptz not null default now(),+ constraint walk_metrics_walker_present check (user_id is not null or anon_id is not null)+);+create unique index if not exists walk_metrics_rollup_uniq+ on walk_metrics (+ coalesce(user_id::text, ''),+ coalesce(anon_id, ''),+ day,+ coalesce(env_id, ''),+ coalesce(embed_origin, ''),+ coalesce(avatar_id::text, '')+ );+create index if not exists walk_metrics_user_day on walk_metrics (user_id, day) where user_id is not null;+create index if not exists walk_metrics_anon_day on walk_metrics (anon_id, day) where anon_id is not null;+create index if not exists walk_metrics_avatar_day on walk_metrics (avatar_id, day) where avatar_id is not null;+create index if not exists walk_metrics_origin on walk_metrics (avatar_id, embed_origin) where avatar_id is not null;++create table if not exists walk_events (+ id bigserial primary key,+ user_id uuid references users(id) on delete set null,+ anon_id text,+ avatar_id uuid references avatars(id) on delete set null,+ event_name text not null,+ value double precision,+ embed_origin text,+ created_at timestamptz not null default now()+);+create index if not exists walk_events_avatar_time on walk_events (avatar_id, created_at desc) where avatar_id is not null;+create index if not exists walk_events_avatar_name on walk_events (avatar_id, event_name) where avatar_id is not null;++create table if not exists walk_achievements (+ id bigserial primary key,+ user_id uuid references users(id) on delete cascade,+ anon_id text,+ code text not null,+ unlocked_at timestamptz not null default now(),+ constraint walk_achievements_walker_present check (user_id is not null or anon_id is not null)+);+create unique index if not exists walk_achievements_uniq+ on walk_achievements (+ coalesce(user_id::text, ''),+ coalesce(anon_id, ''),+ code+ );+create index if not exists walk_achievements_user on walk_achievements (user_id) where user_id is not null;+CREATE TABLE IF NOT EXISTS x_pending_reviews (id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,diff --git a/api/users/[username].js b/api/users/[username].jsindex 706819af5..607268ed0 100644--- a/api/users/[username].js+++ b/api/users/[username].js@@ -144,9 +144,7 @@ export default wrap(async (req, res) => {where a.user_id = ${user.id} and a.is_public = true and a.deleted_at is nulland m.is_public = true and (m.expires_at is null or m.expires_at > now())) as memories_count,(select coalesce(sum(view_count), 0)::bigint from widgets- where user_id = ${user.id} and is_public = true and deleted_at is null) as total_widget_views,- (select count(*)::int from user_follows where following_id = ${user.id}) as followers_count,- (select count(*)::int from user_follows where follower_id = ${user.id}) as following_count+ where user_id = ${user.id} and is_public = true and deleted_at is null) as total_widget_views`,]);@@ -256,6 +254,15 @@ export default wrap(async (req, res) => {social[row.provider] = row.username;}+ // Follower/following counts live in their own query so a deploy that lands+ // before the user_follows migration degrades to zeros rather than 500ing+ // every public profile (migrate-then-deploy; see api/_lib/bounty-likes.js).+ const [followCounts] = await sql`+ select+ (select count(*)::int from user_follows where following_id = ${user.id}) as followers,+ (select count(*)::int from user_follows where follower_id = ${user.id}) as following+ `.catch(() => [{ followers: 0, following: 0 }]);+const stats = {avatars: statsRow?.avatars_count ?? 0,agents: statsRow?.agents_count ?? 0,@@ -265,8 +272,8 @@ export default wrap(async (req, res) => {coins: statsRow?.coins_count ?? 0,memories: statsRow?.memories_count ?? 0,widget_views: Number(statsRow?.total_widget_views ?? 0),- followers: statsRow?.followers_count ?? 0,- following: statsRow?.following_count ?? 0,+ followers: followCounts?.followers ?? 0,+ following: followCounts?.following ?? 0,};res.setHeader('Cache-Control', 'public, s-maxage=60, stale-while-revalidate=300');diff --git a/api/users/me/feed.js b/api/users/me/feed.jsnew file mode 100644index 000000000..eff2cdd1b--- /dev/null+++ b/api/users/me/feed.js@@ -0,0 +1,133 @@+// GET /api/users/me/feed — the signed-in viewer's home feed: recent public+// activity from every account they follow, newest first. This is the social-+// graph payoff — following someone means their new avatars, agents, and coin+// launches surface here.+//+// Activity is derived from the same public records the profile page already+// exposes (no separate event log to keep in sync): a new public avatar, a new+// public agent identity, and a coin launched through an agent. Items are merged,+// sorted by created_at desc, and capped.+//+// ?limit=… (1..50, default 30)+//+// Requires a session — the feed is inherently personal. Anonymous callers get+// 401 so the client can route them to sign-in.++import { sql } from '../../_lib/db.js';+import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';+import { getSessionUser } from '../../_lib/auth.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { publicUrl } from '../../_lib/r2.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const viewer = await getSessionUser(req).catch(() => null);+ if (!viewer) return error(res, 401, 'unauthorized', 'sign in to view your feed');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const limit = Math.min(50, Math.max(1, parseInt(req.query.limit, 10) || 30));+ const perKind = limit; // pull `limit` of each kind, then merge + trim to `limit`++ const [{ following_count }] = await sql`+ select count(*)::int as following_count from user_follows where follower_id = ${viewer.id}+ `;++ if (following_count === 0) {+ return json(res, 200, { items: [], following_count: 0 });+ }++ const [avatarRows, agentRows, coinRows] = await Promise.all([+ sql`+ select a.id, a.name, a.thumbnail_key, a.created_at,+ u.username, u.display_name, u.avatar_url+ from avatars a+ join user_follows f on f.following_id = a.owner_id and f.follower_id = ${viewer.id}+ join users u on u.id = a.owner_id and u.deleted_at is null and u.username is not null+ where a.visibility = 'public' and a.deleted_at is null+ order by a.created_at desc+ limit ${perKind}+ `,+ sql`+ select a.id, a.name, a.description, a.profile_image_url, a.avatar_url, a.created_at,+ u.username, u.display_name, u.avatar_url as actor_avatar+ from agent_identities a+ join user_follows f on f.following_id = a.user_id and f.follower_id = ${viewer.id}+ join users u on u.id = a.user_id and u.deleted_at is null and u.username is not null+ where a.is_public = true and a.deleted_at is null+ order by a.created_at desc+ limit ${perKind}+ `,+ sql`+ select a.id as agent_id, a.name as agent_name, a.profile_image_url, a.avatar_url,+ a.meta->'token' as token, a.created_at,+ u.username, u.display_name, u.avatar_url as actor_avatar+ from agent_identities a+ join user_follows f on f.following_id = a.user_id and f.follower_id = ${viewer.id}+ join users u on u.id = a.user_id and u.deleted_at is null and u.username is not null+ where a.is_public = true and a.deleted_at is null+ and a.meta->'token'->>'mint' is not null+ order by coalesce(a.meta->'token'->>'launched_at', a.created_at::text) desc+ limit ${perKind}+ `,+ ]);++ const actor = (r, avatarKey = 'avatar_url') => ({+ username: r.username,+ display_name: r.display_name || r.username,+ avatar_url: r[avatarKey]+ ? (r[avatarKey].startsWith('http') ? r[avatarKey] : publicUrl(r[avatarKey]))+ : null,+ });++ const items = [];++ for (const r of avatarRows) {+ items.push({+ kind: 'avatar',+ id: r.id,+ created_at: r.created_at,+ actor: actor(r),+ title: r.name,+ href: `/avatars/${r.id}`,+ image: r.thumbnail_key ? publicUrl(r.thumbnail_key) : null,+ });+ }++ for (const r of agentRows) {+ items.push({+ kind: 'agent',+ id: r.id,+ created_at: r.created_at,+ actor: actor(r, 'actor_avatar'),+ title: r.name,+ subtitle: r.description || null,+ href: `/agent/${r.id}`,+ image: r.profile_image_url || r.avatar_url || null,+ });+ }++ for (const r of coinRows) {+ const t = r.token || {};+ if (!t.mint) continue;+ items.push({+ kind: 'coin',+ id: t.mint,+ created_at: t.launched_at || r.created_at,+ actor: actor(r, 'actor_avatar'),+ title: t.name || r.agent_name,+ subtitle: t.symbol ? `$${String(t.symbol).replace(/^\$/, '')}` : null,+ href: t.pumpfun_url || t.explorer_url || `/agent/${r.agent_id}`,+ external: Boolean(t.pumpfun_url || t.explorer_url),+ image: t.image || r.profile_image_url || r.avatar_url || null,+ });+ }++ items.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));++ res.setHeader('Cache-Control', 'private, no-store');+ return json(res, 200, { items: items.slice(0, limit), following_count });+});diff --git a/api/walk/analytics.js b/api/walk/analytics.jsnew file mode 100644index 000000000..3811538b4--- /dev/null+++ b/api/walk/analytics.js@@ -0,0 +1,192 @@+// GET /api/walk/analytics — the per-creator embed analytics dashboard (task 40).+//+// ?avatarId = <uuid> (required)+// ?from = <ISO date> (optional, default 30 days ago, UTC)+// ?to = <ISO date> (optional, default today, UTC, inclusive)+//+// Owner-auth-gated: only the user who owns the avatar can read its analytics. A+// missing session → 401; a session that doesn't own the avatar → 403. Mirrors+// what Plausible / the Stripe dashboard offer, scoped to one walking avatar:+// · totalSessions — sessions counted across the window+// · avgDurationSec — total walk time / total sessions+// · totalDistance — metres walked+// · uniqueOrigins — distinct embed hosts the avatar walked on+// · timeSeries[] — per-day { date, sessions, distanceMeters, durationSec }+// · topOrigins[] — top 10 embed hosts by sessions+// · events[] — creator-defined events with count + conversion rate+//+// All figures come from the same walk_metrics / walk_events pipeline the ingest+// (POST /api/walk/metrics) writes — no sampling, no estimation.++import { cors, method, json, wrap, rateLimited, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { sql } from '../_lib/db.js';+import { isUuid } from '../_lib/validate.js';+import { getSessionUser, extractBearer, authenticateBearer, hasScope } from '../_lib/auth.js';++export const maxDuration = 10;++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer && hasScope(bearer.scope, 'avatars:read')) return { userId: bearer.userId };+ return null;+}++// Clamp / default an ISO date param to a UTC YYYY-MM-DD string.+function normDate(value, fallback) {+ if (!value) return fallback;+ const d = new Date(value);+ if (Number.isNaN(d.getTime())) return fallback;+ return d.toISOString().slice(0, 10);+}++export default wrap(async (req, res) => {+ // Same-origin dashboard fetch; credentials carry the session cookie.+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://x');+ const avatarId = (url.searchParams.get('avatarId') || '').trim();+ if (!isUuid(avatarId)) return error(res, 400, 'bad_avatar_id', 'avatarId must be a UUID');++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in to view analytics');++ // Ownership gate — the avatar must exist and belong to the caller.+ const [owned] = await sql`+ select id, owner_id, name, slug+ from avatars+ where id = ${avatarId} and deleted_at is null+ limit 1+ `;+ if (!owned) return error(res, 404, 'not_found', 'avatar not found');+ if (owned.owner_id !== auth.userId) {+ return error(res, 403, 'forbidden', 'you do not own this avatar');+ }++ const today = new Date().toISOString().slice(0, 10);+ const defaultFrom = (() => {+ const d = new Date();+ d.setUTCDate(d.getUTCDate() - 29); // 30-day window inclusive+ return d.toISOString().slice(0, 10);+ })();+ const from = normDate(url.searchParams.get('from'), defaultFrom);+ const to = normDate(url.searchParams.get('to'), today);+ // `to` is inclusive; aggregate with day <= to.++ // Totals across the window.+ const [totals] = await sql`+ select+ coalesce(sum(sessions), 0) as total_sessions,+ coalesce(sum(distance_meters), 0) as total_distance,+ coalesce(sum(duration_sec), 0) as total_duration,+ count(distinct embed_origin) filter (where embed_origin is not null) as unique_origins+ from walk_metrics+ where avatar_id = ${avatarId} and day >= ${from} and day <= ${to}+ `;++ const totalSessions = Number(totals?.total_sessions || 0);+ const totalDistance = Number(totals?.total_distance || 0);+ const totalDuration = Number(totals?.total_duration || 0);+ const uniqueOrigins = Number(totals?.unique_origins || 0);++ // Per-day series for the chart.+ const seriesRows = await sql`+ select+ day::text as date,+ coalesce(sum(sessions), 0) as sessions,+ coalesce(sum(distance_meters), 0) as distance_meters,+ coalesce(sum(duration_sec), 0) as duration_sec+ from walk_metrics+ where avatar_id = ${avatarId} and day >= ${from} and day <= ${to}+ group by day+ order by day asc+ `;++ // Fill missing days with zeroes so the chart x-axis is continuous.+ const byDate = new Map(+ seriesRows.map((r) => [+ r.date,+ {+ date: r.date,+ sessions: Number(r.sessions),+ distanceMeters: Math.round(Number(r.distance_meters) * 100) / 100,+ durationSec: Math.round(Number(r.duration_sec)),+ },+ ]),+ );+ const timeSeries = [];+ {+ const cursor = new Date(`${from}T00:00:00Z`);+ const end = new Date(`${to}T00:00:00Z`);+ // Guard against an inverted range (from > to) producing an infinite loop.+ let guard = 0;+ while (cursor <= end && guard < 400) {+ const key = cursor.toISOString().slice(0, 10);+ timeSeries.push(+ byDate.get(key) || { date: key, sessions: 0, distanceMeters: 0, durationSec: 0 },+ );+ cursor.setUTCDate(cursor.getUTCDate() + 1);+ guard++;+ }+ }++ // Top 10 embed origins by session count.+ const originRows = await sql`+ select+ embed_origin as origin,+ coalesce(sum(sessions), 0) as sessions,+ coalesce(sum(distance_meters), 0) as distance_meters+ from walk_metrics+ where avatar_id = ${avatarId} and day >= ${from} and day <= ${to}+ and embed_origin is not null+ group by embed_origin+ order by sessions desc, distance_meters desc+ limit 10+ `;+ const topOrigins = originRows.map((r) => ({+ origin: r.origin,+ sessions: Number(r.sessions),+ distanceMeters: Math.round(Number(r.distance_meters) * 100) / 100,+ }));++ // Creator-defined events with conversion rate vs sessions.+ const eventRows = await sql`+ select+ event_name as name,+ count(*) as count,+ coalesce(sum(value), 0) as total_value+ from walk_events+ where avatar_id = ${avatarId}+ and created_at >= ${`${from}T00:00:00Z`}+ and created_at < ${`${to}T23:59:59.999Z`}+ group by event_name+ order by count desc+ `;+ const events = eventRows.map((r) => {+ const count = Number(r.count);+ return {+ name: r.name,+ count,+ totalValue: Math.round(Number(r.total_value) * 100) / 100,+ conversionRate: totalSessions > 0 ? Math.round((count / totalSessions) * 10000) / 100 : 0,+ };+ });++ return json(res, 200, {+ avatar: { id: owned.id, name: owned.name, slug: owned.slug },+ range: { from, to },+ totalSessions,+ avgDurationSec: totalSessions > 0 ? Math.round(totalDuration / totalSessions) : 0,+ totalDistance: Math.round(totalDistance * 100) / 100,+ uniqueOrigins,+ timeSeries,+ topOrigins,+ events,+ });+});diff --git a/api/walk/leaderboard.js b/api/walk/leaderboard.jsnew file mode 100644index 000000000..d278c282c--- /dev/null+++ b/api/walk/leaderboard.js@@ -0,0 +1,242 @@+// GET /api/walk/leaderboard — the public walk leaderboard (task 39).+//+// ?period = daily | weekly | all-time (default weekly)+// ?metric = distance | sites | time (default distance)+// ?limit = 1..100 (default 50)+// ?offset = 0.. (page offset)+// ?anonId = <stable anon id> (to pin an anonymous walker's row)+//+// Ranks walkers (signed-in users AND anonymous walkers) by one of three metrics+// aggregated over the chosen window from the walk_metrics rollup:+// · distance — total metres walked+// · sites — distinct embed origins + extension hostnames the avatar walked on+// · time — total seconds spent walking+//+// Each row carries `deltaFromYesterday`: the same metric earned today minus the+// metric earned the prior UTC day, so the board shows momentum, not just totals.+// The requesting walker's own row is always returned (pinned), even when it falls+// outside the requested page — resolved from the session/bearer or the anonId.++import { cors, method, json, wrap, rateLimited, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { sql } from '../_lib/db.js';+import { getSessionUser, extractBearer, authenticateBearer } from '../_lib/auth.js';+import { publicUrl } from '../_lib/r2.js';++export const maxDuration = 10;++const PERIODS = new Set(['daily', 'weekly', 'all-time']);+const METRICS = new Set(['distance', 'sites', 'time']);++// SQL expression that produces the ranked metric value for a set of summed+// columns. `sites` is a COUNT(DISTINCT …) so it can't be summed like the others —+// handled with its own aggregate in the query builders below.+function metricLabel(metric) {+ return metric === 'sites' ? 'sites' : metric === 'time' ? 'time' : 'distance';+}++// Window lower bound (inclusive UTC date) for a period. all-time → null (no bound).+function periodStartDate(period) {+ if (period === 'all-time') return null;+ const now = new Date();+ const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));+ if (period === 'weekly') d.setUTCDate(d.getUTCDate() - 6); // today + previous 6 days+ return d.toISOString().slice(0, 10);+}++async function resolveWalker(req, anonIdParam) {+ try {+ const bearer = extractBearer(req);+ const user = bearer ? await authenticateBearer(bearer) : await getSessionUser(req);+ const userId = user?.userId || user?.id || user?.sub || null;+ if (userId) return { userId, anonId: null };+ } catch {+ /* fall through to anon */+ }+ return { userId: null, anonId: anonIdParam || null };+}++// Build the metric aggregate fragment for the SELECT and ORDER BY.+function aggExpr(metric) {+ if (metric === 'distance') return sql`coalesce(sum(distance_meters), 0)`;+ if (metric === 'time') return sql`coalesce(sum(duration_sec), 0)`;+ // sites: distinct of embed_origin OR site_hostname, whichever is present.+ return sql`count(distinct coalesce(embed_origin, site_hostname)) filter (where coalesce(embed_origin, site_hostname) is not null)`;+}++// Per-walker aggregation over an optional [start, end) day window, returning a+// keyed map of { '<u|a>:<id>': value }. Used both for the ranked board and for+// the today/yesterday delta passes.+async function aggregateByWalker(metric, startDay, endDayExclusive) {+ const value = aggExpr(metric);+ let where = sql`where (user_id is not null or anon_id is not null)`;+ if (startDay) where = sql`${where} and day >= ${startDay}`;+ if (endDayExclusive) where = sql`${where} and day < ${endDayExclusive}`;+ const rows = await sql`+ select+ user_id,+ anon_id,+ ${value} as value+ from walk_metrics+ ${where}+ group by user_id, anon_id+ having ${value} > 0+ `;+ const map = new Map();+ for (const r of rows) {+ const key = r.user_id ? `u:${r.user_id}` : `a:${r.anon_id}`;+ map.set(key, { userId: r.user_id, anonId: r.anon_id, value: Number(r.value) });+ }+ return map;+}++// Short, stable, privacy-preserving handle for an anonymous walker.+function anonHandle(anonId) {+ const tail = String(anonId || '').replace(/[^a-zA-Z0-9]/g, '').slice(-4) || '0000';+ return `walker-${tail}`;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://x');+ const period = url.searchParams.get('period') || 'weekly';+ const metric = url.searchParams.get('metric') || 'distance';+ if (!PERIODS.has(period)) return error(res, 400, 'bad_period', 'period must be daily, weekly or all-time');+ if (!METRICS.has(metric)) return error(res, 400, 'bad_metric', 'metric must be distance, sites or time');++ const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 50, 1), 100);+ const offset = Math.max(Number(url.searchParams.get('offset')) || 0, 0);++ const startDay = periodStartDate(period);+ const today = new Date().toISOString().slice(0, 10);+ const yesterday = (() => {+ const d = new Date();+ d.setUTCDate(d.getUTCDate() - 1);+ return d.toISOString().slice(0, 10);+ })();++ // Full ranking for the window, plus today/yesterday slices for the delta.+ const [windowMap, todayMap, yesterdayMap] = await Promise.all([+ aggregateByWalker(metric, startDay, null),+ aggregateByWalker(metric, today, null),+ aggregateByWalker(metric, yesterday, today),+ ]);++ // Sort all walkers descending by the window metric, break ties by key for+ // determinism, then assign dense ranks.+ const ranked = [...windowMap.values()].sort((a, b) => {+ if (b.value !== a.value) return b.value - a.value;+ const ka = a.userId ? `u:${a.userId}` : `a:${a.anonId}`;+ const kb = b.userId ? `u:${b.userId}` : `a:${b.anonId}`;+ return ka < kb ? -1 : ka > kb ? 1 : 0;+ });+ const total = ranked.length;++ const rankByKey = new Map();+ ranked.forEach((w, i) => {+ const key = w.userId ? `u:${w.userId}` : `a:${w.anonId}`;+ rankByKey.set(key, i + 1);+ });++ const page = ranked.slice(offset, offset + limit);++ // Resolve profile fields (handle + avatar thumb) for the signed-in users on+ // this page plus the requesting walker, in one query.+ const walker = await resolveWalker(req, url.searchParams.get('anonId'));+ const userIdsNeeded = new Set(page.filter((w) => w.userId).map((w) => w.userId));+ if (walker.userId) userIdsNeeded.add(walker.userId);++ const profiles = new Map();+ const idList = [...userIdsNeeded];+ if (idList.length) {+ const rows = await sql`+ select u.id, u.username, u.display_name,+ (select thumbnail_key from avatars+ where owner_id = u.id and deleted_at is null and thumbnail_key is not null+ order by created_at desc limit 1) as thumbnail_key,+ (select id from avatars+ where owner_id = u.id and deleted_at is null+ order by created_at desc limit 1) as avatar_id+ from users u+ where u.id = any(${idList}) and u.deleted_at is null+ `;+ for (const r of rows) profiles.set(r.id, r);+ }++ function metricNow(key) {+ return todayMap.get(key)?.value || 0;+ }+ function metricPrev(key) {+ return yesterdayMap.get(key)?.value || 0;+ }++ function toRow(w, rank) {+ const key = w.userId ? `u:${w.userId}` : `a:${w.anonId}`;+ const prof = w.userId ? profiles.get(w.userId) : null;+ const handle = prof+ ? prof.username+ ? `@${prof.username}`+ : prof.display_name || 'three.ws walker'+ : anonHandle(w.anonId);+ return {+ rank,+ key,+ userId: w.userId || null,+ anonId: w.userId ? null : w.anonId,+ username: prof?.username || null,+ handle,+ profileUrl: prof?.username ? `/u/${prof.username}` : null,+ avatarId: prof?.avatar_id || null,+ avatar: prof?.thumbnail_key ? publicUrl(prof.thumbnail_key) : null,+ value: Math.round(w.value * 100) / 100,+ deltaFromYesterday: Math.round((metricNow(key) - metricPrev(key)) * 100) / 100,+ };+ }++ const rows = page.map((w) => toRow(w, rankByKey.get(w.userId ? `u:${w.userId}` : `a:${w.anonId}`)));++ // The requester's own pinned row (even if off-page).+ let me = null;+ const meKey = walker.userId ? `u:${walker.userId}` : walker.anonId ? `a:${walker.anonId}` : null;+ if (meKey && rankByKey.has(meKey)) {+ const w = windowMap.get(meKey);+ me = toRow(w, rankByKey.get(meKey));+ me.onPage = rows.some((r) => r.key === meKey);+ } else if (meKey) {+ // Walker has an identity but no qualifying metrics in this window yet.+ me = {+ rank: null,+ key: meKey,+ userId: walker.userId,+ anonId: walker.userId ? null : walker.anonId,+ handle: walker.userId+ ? profiles.get(walker.userId)?.username+ ? `@${profiles.get(walker.userId).username}`+ : profiles.get(walker.userId)?.display_name || 'you'+ : anonHandle(walker.anonId),+ value: 0,+ deltaFromYesterday: 0,+ onPage: false,+ unranked: true,+ };+ }++ // Public read — let the CDN cache it briefly; the board updates on a cadence.+ res.setHeader('cache-control', 'public, max-age=15, s-maxage=30, stale-while-revalidate=60');++ return json(res, 200, {+ period,+ metric: metricLabel(metric),+ total,+ limit,+ offset,+ hasMore: offset + limit < total,+ rows,+ me,+ });+});diff --git a/api/walk/metrics.js b/api/walk/metrics.jsnew file mode 100644index 000000000..27f9978ee--- /dev/null+++ b/api/walk/metrics.js@@ -0,0 +1,175 @@+// POST /api/walk/metrics — the shared ingest for the walk leaderboard (task 39)+// and the per-creator embed analytics dashboard (task 40).+//+// The walking-avatar client (src/walk.js) and the embed runtime accumulate two+// running totals — horizontal distance travelled (sum of per-frame position+// deltas, in metres) and session wall-clock — and flush a compact batch here+// every ~60s plus once on pagehide via navigator.sendBeacon. The Chrome+// extension flushes the same shape with the host it piloted.+//+// One batch UPSERTs into a per-(walker, day, env, embed origin, avatar) rollup+// row in walk_metrics, so a walker who roams for an hour produces a handful of+// rows, not thousands. The leaderboard and analytics endpoints aggregate over+// that rollup.+//+// Attribution: a signed-in session/bearer wins; otherwise the batch is keyed to+// the client-supplied anonymous id (anonId). Anonymous walkers are first-class —+// the leaderboard ranks them too — but a batch with neither identity is rejected.+//+// embedOrigin is NEVER trusted from the body: it is derived server-side from the+// Origin / Referer header (the embedding page's host), so a creator's analytics+// reflect where the avatar actually ran, not what a caller claims.+//+// eventName (+ optional value) records a creator-defined conversion event fired+// from the embed SDK — window.ThreeWalkAvatar.track('subscribe', { value: 9 }) —+// into walk_events for the analytics funnel. Achievement unlocks (1 km, 10 sites,+// all 6 environments) are persisted once each into walk_achievements.++import { z } from 'zod';+import { cors, method, readJson, json, wrap, rateLimited } from '../_lib/http.js';+import { parse } from '../_lib/validate.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { sql } from '../_lib/db.js';+import { getSessionUser, extractBearer, authenticateBearer } from '../_lib/auth.js';++export const maxDuration = 10;++// Known achievement codes — the client may only persist these. Kept in lockstep+// with the toasts fired in src/walk.js.+const ACHIEVEMENT_CODES = new Set([+ 'distance_1km',+ 'distance_5km',+ 'sites_10',+ 'all_environments',+]);++const bodySchema = z+ .object({+ // Cumulative-since-last-flush increments. Clamped to sane per-batch ceilings+ // so a malformed/hostile client can't inject an implausible jump (a brisk+ // walk is ~1.4 m/s, so even a 10-minute batch is < 1 km; 50 km is a hard+ // upper bound that still tolerates fast-travel/teleport edge cases).+ distanceMeters: z.number().finite().min(0).max(50_000).optional().default(0),+ durationSec: z.number().finite().min(0).max(86_400).optional().default(0),+ sessions: z.number().int().min(0).max(50).optional().default(0),+ envId: z.string().trim().max(64).optional().nullable(),+ siteHostname: z.string().trim().max(255).optional().nullable(),+ avatarId: z.string().uuid().optional().nullable(),+ // embedOrigin is accepted in the schema for forward-compat but ignored:+ // the value written to the DB is always derived from request headers.+ embedOrigin: z.string().max(255).optional().nullable(),+ eventName: z.string().trim().min(1).max(64).optional().nullable(),+ value: z.number().finite().optional().nullable(),+ anonId: z.string().trim().min(8).max(64).optional().nullable(),+ achievements: z.array(z.string().trim().max(64)).max(8).optional().default([]),+ })+ .strict();++// Reduce a request's Origin/Referer to a bare hostname, lowercased, https/http+// only. Returns null for same-origin (the three.ws app itself) and for anything+// unparseable — a creator's "unique sites" should count third-party embeds, not+// our own page. APP_ORIGIN is matched so a /walk session on three.ws isn't+// double-counted as an external embed origin.+function deriveEmbedOrigin(req) {+ const raw = req.headers.origin || req.headers.referer || '';+ if (!raw) return null;+ let host;+ try {+ host = new URL(raw).hostname.toLowerCase();+ } catch {+ return null;+ }+ if (!host) return null;+ if (host === 'three.ws' || host === 'www.three.ws' || host === 'localhost') return null;+ return host;+}++async function resolveUserId(req) {+ try {+ const bearer = extractBearer(req);+ const user = bearer ? await authenticateBearer(bearer) : await getSessionUser(req);+ return user?.userId || user?.id || user?.sub || null;+ } catch {+ return null;+ }+}++export default wrap(async (req, res) => {+ // Embeds POST from third-party hosts, so the ingest must be open-CORS.+ if (cors(req, res, { origins: '*', methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ const ip = clientIp(req);+ const rl = await limits.irlInteractIp(ip); // 60/min — matches the ~1/min flush cadence + retries+ if (!rl.success) return rateLimited(res, rl, 'too many metric flushes');++ const raw = await readJson(req);+ const body = parse(bodySchema, raw);++ const userId = await resolveUserId(req);+ const anonId = body.anonId || null;++ // A batch must be attributable to someone. Anonymous walkers supply anonId.+ if (!userId && !anonId) {+ return json(res, 202, { ok: false, reason: 'no walker identity', recorded: false });+ }++ const embedOrigin = deriveEmbedOrigin(req);+ const day = new Date().toISOString().slice(0, 10); // UTC date+ const envId = body.envId || null;+ const avatarId = body.avatarId || null;+ const siteHostname = body.siteHostname || null;++ const hasMetrics = body.distanceMeters > 0 || body.durationSec > 0 || body.sessions > 0;++ // Rollup UPSERT: add this batch's increments onto the matching daily row. The+ // unique index is on the COALESCE'd dimension tuple, so the ON CONFLICT target+ // must match it expression-for-expression.+ if (hasMetrics) {+ await sql`+ insert into walk_metrics+ (user_id, anon_id, avatar_id, day, env_id, embed_origin, site_hostname,+ distance_meters, duration_sec, sessions)+ values+ (${userId}, ${anonId}, ${avatarId}, ${day}, ${envId}, ${embedOrigin}, ${siteHostname},+ ${body.distanceMeters}, ${body.durationSec}, ${body.sessions})+ on conflict (+ coalesce(user_id::text, ''),+ coalesce(anon_id, ''),+ day,+ coalesce(env_id, ''),+ coalesce(embed_origin, ''),+ coalesce(avatar_id::text, '')+ )+ do update set+ distance_meters = walk_metrics.distance_meters + excluded.distance_meters,+ duration_sec = walk_metrics.duration_sec + excluded.duration_sec,+ sessions = walk_metrics.sessions + excluded.sessions,+ site_hostname = coalesce(excluded.site_hostname, walk_metrics.site_hostname),+ updated_at = now()+ `;+ }++ // Creator-defined conversion event from the embed SDK.+ if (body.eventName) {+ await sql`+ insert into walk_events (user_id, anon_id, avatar_id, event_name, value, embed_origin)+ values (${userId}, ${anonId}, ${avatarId}, ${body.eventName}, ${body.value ?? null}, ${embedOrigin})+ `;+ }++ // Persist any newly-crossed achievement thresholds, once each.+ const codes = (body.achievements || []).filter((c) => ACHIEVEMENT_CODES.has(c));+ if (codes.length) {+ for (const code of codes) {+ await sql`+ insert into walk_achievements (user_id, anon_id, code)+ values (${userId}, ${anonId}, ${code})+ on conflict (coalesce(user_id::text, ''), coalesce(anon_id, ''), code)+ do nothing+ `;+ }+ }++ return json(res, 200, { ok: true, recorded: hasMetrics || !!body.eventName || codes.length > 0 });+});diff --git a/data/changelog.json b/data/changelog.jsonindex 1bc66820f..db8d8ab2b 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,35 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-21",+ "title": "Empty pages now guide you instead of going blank",+ "summary": "Across the dashboard and marketplace, anywhere a list can be empty now explains what belongs there, why it's useful, and the next step — instead of a bare 'No data' line. Your Agents, Avatars, Analytics, Brain, embed policies, the marketplace, and My Agents each greet a fresh account with a short plain-language intro and a clear button to create your first one (plus a 'What's an agent?' link). Filtered searches that return nothing now say so and offer to clear the filter. It's the same designed component everywhere, so the whole platform feels consistent and never abandoned.",+ "tags": [+ "improvement"+ ],+ "link": "/dashboard"+ },+ {+ "date": "2026-06-21",+ "title": "Profiles you can edit — and follow",+ "summary": "Your three.ws profile at three.ws/u/<your-username> is now a real social home. Edit it in place: add a bio, a profile picture and banner image, your location, and a website link — all from an Edit button on your own profile. You can now follow other creators and agents, and they can follow you; every profile shows live follower and following counts you can tap to browse the lists, with one-tap follow buttons throughout. And there's a new Feed at three.ws/feed that gathers the latest avatars, agents, and coin launches from everyone you follow, newest first. Find your profile and Feed links from your account page.",+ "tags": [+ "feature"+ ],+ "link": "/feed"+ },+ {+ "date": "2026-06-21",+ "title": "Payment hardening and a steadier holder leaderboard",+ "summary": "Two behind-the-scenes reliability and safety fixes. Agent payment invoices now verify that the wallet paying is actually linked to your account before an invoice is created, closing a gap that let bogus payment requests be generated against any agent. And the $THREE holder leaderboard, its share card, and the token stats panel no longer each kick off a full on-chain holder scan during a traffic spike — one scan now serves everyone and refreshes the shared snapshot, so the leaderboard stays fast and responsive under load. Nothing to do on your end.",+ "tags": [+ "security",+ "fix",+ "infra"+ ],+ "link": "/leaderboard"+ },{"date": "2026-06-21","title": "Every Forge quality tier now runs on free engines",@@ -5489,6 +5518,15 @@"fix"],"link": "/club"+ },+ {+ "date": "2026-06-21",+ "title": "Clearer empty state on the $THREE live-trades feed",+ "summary": "Before the next trade lands, the live-trades panel on the $THREE token page now reads in plain language — 'Live trades will appear here' — with a short note on what it shows, and the technical detail tucked behind an info tooltip. Screen readers announce new trades as they stream in.",+ "tags": [+ "improvement"+ ],+ "link": "/three-token"}]}diff --git a/data/pages.json b/data/pages.jsonindex 1e02bd68d..0e7b8fb96 100644--- a/data/pages.json+++ b/data/pages.json@@ -141,6 +141,14 @@"priority": 0.7,"changefreq": "monthly","added": "2026-06-20"+ },+ {+ "path": "/walk",+ "title": "Walk",+ "description": "Your 3D avatar walks anywhere on the web. Live demos across six environments, a Chrome extension, one-tag embeds, and a global distance leaderboard.",+ "priority": 0.8,+ "changefreq": "weekly",+ "added": "2026-06-21"}]},@@ -465,6 +473,14 @@"priority": 0.8,"changefreq": "weekly","added": "2026-06-05"+ },+ {+ "path": "/walk-leaderboard",+ "title": "Walk Leaderboard",+ "description": "Global leaderboard for the walking avatar — distance walked, sites visited, and time, ranked daily, weekly, and all-time.",+ "priority": 0.6,+ "changefreq": "daily",+ "added": "2026-06-21"}]},diff --git a/package.json b/package.jsonindex 68c6a0062..dc7aaebbd 100644--- a/package.json+++ b/package.json@@ -90,6 +90,7 @@"test:mcp": "node scripts/test-mcp-all.mjs","audit:pages": "node scripts/audit-page-index.mjs","audit:handlers": "node scripts/audit-empty-handlers.mjs",+ "check:images": "node scripts/audit-image-loading.mjs --strict","audit:web": "node scripts/page-audit.mjs","snapshot": "node scripts/page-snapshot.mjs","build:news": "node scripts/build-news.mjs",diff --git a/pages/feed.html b/pages/feed.htmlnew file mode 100644index 000000000..793e0a2cd--- /dev/null+++ b/pages/feed.html@@ -0,0 +1,362 @@+<!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" />+ <title>Your Feed — three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta name="description" content="Recent activity from the people and agents you follow on three.ws." />+ <meta name="theme-color" content="#000000" />+ <meta name="robots" content="noindex" />+ <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="/footer.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />++ <style>+ body {+ overflow: auto;+ display: flex;+ flex-direction: column;+ min-height: 100vh;+ }++ .feed-root {+ max-width: 680px;+ margin: 0 auto;+ padding: 2.5rem 1.5rem 5rem;+ width: 100%;+ flex: 1;+ }++ .feed-head {+ margin-bottom: 2rem;+ }+ .feed-head h1 {+ font-size: 1.618rem;+ font-weight: 400;+ letter-spacing: -0.02em;+ margin: 0 0 0.35rem;+ }+ .feed-head p {+ margin: 0;+ color: rgba(255, 255, 255, 0.45);+ font-size: 0.9rem;+ }++ .feed-tip {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+ margin-top: 1rem;+ font-size: 0.8rem;+ color: rgba(255, 255, 255, 0.55);+ text-decoration: none;+ border: 1px solid rgba(255, 255, 255, 0.12);+ border-radius: 999px;+ padding: 0.35rem 0.85rem;+ transition: border-color 0.15s ease, color 0.15s ease;+ }+ .feed-tip:hover {+ border-color: rgba(255, 255, 255, 0.3);+ color: rgba(255, 255, 255, 0.9);+ }++ .feed-item {+ display: flex;+ gap: 0.9rem;+ padding: 1.1rem 0;+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);+ animation: feed-in 0.4s ease both;+ }+ @keyframes feed-in {+ from { opacity: 0; transform: translateY(6px); }+ to { opacity: 1; transform: none; }+ }++ .feed-avatar {+ width: 40px;+ height: 40px;+ border-radius: 50%;+ flex-shrink: 0;+ background: rgba(255, 255, 255, 0.06);+ border: 1px solid rgba(255, 255, 255, 0.1);+ object-fit: cover;+ display: flex;+ align-items: center;+ justify-content: center;+ color: rgba(255, 255, 255, 0.4);+ font-size: 1.1rem;+ text-decoration: none;+ overflow: hidden;+ }+ .feed-avatar img { width: 100%; height: 100%; object-fit: cover; }++ .feed-body { flex: 1; min-width: 0; }+ .feed-line {+ font-size: 0.9rem;+ color: rgba(255, 255, 255, 0.75);+ line-height: 1.45;+ }+ .feed-line a.actor {+ color: #fff;+ font-weight: 500;+ text-decoration: none;+ }+ .feed-line a.actor:hover { text-decoration: underline; }+ .feed-verb { color: rgba(255, 255, 255, 0.45); }+ .feed-pill {+ display: inline-block;+ font-size: 0.7rem;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: rgba(255, 255, 255, 0.5);+ border: 1px solid rgba(255, 255, 255, 0.12);+ border-radius: 4px;+ padding: 0.05em 0.4em;+ margin-left: 0.4rem;+ vertical-align: middle;+ }++ .feed-card {+ display: flex;+ gap: 0.75rem;+ margin-top: 0.6rem;+ padding: 0.7rem;+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 12px;+ text-decoration: none;+ color: inherit;+ transition: border-color 0.15s ease, background 0.15s ease;+ align-items: center;+ }+ .feed-card:hover {+ border-color: rgba(255, 255, 255, 0.2);+ background: rgba(255, 255, 255, 0.02);+ }+ .feed-card-thumb {+ width: 52px;+ height: 52px;+ border-radius: 8px;+ flex-shrink: 0;+ object-fit: cover;+ background: rgba(255, 255, 255, 0.05);+ display: flex;+ align-items: center;+ justify-content: center;+ color: rgba(255, 255, 255, 0.35);+ font-size: 1.3rem;+ overflow: hidden;+ }+ .feed-card-thumb img { width: 100%; height: 100%; object-fit: cover; }+ .feed-card-title { font-weight: 500; font-size: 0.92rem; color: #fff; }+ .feed-card-sub {+ font-size: 0.8rem;+ color: rgba(255, 255, 255, 0.45);+ margin-top: 0.15rem;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }+ .feed-time {+ font-size: 0.75rem;+ color: rgba(255, 255, 255, 0.35);+ margin-top: 0.35rem;+ }++ .feed-state {+ text-align: center;+ padding: 4rem 1rem;+ color: rgba(255, 255, 255, 0.5);+ }+ .feed-state .glyph { font-size: 2.5rem; opacity: 0.4; margin-bottom: 0.8rem; }+ .feed-state h2 { font-weight: 400; font-size: 1.2rem; color: #fff; margin: 0 0 0.5rem; }+ .feed-state p { margin: 0 auto 1.4rem; max-width: 340px; line-height: 1.5; font-size: 0.9rem; }+ .feed-btn {+ display: inline-block;+ background: #fff;+ color: #000;+ text-decoration: none;+ font-weight: 500;+ font-size: 0.9rem;+ padding: 0.65rem 1.3rem;+ border-radius: 10px;+ transition: opacity 0.15s ease;+ }+ .feed-btn:hover { opacity: 0.85; }++ .feed-skeleton {+ height: 84px;+ border-radius: 12px;+ background: linear-gradient(+ 90deg,+ rgba(255, 255, 255, 0.03) 25%,+ rgba(255, 255, 255, 0.07) 37%,+ rgba(255, 255, 255, 0.03) 63%+ );+ background-size: 400% 100%;+ animation: feed-shimmer 1.4s ease infinite;+ margin-bottom: 0.8rem;+ }+ @keyframes feed-shimmer {+ 0% { background-position: 100% 0; }+ 100% { background-position: 0 0; }+ }+ </style>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main>+ <div class="feed-root">+ <div class="feed-head">+ <h1>Your Feed</h1>+ <p>New avatars, agents, and launches from everyone you follow.</p>+ <a class="feed-tip" href="/discover">+ <svg width="13" height="13" viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M8 1a7 7 0 1 0 0 14A7 7 0 0 0 8 1m.75 10.5h-1.5V7h1.5zm0-6h-1.5V4h1.5z"/></svg>+ Discover more people to follow+ </a>+ </div>+ <div id="feed-list">+ <div class="feed-skeleton"></div>+ <div class="feed-skeleton"></div>+ <div class="feed-skeleton"></div>+ </div>+ </div>+ </main>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script src="/brand.js" defer></script>++ <script type="module">+ const esc = (s) =>+ String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+ const attr = (s) => esc(s).replace(/"/g, '"');+ const list = document.getElementById('feed-list');++ const VERB = {+ avatar: 'created a new avatar',+ agent: 'launched an agent',+ coin: 'launched a coin',+ };+ const GLYPH = { avatar: '◎', agent: '🤖', coin: '◉' };++ function relTime(iso) {+ if (!iso) return '';+ const then = new Date(iso).getTime();+ if (!Number.isFinite(then)) return '';+ const diff = Math.max(0, Date.now() - then);+ const m = Math.floor(diff / 60000);+ if (m < 1) return 'just now';+ if (m < 60) return `${m}m ago`;+ const h = Math.floor(m / 60);+ if (h < 24) return `${h}h ago`;+ const d = Math.floor(h / 24);+ if (d < 30) return `${d}d ago`;+ return new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });+ }++ function avatarEl(actor) {+ const inner = actor.avatar_url+ ? `<img src="${attr(actor.avatar_url)}" alt="${attr(actor.display_name)}" loading="lazy" referrerpolicy="no-referrer">`+ : '◎';+ return `<a class="feed-avatar" href="/u/${attr(actor.username)}" aria-label="${attr(actor.display_name)}">${inner}</a>`;+ }++ function itemEl(it) {+ const a = it.actor || {};+ const cardThumb = it.image+ ? `<img src="${attr(it.image)}" alt="" loading="lazy" referrerpolicy="no-referrer">`+ : GLYPH[it.kind] || '◎';+ const external = it.external ? ' target="_blank" rel="noopener"' : '';+ return `+ <article class="feed-item">+ ${avatarEl(a)}+ <div class="feed-body">+ <div class="feed-line">+ <a class="actor" href="/u/${attr(a.username)}">${esc(a.display_name)}</a>+ <span class="feed-verb"> ${esc(VERB[it.kind] || 'shared something')}</span>+ <span class="feed-pill">${esc(it.kind)}</span>+ </div>+ <a class="feed-card" href="${attr(it.href)}"${external}>+ <div class="feed-card-thumb">${cardThumb}</div>+ <div style="min-width:0">+ <div class="feed-card-title">${esc(it.title || 'Untitled')}</div>+ ${it.subtitle ? `<div class="feed-card-sub">${esc(it.subtitle)}</div>` : ''}+ </div>+ </a>+ <div class="feed-time">${esc(relTime(it.created_at))}</div>+ </div>+ </article>+ `;+ }++ function renderState({ glyph, title, body, cta }) {+ list.innerHTML = `+ <div class="feed-state">+ <div class="glyph">${glyph}</div>+ <h2>${esc(title)}</h2>+ <p>${esc(body)}</p>+ ${cta ? `<a class="feed-btn" href="${attr(cta.href)}">${esc(cta.label)}</a>` : ''}+ </div>+ `;+ }++ (async function load() {+ let res;+ try {+ res = await fetch('/api/users/me/feed?limit=40', { credentials: 'include' });+ } catch {+ renderState({ glyph: '⚠', title: 'Could not load your feed', body: 'Check your connection and try again.', cta: { href: '/feed', label: 'Retry' } });+ return;+ }++ if (res.status === 401) {+ renderState({+ glyph: '◎',+ title: 'Sign in to see your feed',+ body: 'Follow creators and agents on three.ws to build a feed of their latest work.',+ cta: { href: `/login?return=${encodeURIComponent('/feed')}`, label: 'Sign in' },+ });+ return;+ }+ if (!res.ok) {+ renderState({ glyph: '⚠', title: 'Something went wrong', body: 'We could not load your feed right now.', cta: { href: '/feed', label: 'Retry' } });+ return;+ }++ const data = await res.json();+ const items = data.items || [];++ if (data.following_count === 0) {+ renderState({+ glyph: '✦',+ title: "You're not following anyone yet",+ body: 'Find creators and agents to follow — their new avatars, agents, and launches will show up here.',+ cta: { href: '/discover', label: 'Discover creators' },+ });+ return;+ }+ if (!items.length) {+ renderState({+ glyph: '☾',+ title: 'No recent activity',+ body: 'The people you follow have not posted anything public lately. Check back soon.',+ cta: { href: '/discover', label: 'Follow more people' },+ });+ return;+ }++ list.innerHTML = items.map(itemEl).join('');+ })();+ </script>+ </body>+</html>diff --git a/pages/profile.html b/pages/profile.htmlindex 0be95fe5a..0726bbd2f 100644--- a/pages/profile.html+++ b/pages/profile.html@@ -707,6 +707,219 @@font-size: 1.1rem;}}++ /* ── Social: banner, bio, actions, edit + follow modals ─────────────── */+ .up-banner {+ width: 100%;+ height: 180px;+ border-radius: 16px;+ margin-bottom: -56px;+ background-size: cover;+ background-position: center;+ border: 1px solid rgba(255, 255, 255, 0.08);+ }+ .up-banner-pad { padding-top: 64px; }++ .up-pfp {+ width: 88px;+ height: 88px;+ border-radius: 50%;+ object-fit: cover;+ border: 3px solid var(--bg-0, #000);+ background: #0a0a0a;+ flex-shrink: 0;+ }++ .up-bio {+ color: rgba(255, 255, 255, 0.78);+ font-size: 0.95rem;+ line-height: 1.55;+ margin: 0.7rem 0 0;+ max-width: 52ch;+ white-space: pre-wrap;+ }+ .up-bio-meta {+ display: flex;+ flex-wrap: wrap;+ gap: 0.4rem 1rem;+ margin-top: 0.6rem;+ font-size: 0.82rem;+ color: rgba(255, 255, 255, 0.45);+ }+ .up-bio-meta a { color: #69b7ff; text-decoration: none; }+ .up-bio-meta a:hover { text-decoration: underline; }+ .up-bio-meta span { display: inline-flex; align-items: center; gap: 0.3rem; }++ .up-actions {+ display: flex;+ gap: 0.5rem;+ margin-top: 0.9rem;+ flex-wrap: wrap;+ }+ .up-action-btn {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+ font-family: inherit;+ font-size: 0.85rem;+ font-weight: 500;+ padding: 0.5rem 1.1rem;+ border-radius: 999px;+ cursor: pointer;+ border: 1px solid rgba(255, 255, 255, 0.18);+ background: transparent;+ color: rgba(255, 255, 255, 0.9);+ transition: background 0.15s ease, border-color 0.15s ease, opacity 0.15s ease;+ }+ .up-action-btn:hover { border-color: rgba(255, 255, 255, 0.4); }+ .up-action-btn--primary {+ background: #fff;+ color: #000;+ border-color: #fff;+ }+ .up-action-btn--primary:hover { opacity: 0.85; }+ .up-action-btn--following {+ background: transparent;+ color: rgba(255, 255, 255, 0.9);+ }+ .up-action-btn--following:hover {+ border-color: #ff6b6b;+ color: #ff6b6b;+ }+ .up-action-btn--following:hover .up-follow-label::after { content: 'Unfollow'; }+ .up-action-btn--following:hover .up-follow-label { font-size: 0; }+ .up-action-btn--following:hover .up-follow-label::after { font-size: 0.85rem; }+ .up-action-btn[disabled] { opacity: 0.5; cursor: default; }++ .up-stat--link { cursor: pointer; background: none; border: 0; font-family: inherit; }+ .up-stat--link:hover .up-stat-num { color: #fff; }++ /* Modals (edit + follow lists) */+ .up-modal-backdrop {+ position: fixed;+ inset: 0;+ background: rgba(0, 0, 0, 0.7);+ backdrop-filter: blur(6px);+ display: flex;+ align-items: center;+ justify-content: center;+ z-index: 9999;+ padding: 1rem;+ }+ .up-modal {+ background: var(--bg-0, #0a0a0a);+ border: 1px solid rgba(255, 255, 255, 0.12);+ border-radius: 16px;+ width: 100%;+ max-width: 460px;+ max-height: 85vh;+ overflow-y: auto;+ color: rgba(255, 255, 255, 0.95);+ animation: up-modal-in 0.2s ease both;+ }+ @keyframes up-modal-in {+ from { opacity: 0; transform: translateY(10px) scale(0.98); }+ to { opacity: 1; transform: none; }+ }+ .up-modal-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 1.2rem 1.4rem;+ border-bottom: 1px solid rgba(255, 255, 255, 0.08);+ position: sticky;+ top: 0;+ background: var(--bg-0, #0a0a0a);+ }+ .up-modal-head h3 { margin: 0; font-weight: 500; font-size: 1.05rem; }+ .up-modal-close {+ background: transparent;+ border: 0;+ color: rgba(255, 255, 255, 0.5);+ font-size: 1.5rem;+ line-height: 1;+ cursor: pointer;+ }+ .up-modal-close:hover { color: #fff; }+ .up-modal-body { padding: 1.4rem; }++ .up-field { margin-bottom: 1.1rem; }+ .up-field label {+ display: block;+ font-size: 0.8rem;+ color: rgba(255, 255, 255, 0.55);+ margin-bottom: 0.4rem;+ }+ .up-field input,+ .up-field textarea {+ width: 100%;+ background: #000;+ color: #fff;+ border: 1px solid rgba(255, 255, 255, 0.14);+ border-radius: 9px;+ padding: 0.65rem 0.85rem;+ font-size: 0.92rem;+ font-family: inherit;+ box-sizing: border-box;+ transition: border-color 0.15s ease;+ }+ .up-field input:focus,+ .up-field textarea:focus {+ outline: none;+ border-color: rgba(255, 255, 255, 0.4);+ }+ .up-field textarea { resize: vertical; min-height: 80px; }+ .up-field-count { float: right; font-size: 0.72rem; color: rgba(255, 255, 255, 0.35); }+ .up-modal-error {+ color: #ff7a7a;+ font-size: 0.82rem;+ min-height: 1.2em;+ margin-bottom: 0.6rem;+ }+ .up-modal-actions { display: flex; gap: 0.6rem; justify-content: flex-end; }++ .up-follow-row {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ padding: 0.7rem 0;+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);+ }+ .up-follow-row:last-child { border-bottom: 0; }+ .up-follow-pfp {+ width: 40px;+ height: 40px;+ border-radius: 50%;+ object-fit: cover;+ background: rgba(255, 255, 255, 0.06);+ border: 1px solid rgba(255, 255, 255, 0.1);+ display: flex;+ align-items: center;+ justify-content: center;+ color: rgba(255, 255, 255, 0.4);+ text-decoration: none;+ flex-shrink: 0;+ overflow: hidden;+ }+ .up-follow-pfp img { width: 100%; height: 100%; object-fit: cover; }+ .up-follow-info { flex: 1; min-width: 0; }+ .up-follow-name { color: #fff; text-decoration: none; font-weight: 500; font-size: 0.9rem; }+ .up-follow-name:hover { text-decoration: underline; }+ .up-follow-handle { color: rgba(255, 255, 255, 0.4); font-size: 0.8rem; }+ .up-follow-mini {+ font-family: inherit;+ font-size: 0.78rem;+ font-weight: 500;+ padding: 0.35rem 0.85rem;+ border-radius: 999px;+ border: 1px solid rgba(255, 255, 255, 0.2);+ background: transparent;+ color: #fff;+ cursor: pointer;+ flex-shrink: 0;+ }+ .up-follow-mini[data-following="true"] { color: rgba(255, 255, 255, 0.55); }+ .up-follow-mini:hover { border-color: rgba(255, 255, 255, 0.45); }</style><link rel="stylesheet" href="/nav.css" /><link rel="stylesheet" href="/mobile.css" />@@ -885,6 +1098,7 @@<script type="module">import { mountUserProfile } from '/src/erc8004/user-profile.js';import { onchainBadgeHTML } from '/src/shared/onchain-badge.js';+ import { apiFetch } from '/src/api.js';const esc = (s) =>String(s ?? '').replace(@@ -955,6 +1169,25 @@memories = [],} = data;+ // Who's viewing? Drives the owner-only Edit button vs the Follow button.+ const viewer = await fetch('/api/auth/me', { credentials: 'include' })+ .then((r) => (r.ok ? r.json() : null))+ .then((j) => j?.user || null)+ .catch(() => null);+ const isOwner = Boolean(viewer && user.id && viewer.id === user.id);++ // Follow state (only meaningful for a signed-in non-owner viewer).+ let followState = { following: false, followed_by: false };+ if (viewer && !isOwner) {+ followState = await fetch(+ `/api/users/${encodeURIComponent(user.username)}/follow`,+ { credentials: 'include' },+ )+ .then((r) => (r.ok ? r.json() : null))+ .then((j) => j || followState)+ .catch(() => followState);+ }+// Update page metaconst display = user.display_name || user.username;const title = `@${user.username} — three.ws`;@@ -1000,8 +1233,22 @@? `<img src="${attr(heroAvatar.thumbnail_url)}" alt="${attr(heroAvatar?.name || display)}">`: `<div class="up-hero-3d-empty">◎</div>`;- // Meta line: joined date + social+ // Meta line: location + website + joined date + socialconst metaBits = [];+ if (user.location) {+ metaBits.push(`<span>+ <svg width="11" height="11" viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M8 0a5 5 0 0 0-5 5c0 3.5 5 11 5 11s5-7.5 5-11a5 5 0 0 0-5-5m0 7a2 2 0 1 1 0-4 2 2 0 0 1 0 4"/></svg>+ ${esc(user.location)}+ </span>`);+ }+ if (user.website) {+ let host = user.website;+ try { host = new URL(user.website).host.replace(/^www\./, ''); } catch {}+ metaBits.push(`<a href="${attr(user.website)}" target="_blank" rel="noopener nofollow">+ <svg width="11" height="11" viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M6.9 11.1 5.5 9.7a1 1 0 0 0-.3.2l-1 1a2 2 0 1 1-2.8-2.8l1-1a2 2 0 0 1 2.8 0 1 1 0 0 0 1.4-1.4 4 4 0 0 0-5.6 0l-1 1a4 4 0 0 0 5.6 5.6l1-1a1 1 0 0 0 .3-.8zm7.7-9.7a4 4 0 0 0-5.6 0l-1 1a1 1 0 0 0 1.4 1.4l1-1a2 2 0 0 1 2.8 2.8l-1 1a2 2 0 0 1-2.8 0 1 1 0 0 0-1.4 1.4 4 4 0 0 0 5.6 0l1-1a4 4 0 0 0 0-5.6z"/></svg>+ ${esc(host)}+ </a>`);+ }if (user.created_at) {const joined = new Date(user.created_at);metaBits.push(@@ -1035,14 +1282,9 @@const snsPillSlot = `<span id="up-sns-pill"></span><span id="up-pay-slot"></span>`;(async () => {try {- const [snsRes, meRes] = await Promise.all([- fetch(- `/api/threews/subdomain?label=${encodeURIComponent(user.username)}`,- ),- fetch('/api/auth/me', { credentials: 'include' }).catch(() => null),- ]);- const viewerId = meRes?.ok ? (await meRes.json())?.user?.id : null;- const isOwner = viewerId && user.id && viewerId === user.id;+ const snsRes = await fetch(+ `/api/threews/subdomain?label=${encodeURIComponent(user.username)}`,+ );if (snsRes.ok) {const j = await snsRes.json();@@ -1168,7 +1410,22 @@});}- // Stats strip+ // Stats strip. Followers/Following lead and are clickable (open the+ // social list modal); the rest are static creation counts.+ const followStats = [+ ['followers', 'Followers'],+ ['following', 'Following'],+ ]+ .map(+ ([key, label]) => `+ <button class="up-stat up-stat--link" type="button" data-follows="${key}">+ <span class="up-stat-num">${formatStat(stats[key] || 0)}</span>+ <span class="up-stat-label">${label}</span>+ </button>+ `,+ )+ .join('');+const statDefs = [['avatars', 'Avatars'],['agents', 'Agents'],@@ -1179,16 +1436,19 @@['memories', 'Memories'],];if (stats.widget_views > 0) statDefs.push(['widget_views', 'Widget Views']);- const statsHtml = statDefs- .map(- ([key, label]) => `+ const statsHtml =+ followStats ++ statDefs+ .filter(([key]) => stats[key] > 0)+ .map(+ ([key, label]) => `<div class="up-stat"><span class="up-stat-num">${formatStat(stats[key] || 0)}</span><span class="up-stat-label">${label}</span></div>`,- )- .join('');+ )+ .join('');// Tabs: only show those with content; default to first non-emptyconst tabs = [@@ -1219,14 +1479,48 @@</div>`: '';+ // Banner + profile picture + bio + actions+ const bannerHtml = user.banner_url+ ? `<div class="up-banner" style="background-image:url('${attr(user.banner_url)}')"></div>`+ : '';+ const pfpHtml = user.avatar_url+ ? `<img class="up-pfp" src="${attr(user.avatar_url)}" alt="${attr(display)}" referrerpolicy="no-referrer">`+ : '';+ const bioHtml = user.bio ? `<p class="up-bio">${esc(user.bio)}</p>` : '';++ const followLabel = followState.following+ ? 'Following'+ : followState.followed_by+ ? 'Follow back'+ : 'Follow';+ let actionsHtml = '';+ if (isOwner) {+ actionsHtml = `+ <button class="up-action-btn" id="up-edit-btn" type="button">+ <svg width="13" height="13" viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M11.5 1.5a2.1 2.1 0 0 1 3 3L6 13l-4 1 1-4z"/></svg>+ Edit profile+ </button>+ <a class="up-action-btn" href="/feed">Your feed</a>`;+ } else if (viewer) {+ actionsHtml = `<button class="up-action-btn ${followState.following ? 'up-action-btn--following' : 'up-action-btn--primary'}" id="up-follow-btn" type="button" data-following="${followState.following}">+ <span class="up-follow-label">${esc(followLabel)}</span>+ </button>`;+ } else {+ actionsHtml = `<a class="up-action-btn up-action-btn--primary" href="/login?return=${encodeURIComponent('/u/' + user.username)}">Follow</a>`;+ }+rootEl.innerHTML = `- <div class="up-hero-rich">+ ${bannerHtml}+ <div class="up-hero-rich${user.banner_url ? ' up-banner-pad' : ''}"><div class="up-hero-3d">${heroMedia}</div><div class="up-hero-info">+ ${pfpHtml}<h1 class="up-display-name">${esc(display)}</h1><p class="up-handle">@${esc(user.username)}</p>- ${metaBits.length ? `<div class="up-meta-line">${metaBits.join('')}</div>` : ''}- <div class="up-pill-row" style="display:flex;flex-wrap:wrap;gap:.4rem;align-items:center">+ ${bioHtml}+ ${metaBits.length ? `<div class="up-bio-meta">${metaBits.join('')}</div>` : ''}+ <div class="up-actions">${actionsHtml}</div>+ <div class="up-pill-row" style="display:flex;flex-wrap:wrap;gap:.4rem;align-items:center;margin-top:.6rem">${walletPill}${snsPillSlot}</div>@@ -1271,6 +1565,229 @@});});});++ // Follow / unfollow+ const followBtn = rootEl.querySelector('#up-follow-btn');+ if (followBtn) {+ followBtn.addEventListener('click', async () => {+ const wasFollowing = followBtn.dataset.following === 'true';+ followBtn.disabled = true;+ try {+ const r = await apiFetch(+ `/api/users/${encodeURIComponent(user.username)}/follow`,+ { method: wasFollowing ? 'DELETE' : 'POST', credentials: 'include' },+ );+ if (!r.ok) throw new Error('follow failed');+ const j = await r.json();+ const nowFollowing = Boolean(j.following);+ followBtn.dataset.following = String(nowFollowing);+ followBtn.classList.toggle('up-action-btn--following', nowFollowing);+ followBtn.classList.toggle('up-action-btn--primary', !nowFollowing);+ followBtn.querySelector('.up-follow-label').textContent = nowFollowing+ ? 'Following'+ : j.followed_by+ ? 'Follow back'+ : 'Follow';+ // Reflect the new follower count on the strip.+ const fc = rootEl.querySelector('[data-follows="followers"] .up-stat-num');+ if (fc && typeof j.followers_count === 'number') {+ fc.textContent = formatStat(j.followers_count);+ }+ } catch {+ /* leave button as-is; user can retry */+ } finally {+ followBtn.disabled = false;+ }+ });+ }++ // Edit profile (owner only)+ const editBtn = rootEl.querySelector('#up-edit-btn');+ if (editBtn) editBtn.addEventListener('click', () => openEditModal(user));++ // Followers / following lists+ rootEl.querySelectorAll('[data-follows]').forEach((btn) => {+ btn.addEventListener('click', () =>+ openFollowsModal(user.username, btn.dataset.follows, viewer),+ );+ });+ }++ // ── Edit profile modal ──────────────────────────────────────────────+ function openEditModal(user) {+ const fields = [+ { key: 'display_name', label: 'Display name', value: user.display_name || '', max: 80 },+ { key: 'bio', label: 'Bio', value: user.bio || '', max: 280, textarea: true },+ { key: 'location', label: 'Location', value: user.location || '', max: 80, placeholder: 'Where you are' },+ { key: 'website', label: 'Website', value: user.website || '', max: 500, placeholder: 'https://…' },+ { key: 'avatar_url', label: 'Profile picture URL', value: user.avatar_url || '', max: 500, placeholder: 'https://…' },+ { key: 'banner_url', label: 'Banner image URL', value: user.banner_url || '', max: 500, placeholder: 'https://…' },+ ];+ const body = fields+ .map((f) => {+ const counter = f.max+ ? `<span class="up-field-count" data-count-for="${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>`;+ })+ .join('');++ const modal = buildModal('Edit profile', `+ <div class="up-modal-error" id="up-edit-error"></div>+ <form id="up-edit-form">+ ${body}+ <div class="up-modal-actions">+ <button type="button" class="up-action-btn" data-close>Cancel</button>+ <button type="submit" class="up-action-btn up-action-btn--primary" id="up-edit-save">Save</button>+ </div>+ </form>+ `);++ // Live char counters+ modal.querySelectorAll('input[maxlength], textarea[maxlength]').forEach((el) => {+ el.addEventListener('input', () => {+ const c = modal.querySelector(`[data-count-for="${el.name}"]`);+ if (c) c.textContent = `${el.value.length}/${el.getAttribute('maxlength')}`;+ });+ });++ const form = modal.querySelector('#up-edit-form');+ const errEl = modal.querySelector('#up-edit-error');+ const saveBtn = modal.querySelector('#up-edit-save');+ form.addEventListener('submit', async (e) => {+ e.preventDefault();+ errEl.textContent = '';+ saveBtn.disabled = true;+ saveBtn.textContent = 'Saving…';+ const payload = {};+ for (const f of fields) {+ payload[f.key] = (form.elements[f.key].value || '').trim();+ }+ try {+ const r = await apiFetch('/api/auth/profile', {+ method: 'PATCH',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(payload),+ });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) {+ errEl.textContent =+ j.error_description || j.issues?.[0]?.message || 'Could not save changes.';+ saveBtn.disabled = false;+ saveBtn.textContent = 'Save';+ return;+ }+ // Reload to reflect the saved profile cleanly.+ location.reload();+ } catch {+ errEl.textContent = 'Network error — try again.';+ saveBtn.disabled = false;+ saveBtn.textContent = 'Save';+ }+ });+ }++ // ── Followers / following modal ─────────────────────────────────────+ async function openFollowsModal(username, type, viewer) {+ const titles = { followers: 'Followers', following: 'Following' };+ const modal = buildModal(+ titles[type] || 'People',+ `<div id="up-follows-list"><p class="up-empty" style="padding:1rem 0">Loading…</p></div>`,+ );+ const listEl = modal.querySelector('#up-follows-list');+ try {+ const r = await fetch(+ `/api/users/${encodeURIComponent(username)}/follows?type=${type}&limit=100`,+ { credentials: 'include' },+ );+ const j = await r.json();+ const users = j.users || [];+ if (!users.length) {+ listEl.innerHTML = `<p class="up-empty" style="padding:1.5rem 0;text-align:center">${+ type === 'followers' ? 'No followers yet.' : 'Not following anyone yet.'+ }</p>`;+ return;+ }+ listEl.innerHTML = users+ .map((u) => {+ const pfp = u.avatar_url+ ? `<img src="${attr(u.avatar_url)}" alt="" referrerpolicy="no-referrer">`+ : '◎';+ const btn =+ viewer && !u.is_self+ ? `<button class="up-follow-mini" data-username="${attr(u.username)}" data-following="${u.is_following}">${u.is_following ? 'Following' : 'Follow'}</button>`+ : '';+ return `+ <div class="up-follow-row">+ <a class="up-follow-pfp" href="/u/${attr(u.username)}">${pfp}</a>+ <div class="up-follow-info">+ <a class="up-follow-name" href="/u/${attr(u.username)}">${esc(u.display_name)}</a>+ <div class="up-follow-handle">@${esc(u.username)}</div>+ </div>+ ${btn}+ </div>`;+ })+ .join('');++ // In-modal follow toggles+ listEl.querySelectorAll('.up-follow-mini').forEach((b) => {+ b.addEventListener('click', async () => {+ const uname = b.dataset.username;+ const following = b.dataset.following === 'true';+ b.disabled = true;+ try {+ const rr = await apiFetch(+ `/api/users/${encodeURIComponent(uname)}/follow`,+ { method: following ? 'DELETE' : 'POST', credentials: 'include' },+ );+ if (!rr.ok) throw new Error();+ const jj = await rr.json();+ b.dataset.following = String(jj.following);+ b.textContent = jj.following ? 'Following' : 'Follow';+ } catch {+ /* retry on next click */+ } finally {+ b.disabled = false;+ }+ });+ });+ } catch {+ listEl.innerHTML = `<p class="up-empty" style="padding:1.5rem 0;text-align:center">Could not load list.</p>`;+ }+ }++ // Shared modal scaffold. Returns the modal element (already in the DOM).+ function buildModal(title, innerHtml) {+ document.getElementById('up-modal-backdrop')?.remove();+ const backdrop = document.createElement('div');+ backdrop.className = 'up-modal-backdrop';+ backdrop.id = 'up-modal-backdrop';+ backdrop.setAttribute('role', 'dialog');+ backdrop.setAttribute('aria-modal', 'true');+ backdrop.innerHTML = `+ <div class="up-modal">+ <div class="up-modal-head">+ <h3>${esc(title)}</h3>+ <button class="up-modal-close" aria-label="Close" data-close>×</button>+ </div>+ <div class="up-modal-body">${innerHtml}</div>+ </div>`;+ document.body.appendChild(backdrop);+ const close = () => backdrop.remove();+ backdrop.addEventListener('click', (e) => {+ if (e.target === backdrop || e.target.closest('[data-close]')) close();+ });+ document.addEventListener('keydown', function onKey(e) {+ if (e.key === 'Escape') {+ close();+ document.removeEventListener('keydown', onKey);+ }+ });+ return backdrop;}function formatStat(n) {diff --git a/pages/walk-analytics.html b/pages/walk-analytics.htmlnew file mode 100644index 000000000..1eff88cde--- /dev/null+++ b/pages/walk-analytics.html@@ -0,0 +1,330 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash */(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, viewport-fit=cover" />+ <title>Walk Analytics · three.ws</title>+ <meta name="description" content="Analytics for your embedded walking avatars — sessions, time spent, distance walked, conversion events, and top embed locations. Your private creator dashboard." />+ <link rel="canonical" href="https://three.ws/walk-analytics" />+ <meta name="robots" content="noindex" />+ <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" />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Walk Analytics · three.ws" />+ <meta property="og:description" content="Sessions, time, distance, conversions and top embed locations for your walking avatars." />+ <meta name="theme-color" content="#0a0a0a" />+ <style>+ .wa-shell { max-width: 1080px; margin: 0 auto; padding: var(--space-lg) var(--space-md) var(--space-2xl); }+ .wa-hero { padding: var(--space-xl) 0 var(--space-md); }+ .wa-title { font: var(--weight-bold) var(--text-2xl)/1.05 var(--font-display); color: var(--color-text-bright); margin: 0 0 var(--space-sm); letter-spacing: -0.02em; }+ .wa-sub { font: var(--weight-regular) var(--text-base)/var(--leading-normal) var(--font-body); color: var(--color-text-dim); margin: 0; max-width: 62ch; }++ .wa-controls { display: flex; flex-wrap: wrap; gap: var(--space-sm); align-items: flex-end; margin: var(--space-lg) 0 var(--space-md); }+ .wa-field { display: flex; flex-direction: column; gap: var(--space-3xs); }+ .wa-field label { font: var(--weight-semibold) var(--text-2xs)/1 var(--font-mono); text-transform: uppercase; letter-spacing: 0.06em; color: var(--color-text-faint); }+ .wa-input, .wa-select {+ appearance: none; background: var(--surface-1); color: var(--color-text);+ border: 1px solid var(--color-border); border-radius: var(--radius-md);+ padding: var(--space-xs) var(--space-sm); font: var(--weight-medium) var(--text-md)/1.2 var(--font-body);+ min-height: 38px; transition: border-color var(--duration-fast) var(--ease-standard);+ }+ .wa-input:hover, .wa-select:hover { border-color: var(--color-border-strong); }+ .wa-input:focus-visible, .wa-select:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: var(--focus-ring-offset); }+ .wa-select { min-width: 200px; }++ .wa-cards { display: grid; grid-template-columns: repeat(4, 1fr); gap: var(--space-sm); margin: var(--space-md) 0; }+ .wa-card { background: var(--surface-1); border: 1px solid var(--color-border); border-radius: var(--radius-lg); padding: var(--space-md); }+ .wa-card-label { font: var(--weight-semibold) var(--text-2xs)/1 var(--font-mono); text-transform: uppercase; letter-spacing: 0.06em; color: var(--color-text-faint); margin: 0 0 var(--space-xs); }+ .wa-card-value { font: var(--weight-bold) var(--text-xl)/1 var(--font-display); color: var(--color-text-bright); }++ .wa-panel { background: var(--surface-1); border: 1px solid var(--color-border); border-radius: var(--radius-lg); padding: var(--space-md); margin: var(--space-md) 0; }+ .wa-panel-title { font: var(--weight-semibold) var(--text-lg)/1.2 var(--font-display); color: var(--color-text-bright); margin: 0 0 var(--space-sm); }++ .wa-chart-wrap { position: relative; width: 100%; }+ .wa-chart { width: 100%; height: auto; display: block; overflow: visible; }+ .wa-chart-legend { display: flex; gap: var(--space-md); margin-top: var(--space-sm); flex-wrap: wrap; }+ .wa-legend-item { display: inline-flex; align-items: center; gap: var(--space-2xs); font: var(--weight-medium) var(--text-sm)/1 var(--font-body); color: var(--color-text-dim); cursor: pointer; user-select: none; }+ .wa-legend-swatch { width: 10px; height: 10px; border-radius: 3px; flex: none; }+ .wa-legend-item.is-off { opacity: 0.4; }++ .wa-table { width: 100%; border-collapse: collapse; }+ .wa-table th, .wa-table td { text-align: left; padding: var(--space-sm); border-bottom: 1px solid var(--color-border); font: var(--weight-regular) var(--text-md)/1.3 var(--font-body); color: var(--color-text); }+ .wa-table th { font: var(--weight-semibold) var(--text-2xs)/1 var(--font-mono); text-transform: uppercase; letter-spacing: 0.06em; color: var(--color-text-faint); }+ .wa-table td.num, .wa-table th.num { text-align: right; font-family: var(--font-mono); }+ .wa-table tr:last-child td { border-bottom: 0; }+ .wa-origin { font-family: var(--font-mono); color: var(--color-text-bright); }+ .wa-rate { color: var(--color-success); font-weight: var(--weight-semibold); }++ .wa-state { padding: var(--space-2xl) var(--space-md); text-align: center; }+ .wa-state-title { font: var(--weight-semibold) var(--text-lg)/1.2 var(--font-display); color: var(--color-text-bright); margin: 0 0 var(--space-xs); }+ .wa-state-msg { font: var(--weight-regular) var(--text-md)/var(--leading-normal) var(--font-body); color: var(--color-text-dim); margin: 0 auto var(--space-md); max-width: 48ch; }+ .wa-cta { display: inline-flex; align-items: center; gap: var(--space-xs); padding: var(--space-sm) var(--space-lg); border-radius: var(--radius-md); background: var(--accent); color: #0a0a0a; font: var(--weight-semibold) var(--text-md)/1 var(--font-body); text-decoration: none; transition: opacity var(--duration-fast) var(--ease-standard); border: 0; cursor: pointer; }+ .wa-cta:hover { opacity: 0.85; }+ .wa-cta.ghost { background: var(--surface-2); color: var(--color-text); border: 1px solid var(--color-border); }++ .wa-empty { padding: var(--space-xl) var(--space-md); text-align: center; color: var(--color-text-dim); font: var(--weight-regular) var(--text-md)/1.4 var(--font-body); }++ .wa-skel { height: 14px; border-radius: var(--radius-sm); background: linear-gradient(90deg, var(--surface-2) 25%, var(--surface-3) 37%, var(--surface-2) 63%); background-size: 400% 100%; animation: wa-shimmer 1.4s ease infinite; }+ @keyframes wa-shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }+ @media (prefers-reduced-motion: reduce) { .wa-skel { animation: none; } }++ [hidden] { display: none !important; }+ @media (max-width: 820px) { .wa-cards { grid-template-columns: repeat(2, 1fr); } }+ @media (max-width: 480px) { .wa-cards { grid-template-columns: 1fr; } .wa-select { min-width: 0; width: 100%; } .wa-title { font-size: var(--text-xl); } }+ </style>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="wa-shell" aria-labelledby="wa-title">+ <section class="wa-hero">+ <h1 id="wa-title" class="wa-title">Walk Analytics</h1>+ <p class="wa-sub">How your embedded walking avatars are performing — sessions, time spent, distance walked, conversion events, and where they're running. Private to you, the creator.</p>+ </section>++ <!-- Auth / ownership states swap in here -->+ <div id="wa-gate" hidden></div>++ <!-- Dashboard (shown when authed + owns at least one avatar) -->+ <div id="wa-dash" hidden>+ <section class="wa-controls" aria-label="Filters">+ <div class="wa-field">+ <label for="wa-avatar">Avatar</label>+ <select id="wa-avatar" class="wa-select" aria-label="Choose an avatar"></select>+ </div>+ <div class="wa-field">+ <label for="wa-from">From</label>+ <input type="date" id="wa-from" class="wa-input" aria-label="From date" />+ </div>+ <div class="wa-field">+ <label for="wa-to">To</label>+ <input type="date" id="wa-to" class="wa-input" aria-label="To date" />+ </div>+ <button type="button" id="wa-apply" class="wa-cta ghost">Apply</button>+ </section>++ <section class="wa-cards" id="wa-cards" aria-label="Summary">+ <div class="wa-card"><p class="wa-card-label">Sessions</p><div class="wa-card-value" id="wa-c-sessions">—</div></div>+ <div class="wa-card"><p class="wa-card-label">Avg duration</p><div class="wa-card-value" id="wa-c-duration">—</div></div>+ <div class="wa-card"><p class="wa-card-label">Distance walked</p><div class="wa-card-value" id="wa-c-distance">—</div></div>+ <div class="wa-card"><p class="wa-card-label">Unique sites</p><div class="wa-card-value" id="wa-c-origins">—</div></div>+ </section>++ <section class="wa-panel" aria-label="Sessions over time">+ <h2 class="wa-panel-title">Over time</h2>+ <div class="wa-chart-wrap" id="wa-chart-wrap"></div>+ <div class="wa-chart-legend" id="wa-legend"></div>+ </section>++ <section class="wa-panel" aria-label="Top embed locations">+ <h2 class="wa-panel-title">Top embed locations</h2>+ <div id="wa-origins"></div>+ </section>++ <section class="wa-panel" aria-label="Conversion events">+ <h2 class="wa-panel-title">Events</h2>+ <p class="wa-sub" style="margin:0 0 12px;font-size:var(--text-sm)">Fire events from your embed with <code style="font-family:var(--font-mono)">window.ThreeWalkAvatar.track('subscribe', { value: 9 })</code>. Conversion rate is events ÷ sessions.</p>+ <div id="wa-events"></div>+ </section>+ </div>+ </main>++ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>++ <script type="module">+ const gate = document.getElementById('wa-gate');+ const dash = document.getElementById('wa-dash');+ const avatarSel = document.getElementById('wa-avatar');+ const fromEl = document.getElementById('wa-from');+ const toEl = document.getElementById('wa-to');+ const applyEl = document.getElementById('wa-apply');++ const esc = (s) => String(s).replace(/[<>&"']/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' }[c]));+ const isoDate = (d) => d.toISOString().slice(0, 10);++ function showGate(html) { gate.innerHTML = html; gate.hidden = false; dash.hidden = true; }++ function fmtDistance(m) { return m >= 1000 ? (m / 1000).toFixed(2) + ' km' : Math.round(m) + ' m'; }+ function fmtDuration(s) {+ s = Math.round(s);+ if (s >= 3600) return (s / 3600).toFixed(1) + ' h';+ if (s >= 60) return Math.round(s / 60) + ' min ' + (s % 60) + ' s';+ return s + ' s';+ }++ async function boot() {+ let mine;+ try {+ const res = await fetch('/api/avatars/mine?limit=100', { credentials: 'include' });+ if (res.status === 401) {+ return showGate(`<div class="wa-state"><p class="wa-state-title">Sign in to view your analytics</p><p class="wa-state-msg">Walk analytics are private to the creator who owns the avatar. Sign in to see how your embedded walking avatars are performing.</p><a class="wa-cta" href="/login?next=/walk-analytics">Sign in →</a></div>`);+ }+ if (!res.ok) throw new Error('HTTP ' + res.status);+ mine = await res.json();+ } catch (err) {+ return showGate(`<div class="wa-state"><p class="wa-state-title">Couldn't load your avatars</p><p class="wa-state-msg">${esc(err.message || 'Something went wrong.')}</p><button class="wa-cta" type="button" onclick="location.reload()">Retry</button></div>`);+ }++ const avatars = (mine && mine.avatars) || [];+ if (!avatars.length) {+ return showGate(`<div class="wa-state"><p class="wa-state-title">No avatars yet</p><p class="wa-state-msg">Create a walking avatar and embed it on your site. Once it starts walking, your sessions, distance, and conversion events will show up here.</p><a class="wa-cta" href="/create">Create an avatar →</a> <a class="wa-cta ghost" href="/walk-embed" style="margin-left:8px">Get embed code</a></div>`);+ }++ gate.hidden = true;+ dash.hidden = false;+ avatarSel.innerHTML = avatars.map((a) => `<option value="${esc(a.id)}">${esc(a.name || a.slug || 'Untitled')}</option>`).join('');++ const today = new Date();+ const start = new Date(); start.setUTCDate(start.getUTCDate() - 29);+ fromEl.value = isoDate(start);+ toEl.value = isoDate(today);+ toEl.max = isoDate(today);+ fromEl.max = isoDate(today);++ // Preselect avatar from ?avatarId if present.+ const qpAvatar = new URLSearchParams(location.search).get('avatarId');+ if (qpAvatar && avatars.some((a) => a.id === qpAvatar)) avatarSel.value = qpAvatar;++ avatarSel.addEventListener('change', loadAnalytics);+ applyEl.addEventListener('click', loadAnalytics);+ loadAnalytics();+ }++ function cardSkeletons() {+ ['wa-c-sessions', 'wa-c-duration', 'wa-c-distance', 'wa-c-origins'].forEach((id) => {+ document.getElementById(id).innerHTML = '<span class="wa-skel" style="display:inline-block;width:60px"></span>';+ });+ document.getElementById('wa-chart-wrap').innerHTML = '<div class="wa-skel" style="height:220px;border-radius:10px"></div>';+ document.getElementById('wa-origins').innerHTML = '<div class="wa-skel" style="height:80px;border-radius:10px"></div>';+ document.getElementById('wa-events').innerHTML = '<div class="wa-skel" style="height:80px;border-radius:10px"></div>';+ }++ async function loadAnalytics() {+ const avatarId = avatarSel.value;+ if (!avatarId) return;+ cardSkeletons();+ const params = new URLSearchParams({ avatarId, from: fromEl.value, to: toEl.value });+ let data;+ try {+ const res = await fetch('/api/walk/analytics?' + params.toString(), { credentials: 'include' });+ if (res.status === 403) {+ return showGate(`<div class="wa-state"><p class="wa-state-title">Not your avatar</p><p class="wa-state-msg">You can only view analytics for avatars you own.</p><a class="wa-cta" href="/walk-analytics">Back to your avatars</a></div>`);+ }+ if (!res.ok) throw new Error('HTTP ' + res.status);+ data = await res.json();+ } catch (err) {+ document.getElementById('wa-chart-wrap').innerHTML = `<div class="wa-empty">Couldn't load analytics — ${esc(err.message || 'error')}. <button class="wa-cta ghost" type="button" style="margin-left:8px" onclick="this.dispatchEvent(new CustomEvent('retry',{bubbles:true}))">Retry</button></div>`;+ document.getElementById('wa-chart-wrap').addEventListener('retry', loadAnalytics, { once: true });+ return;+ }++ document.getElementById('wa-c-sessions').textContent = data.totalSessions.toLocaleString();+ document.getElementById('wa-c-duration').textContent = data.totalSessions ? fmtDuration(data.avgDurationSec) : '—';+ document.getElementById('wa-c-distance').textContent = fmtDistance(data.totalDistance);+ document.getElementById('wa-c-origins').textContent = data.uniqueOrigins.toLocaleString();++ renderChart(data.timeSeries || []);+ renderOrigins(data.topOrigins || []);+ renderEvents(data.events || [], data.totalSessions);+ }++ // ── Hand-rolled SVG line/area chart (sessions + distance) ──────────────+ const chartState = { sessions: true, distance: true };+ let lastSeries = [];+ function renderChart(series) {+ lastSeries = series;+ const wrap = document.getElementById('wa-chart-wrap');+ const legend = document.getElementById('wa-legend');+ const hasData = series.some((d) => d.sessions > 0 || d.distanceMeters > 0);+ if (!series.length || !hasData) {+ wrap.innerHTML = '<div class="wa-empty">No walks recorded in this range yet. Embed your avatar and check back — sessions appear within ~60 seconds of a visit.</div>';+ legend.innerHTML = '';+ return;+ }++ const W = 920, H = 240, padL = 44, padR = 16, padT = 16, padB = 28;+ const innerW = W - padL - padR, innerH = H - padT - padB;+ const n = series.length;+ const xAt = (i) => padL + (n === 1 ? innerW / 2 : (i / (n - 1)) * innerW);++ const maxS = Math.max(1, ...series.map((d) => d.sessions));+ const maxD = Math.max(1, ...series.map((d) => d.distanceMeters));+ const ySessions = (v) => padT + innerH - (v / maxS) * innerH;+ const yDistance = (v) => padT + innerH - (v / maxD) * innerH;++ const colSessions = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim() || '#fff';+ const colDistance = '#8b5cf6';++ function path(yFn, key) {+ return series.map((d, i) => `${i === 0 ? 'M' : 'L'}${xAt(i).toFixed(1)},${yFn(d[key]).toFixed(1)}`).join(' ');+ }+ function area(yFn, key) {+ const top = series.map((d, i) => `${i === 0 ? 'M' : 'L'}${xAt(i).toFixed(1)},${yFn(d[key]).toFixed(1)}`).join(' ');+ return `${top} L${xAt(n - 1).toFixed(1)},${(padT + innerH).toFixed(1)} L${xAt(0).toFixed(1)},${(padT + innerH).toFixed(1)} Z`;+ }++ // Gridlines + y labels (sessions axis).+ let grid = '';+ for (let g = 0; g <= 4; g++) {+ const y = padT + (g / 4) * innerH;+ const val = Math.round(maxS * (1 - g / 4));+ grid += `<line x1="${padL}" y1="${y.toFixed(1)}" x2="${W - padR}" y2="${y.toFixed(1)}" stroke="var(--color-border)" stroke-width="1" />`;+ grid += `<text x="${padL - 8}" y="${(y + 4).toFixed(1)}" text-anchor="end" font-size="10" fill="var(--color-text-faint)" font-family="var(--font-mono)">${val}</text>`;+ }+ // x labels (first, middle, last).+ let xlabels = '';+ [0, Math.floor((n - 1) / 2), n - 1].forEach((i) => {+ if (i < 0 || i >= n) return;+ const lbl = series[i].date.slice(5); // MM-DD+ xlabels += `<text x="${xAt(i).toFixed(1)}" y="${H - 8}" text-anchor="middle" font-size="10" fill="var(--color-text-faint)" font-family="var(--font-mono)">${lbl}</text>`;+ });++ const dots = series.map((d, i) => chartState.sessions && d.sessions > 0+ ? `<circle cx="${xAt(i).toFixed(1)}" cy="${ySessions(d.sessions).toFixed(1)}" r="2.5" fill="${colSessions}"><title>${esc(d.date)}: ${d.sessions} sessions, ${fmtDistance(d.distanceMeters)}</title></circle>`+ : '').join('');++ wrap.innerHTML = `+ <svg class="wa-chart" viewBox="0 0 ${W} ${H}" preserveAspectRatio="xMidYMid meet" role="img" aria-label="Sessions and distance over time">+ ${grid}${xlabels}+ ${chartState.distance ? `<path d="${area(yDistance, 'distanceMeters')}" fill="${colDistance}" fill-opacity="0.10" />` : ''}+ ${chartState.distance ? `<path d="${path(yDistance, 'distanceMeters')}" fill="none" stroke="${colDistance}" stroke-width="2" stroke-linejoin="round" />` : ''}+ ${chartState.sessions ? `<path d="${path(ySessions, 'sessions')}" fill="none" stroke="${colSessions}" stroke-width="2" stroke-linejoin="round" />` : ''}+ ${dots}+ </svg>`;++ legend.innerHTML = `+ <span class="wa-legend-item ${chartState.sessions ? '' : 'is-off'}" data-k="sessions" role="button" tabindex="0"><span class="wa-legend-swatch" style="background:${colSessions}"></span>Sessions</span>+ <span class="wa-legend-item ${chartState.distance ? '' : 'is-off'}" data-k="distance" role="button" tabindex="0"><span class="wa-legend-swatch" style="background:${colDistance}"></span>Distance</span>`;+ legend.querySelectorAll('.wa-legend-item').forEach((el) => {+ const toggle = () => { const k = el.dataset.k; chartState[k] = !chartState[k]; renderChart(lastSeries); };+ el.addEventListener('click', toggle);+ el.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggle(); } });+ });+ }++ function renderOrigins(origins) {+ const el = document.getElementById('wa-origins');+ if (!origins.length) { el.innerHTML = '<div class="wa-empty">No embed origins recorded yet. When your avatar runs inside an iframe on another site, that host appears here.</div>'; return; }+ el.innerHTML = `<table class="wa-table"><thead><tr><th>Origin</th><th class="num">Sessions</th><th class="num">Distance</th></tr></thead><tbody>${origins.map((o) => `<tr><td class="wa-origin">${esc(o.origin)}</td><td class="num">${o.sessions.toLocaleString()}</td><td class="num">${fmtDistance(o.distanceMeters)}</td></tr>`).join('')}</tbody></table>`;+ }++ function renderEvents(events, sessions) {+ const el = document.getElementById('wa-events');+ if (!events.length) { el.innerHTML = '<div class="wa-empty">No conversion events tracked yet. Call <code style="font-family:var(--font-mono)">ThreeWalkAvatar.track(...)</code> from your embed to measure subscribes, purchases, plays, and more.</div>'; return; }+ el.innerHTML = `<table class="wa-table"><thead><tr><th>Event</th><th class="num">Count</th><th class="num">Conversion</th></tr></thead><tbody>${events.map((e) => `<tr><td>${esc(e.name)}</td><td class="num">${e.count.toLocaleString()}</td><td class="num wa-rate">${sessions ? e.conversionRate.toFixed(2) + '%' : '—'}</td></tr>`).join('')}</tbody></table>`;+ }++ boot();+ </script>+ </body>+</html>diff --git a/pages/walk-landing.html b/pages/walk-landing.htmlnew file mode 100644index 000000000..ed5974282--- /dev/null+++ b/pages/walk-landing.html@@ -0,0 +1,1152 @@+<!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 http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>Walk — your avatar walks anywhere on the web · three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta name="author" content="nirholas" />+ <meta+ name="description"+ content="Your 3D avatar walks anywhere on the web. Drive it with WASD or a touch joystick, drop it on any site with one tag, and let it stroll across real pages with the Chrome extension. No app install."+ />+ <meta name="theme-color" content="#000000" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/walk" />+ <meta property="og:title" content="Walk — your avatar walks anywhere on the web · three.ws" />+ <meta+ property="og:description"+ content="Drive your 3D avatar with WASD or a joystick, embed it on any site with one tag, and let it walk across real web pages. No app install."+ />+ <meta property="og:image" content="https://three.ws/api/walk-og" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta property="og:image:alt" content="A 3D avatar walking in the three.ws Walk experience" />+ <meta property="og:locale" content="en_US" />++ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Walk — your avatar walks anywhere on the web · three.ws" />+ <meta+ name="twitter:description"+ content="Drive your 3D avatar with WASD or a joystick, embed it on any site with one tag, and let it walk across real web pages."+ />+ <meta name="twitter:image" content="https://three.ws/api/walk-og" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />++ <link rel="canonical" href="https://three.ws/walk" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />++ <link rel="preconnect" href="https://three.ws" />+ <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" />+ <script defer src="/footer-newsletter.js"></script>++ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@type": "WebApplication",+ "name": "three.ws Walk",+ "url": "https://three.ws/walk",+ "applicationCategory": "MultimediaApplication",+ "operatingSystem": "Any (web browser)",+ "browserRequirements": "Requires a WebGL-capable browser",+ "description": "Drive a 3D avatar around the browser with WASD or a touch joystick, embed it on any website with one tag, and walk it across real web pages with the Chrome extension.",+ "offers": { "@type": "Offer", "price": "0", "priceCurrency": "USD" },+ "isPartOf": { "@type": "WebSite", "name": "three.ws", "url": "https://three.ws" }+ }+ </script>++ <style>+ /* ────────────────────────────────────────────────────────────────+ Walk landing — page-scoped styles. Token vars only; no hardcoded+ colour / radius / type / spacing literals. Mirrors the marketing+ rhythm of /features (eyebrow → display headline → sub → CTAs).+ ──────────────────────────────────────────────────────────────── */+ .wl-main {+ max-width: 1180px;+ margin: 0 auto;+ padding: 0 var(--space-md);+ }++ .wl-eyebrow {+ display: inline-flex;+ align-items: center;+ gap: var(--space-2);+ font-family: var(--font-mono);+ font-size: var(--text-sm);+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--color-text-dim);+ margin: 0 0 var(--space-4);+ }+ .wl-eyebrow::before {+ content: "";+ width: var(--space-5);+ height: 1px;+ background: var(--color-border-strong);+ }++ .wl-section {+ padding: var(--space-2xl) 0;+ border-top: 1px solid var(--color-hairline);+ }+ .wl-section-head {+ max-width: 44rem;+ margin: 0 auto var(--space-xl);+ text-align: center;+ }+ .wl-section-title {+ font-family: var(--font-display);+ font-weight: var(--weight-bold);+ font-size: var(--text-xl);+ line-height: var(--leading-tight);+ color: var(--color-text-bright);+ margin: 0 0 var(--space-3);+ letter-spacing: -0.01em;+ }+ .wl-section-sub {+ font-size: var(--text-base);+ line-height: var(--leading-normal);+ color: var(--color-text-dim);+ margin: 0;+ }++ /* ── Hero ───────────────────────────────────────────────────── */+ .wl-hero {+ display: grid;+ grid-template-columns: 1.05fr 0.95fr;+ gap: var(--space-xl);+ align-items: center;+ padding: var(--space-2xl) 0 var(--space-xl);+ }+ .wl-hero-title {+ font-family: var(--font-display);+ font-weight: var(--weight-bold);+ font-size: var(--text-2xl);+ line-height: 1.04;+ letter-spacing: -0.02em;+ color: var(--color-text-bright);+ margin: 0 0 var(--space-4);+ }+ .wl-hero-sub {+ font-size: var(--text-lg);+ line-height: var(--leading-normal);+ color: var(--color-text-dim);+ margin: 0 0 var(--space-6);+ max-width: 34rem;+ }+ .wl-cta-row {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-3);+ align-items: center;+ }+ .wl-hero-meta {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-5);+ margin-top: var(--space-7);+ font-size: var(--text-sm);+ color: var(--color-text-faint);+ }+ .wl-hero-meta span {+ display: inline-flex;+ align-items: center;+ gap: var(--space-2);+ }+ .wl-hero-meta svg {+ width: 1rem;+ height: 1rem;+ color: var(--color-text-dim);+ }++ /* ── Live embed frame (reusable card) ───────────────────────── */+ .wl-frame {+ position: relative;+ border: 1px solid var(--color-border);+ border-radius: var(--radius-lg);+ overflow: hidden;+ background:+ radial-gradient(120% 90% at 50% 0%, var(--surface-2), transparent 70%),+ var(--color-bg);+ box-shadow: var(--shadow-2);+ }+ .wl-frame--hero {+ aspect-ratio: 4 / 5;+ box-shadow: var(--shadow-3);+ }+ .wl-frame iframe {+ display: block;+ width: 100%;+ height: 100%;+ border: 0;+ background: transparent;+ }+ .wl-frame-chrome {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ padding: var(--space-2) var(--space-3);+ border-bottom: 1px solid var(--color-hairline);+ background: var(--surface-1);+ }+ .wl-frame-dot {+ width: 9px;+ height: 9px;+ border-radius: var(--radius-pill);+ background: var(--surface-3);+ }+ .wl-frame-label {+ margin-left: var(--space-2);+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ color: var(--color-text-faint);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }+ .wl-frame-stage {+ position: relative;+ }+ .wl-frame--hero .wl-frame-stage {+ height: 100%;+ }+ .wl-frame-hint {+ position: absolute;+ left: 50%;+ bottom: var(--space-3);+ transform: translateX(-50%);+ padding: var(--space-1) var(--space-3);+ border-radius: var(--radius-pill);+ background: var(--surface-glass);+ border: 1px solid var(--color-border);+ backdrop-filter: blur(var(--blur-sm));+ -webkit-backdrop-filter: blur(var(--blur-sm));+ font-size: var(--text-xs);+ color: var(--color-text-dim);+ pointer-events: none;+ z-index: 2;+ }++ /* ── Demo strip ─────────────────────────────────────────────── */+ .wl-demos {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: var(--space-4);+ }+ .wl-demo .wl-frame-stage {+ aspect-ratio: 3 / 4;+ }+ .wl-demo-caption {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: var(--space-3);+ margin-top: var(--space-3);+ }+ .wl-demo-name {+ font-weight: var(--weight-semibold);+ color: var(--color-text-bright);+ font-size: var(--text-ui);+ }+ .wl-demo-desc {+ font-size: var(--text-sm);+ color: var(--color-text-faint);+ }++ /* ── How it works ───────────────────────────────────────────── */+ .wl-steps {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: var(--space-5);+ }+ .wl-step {+ display: flex;+ flex-direction: column;+ border: 1px solid var(--color-border);+ border-radius: var(--radius-lg);+ background: var(--surface-1);+ overflow: hidden;+ transition: border-color var(--dur-fast) var(--ease-standard),+ transform var(--dur-fast) var(--ease-standard);+ }+ .wl-step:hover {+ border-color: var(--color-border-strong);+ transform: translateY(-2px);+ }+ .wl-step .wl-frame-stage {+ aspect-ratio: 16 / 11;+ border-bottom: 1px solid var(--color-hairline);+ }+ .wl-step-body {+ padding: var(--space-5);+ }+ .wl-step-num {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 1.9rem;+ height: 1.9rem;+ border-radius: var(--radius-pill);+ border: 1px solid var(--color-border-strong);+ font-family: var(--font-mono);+ font-size: var(--text-sm);+ color: var(--color-text-bright);+ margin-bottom: var(--space-3);+ }+ .wl-step-title {+ font-size: var(--text-lg);+ font-weight: var(--weight-semibold);+ color: var(--color-text-bright);+ margin: 0 0 var(--space-2);+ }+ .wl-step-desc {+ font-size: var(--text-md);+ line-height: var(--leading-normal);+ color: var(--color-text-dim);+ margin: 0;+ }++ /* ── Extension card ─────────────────────────────────────────── */+ .wl-ext {+ display: grid;+ grid-template-columns: 1.05fr 0.95fr;+ gap: var(--space-xl);+ align-items: center;+ border: 1px solid var(--color-border);+ border-radius: var(--radius-lg);+ background:+ radial-gradient(90% 140% at 100% 0%, var(--surface-2), transparent 60%),+ var(--surface-1);+ padding: var(--space-xl);+ }+ .wl-ext-icon {+ width: 3.5rem;+ height: 3.5rem;+ border-radius: var(--radius-md);+ border: 1px solid var(--color-border-strong);+ background: var(--surface-2);+ display: grid;+ place-items: center;+ margin-bottom: var(--space-4);+ }+ .wl-ext-icon img {+ width: 2rem;+ height: 2rem;+ }+ .wl-ext-title {+ font-family: var(--font-display);+ font-weight: var(--weight-bold);+ font-size: var(--text-xl);+ color: var(--color-text-bright);+ margin: 0 0 var(--space-3);+ letter-spacing: -0.01em;+ }+ .wl-ext-list {+ list-style: none;+ margin: 0 0 var(--space-6);+ padding: 0;+ display: grid;+ gap: var(--space-3);+ }+ .wl-ext-list li {+ display: flex;+ align-items: flex-start;+ gap: var(--space-3);+ font-size: var(--text-md);+ color: var(--color-text-dim);+ line-height: var(--leading-normal);+ }+ .wl-ext-list svg {+ flex: none;+ width: 1.15rem;+ height: 1.15rem;+ margin-top: 0.15rem;+ color: var(--color-success);+ }+ /* Browser-window mock showing the avatar walking on a real page */+ .wl-ext-mock {+ border: 1px solid var(--color-border);+ border-radius: var(--radius-lg);+ overflow: hidden;+ background: var(--color-bg);+ box-shadow: var(--shadow-2);+ }+ .wl-ext-mock-bar {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ padding: var(--space-2) var(--space-3);+ border-bottom: 1px solid var(--color-hairline);+ background: var(--surface-1);+ }+ .wl-ext-mock-url {+ margin-left: var(--space-2);+ flex: 1;+ padding: var(--space-1) var(--space-3);+ border-radius: var(--radius-pill);+ background: var(--surface-2);+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ color: var(--color-text-faint);+ }+ .wl-ext-mock-stage {+ position: relative;+ aspect-ratio: 16 / 10;+ }+ .wl-ext-mock-page {+ position: absolute;+ inset: 0;+ padding: var(--space-5);+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ }+ .wl-ext-mock-line {+ height: 0.55rem;+ border-radius: var(--radius-sm);+ background: var(--surface-2);+ }+ .wl-ext-mock-line.is-head { height: 0.95rem; width: 55%; background: var(--surface-3); }+ .wl-ext-mock-line.is-short { width: 70%; }+ .wl-ext-mock-line.is-mid { width: 88%; }+ .wl-ext-mock-frame {+ position: absolute;+ right: var(--space-4);+ bottom: 0;+ width: 42%;+ height: 78%;+ }+ .wl-ext-mock-frame iframe {+ display: block;+ width: 100%;+ height: 100%;+ border: 0;+ background: transparent;+ }++ /* ── Developer embed ────────────────────────────────────────── */+ .wl-dev {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: var(--space-5);+ align-items: stretch;+ }+ .wl-code {+ display: flex;+ flex-direction: column;+ border: 1px solid var(--color-border);+ border-radius: var(--radius-lg);+ overflow: hidden;+ background: var(--color-bg);+ }+ .wl-code-bar {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ padding: var(--space-2) var(--space-3);+ border-bottom: 1px solid var(--color-hairline);+ background: var(--surface-1);+ }+ .wl-code-label {+ flex: 1;+ margin-left: var(--space-2);+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ color: var(--color-text-faint);+ }+ .wl-copy-btn {+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ color: var(--color-text-dim);+ background: var(--surface-2);+ border: 1px solid var(--color-border);+ border-radius: var(--radius-sm);+ padding: var(--space-1) var(--space-3);+ cursor: pointer;+ transition: background var(--dur-fast) var(--ease-standard),+ color var(--dur-fast) var(--ease-standard);+ }+ .wl-copy-btn:hover { background: var(--surface-3); color: var(--color-text-bright); }+ .wl-copy-btn.is-copied { color: var(--color-success); border-color: var(--color-success); }+ .wl-code pre {+ margin: 0;+ padding: var(--space-4);+ overflow-x: auto;+ font-family: var(--font-mono);+ font-size: var(--text-md);+ line-height: var(--leading-normal);+ color: var(--color-text);+ flex: 1;+ }+ .wl-tok-tag { color: #7dd3fc; }+ .wl-tok-attr { color: #c4b5fd; }+ .wl-tok-val { color: var(--color-success); }+ .wl-tok-com { color: var(--color-text-faint); font-style: italic; }+ .wl-dev-preview .wl-frame-stage { aspect-ratio: 1 / 1; height: auto; }++ /* ── Leaderboard ────────────────────────────────────────────── */+ .wl-board {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: var(--space-4);+ min-height: 7rem;+ }+ .wl-rank {+ display: flex;+ align-items: center;+ gap: var(--space-4);+ border: 1px solid var(--color-border);+ border-radius: var(--radius-lg);+ background: var(--surface-1);+ padding: var(--space-4) var(--space-5);+ }+ .wl-rank--1 { border-color: var(--color-border-strong); background: var(--surface-2); }+ .wl-rank-medal {+ font-family: var(--font-display);+ font-weight: var(--weight-bold);+ font-size: var(--text-lg);+ color: var(--color-text-bright);+ width: 2rem;+ flex: none;+ text-align: center;+ }+ .wl-rank-av {+ width: 2.75rem;+ height: 2.75rem;+ border-radius: var(--radius-pill);+ object-fit: cover;+ background: var(--surface-3);+ border: 1px solid var(--color-border);+ flex: none;+ }+ .wl-rank-meta { min-width: 0; }+ .wl-rank-name {+ font-weight: var(--weight-semibold);+ color: var(--color-text-bright);+ font-size: var(--text-ui);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }+ .wl-rank-dist {+ font-family: var(--font-mono);+ font-size: var(--text-sm);+ color: var(--color-text-dim);+ }+ .wl-skeleton {+ border: 1px solid var(--color-border);+ border-radius: var(--radius-lg);+ background: linear-gradient(100deg, var(--surface-1) 30%, var(--surface-2) 50%, var(--surface-1) 70%);+ background-size: 200% 100%;+ animation: wl-shimmer 1.4s linear infinite;+ height: 5.4rem;+ }+ @keyframes wl-shimmer { to { background-position: -200% 0; } }+ .wl-state {+ grid-column: 1 / -1;+ text-align: center;+ padding: var(--space-xl);+ border: 1px dashed var(--color-border-strong);+ border-radius: var(--radius-lg);+ color: var(--color-text-dim);+ }+ .wl-state strong { display: block; color: var(--color-text-bright); margin-bottom: var(--space-2); font-size: var(--text-base); }+ .wl-state .btn { margin-top: var(--space-4); }++ /* ── Social proof ───────────────────────────────────────────── */+ .wl-social {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: var(--space-4);+ min-height: 6rem;+ }+ .wl-quote {+ display: flex;+ flex-direction: column;+ gap: var(--space-4);+ border: 1px solid var(--color-border);+ border-radius: var(--radius-lg);+ background: var(--surface-1);+ padding: var(--space-5);+ text-decoration: none;+ transition: border-color var(--dur-fast) var(--ease-standard),+ transform var(--dur-fast) var(--ease-standard);+ }+ .wl-quote:hover { border-color: var(--color-border-strong); transform: translateY(-2px); }+ .wl-quote-text {+ font-size: var(--text-md);+ line-height: var(--leading-normal);+ color: var(--color-text);+ margin: 0;+ flex: 1;+ }+ .wl-quote-author {+ display: flex;+ align-items: center;+ gap: var(--space-3);+ }+ .wl-quote-av {+ width: 2.25rem;+ height: 2.25rem;+ border-radius: var(--radius-pill);+ object-fit: contain;+ background: var(--surface-2);+ border: 1px solid var(--color-border);+ padding: var(--space-1);+ }+ .wl-quote-name { font-weight: var(--weight-semibold); color: var(--color-text-bright); font-size: var(--text-sm); }+ .wl-quote-handle { font-size: var(--text-xs); color: var(--color-text-faint); }++ /* ── Footer CTA ─────────────────────────────────────────────── */+ .wl-final {+ text-align: center;+ padding: var(--space-2xl) var(--space-md);+ border-top: 1px solid var(--color-hairline);+ }+ .wl-final h2 {+ font-family: var(--font-display);+ font-weight: var(--weight-bold);+ font-size: var(--text-2xl);+ letter-spacing: -0.02em;+ color: var(--color-text-bright);+ margin: 0 0 var(--space-3);+ }+ .wl-final p { color: var(--color-text-dim); font-size: var(--text-base); margin: 0 0 var(--space-6); }+ .wl-final .wl-cta-row { justify-content: center; }++ /* ── Reveal ─────────────────────────────────────────────────── */+ .wl-reveal { opacity: 0; transform: translateY(16px); transition: opacity var(--duration-slow) var(--ease-emphasized), transform var(--duration-slow) var(--ease-emphasized); }+ .wl-reveal.is-in { opacity: 1; transform: none; }++ .btn-arrow { transition: transform var(--dur-fast) var(--ease-standard); }+ .btn:hover .btn-arrow { transform: translateX(2px); }++ /* ── Responsive ─────────────────────────────────────────────── */+ @media (max-width: 980px) {+ .wl-hero, .wl-ext, .wl-dev { grid-template-columns: 1fr; }+ .wl-frame--hero { aspect-ratio: 16 / 11; }+ .wl-demos, .wl-steps, .wl-board, .wl-social { grid-template-columns: 1fr; }+ .wl-demos { grid-template-columns: repeat(2, 1fr); }+ }+ @media (max-width: 560px) {+ .wl-demos { grid-template-columns: 1fr; }+ .wl-section { padding: var(--space-xl) 0; }+ .wl-hero { padding: var(--space-xl) 0; }+ }+ @media (prefers-reduced-motion: reduce) {+ .wl-reveal { opacity: 1; transform: none; transition: none; }+ .wl-skeleton { animation: none; }+ .wl-step:hover, .wl-quote:hover { transform: none; }+ }+ </style>+ </head>+ <body class="walk-landing-page">+ <a href="#main-content" class="skip-link">Skip to main content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main id="main-content" class="wl-main">+ <!-- ── 1. HERO ── -->+ <section class="wl-hero" aria-labelledby="wl-hero-title">+ <div class="wl-reveal">+ <p class="wl-eyebrow">three.ws Walk</p>+ <h1 class="wl-hero-title" id="wl-hero-title">Your avatar walks anywhere on the web.</h1>+ <p class="wl-hero-sub">+ Drive a fully-rigged 3D avatar with WASD or a touch joystick. Drop it on any+ site with a single tag, or install the extension and let it stroll across real+ pages — reading them aloud as it goes. No app install. It just runs in the browser.+ </p>+ <div class="wl-cta-row">+ <a class="btn btn--primary btn--lg" href="/walk/app">+ Try it now <span class="btn-arrow" aria-hidden="true">→</span>+ </a>+ <a class="btn btn--ghost btn--lg" href="/extension">+ Get the extension <span class="btn-arrow" aria-hidden="true">→</span>+ </a>+ </div>+ <div class="wl-hero-meta">+ <span>+ <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M5 13l4 4L19 7" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>+ Runs in any WebGL browser+ </span>+ <span>+ <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M5 13l4 4L19 7" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>+ Works on desktop & mobile+ </span>+ <span>+ <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M5 13l4 4L19 7" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>+ Embed with one tag+ </span>+ </div>+ </div>++ <div class="wl-reveal wl-frame wl-frame--hero">+ <div class="wl-frame-chrome" aria-hidden="true">+ <span class="wl-frame-dot"></span>+ <span class="wl-frame-dot"></span>+ <span class="wl-frame-dot"></span>+ <span class="wl-frame-label">three.ws/walk-embed</span>+ </div>+ <div class="wl-frame-stage">+ <iframe+ src="/walk-embed?env=void&autoplay=true&controls=none&orbit=false"+ title="Live demo — a 3D avatar walking in the void environment"+ allow="accelerometer; gyroscope"+ ></iframe>+ <span class="wl-frame-hint">Live · walking now</span>+ </div>+ </div>+ </section>++ <!-- ── 2. DEMO STRIP ── -->+ <section class="wl-section" aria-labelledby="wl-demos-title">+ <div class="wl-section-head wl-reveal">+ <h2 class="wl-section-title" id="wl-demos-title">Choose your world.</h2>+ <p class="wl-section-sub">Six built-in environments, no HDRIs to download. Grab the joystick or use WASD — these are live, not videos.</p>+ </div>+ <div class="wl-demos">+ <article class="wl-demo wl-reveal">+ <div class="wl-frame">+ <div class="wl-frame-stage">+ <iframe+ src="/walk-embed?env=beach&controls=joystick&autoplay=true"+ title="Interactive demo — walk the avatar on a sunlit beach"+ loading="lazy"+ allow="accelerometer; gyroscope"+ ></iframe>+ </div>+ </div>+ <div class="wl-demo-caption">+ <span class="wl-demo-name">Beach</span>+ <span class="wl-demo-desc">Sun, sand, soft fog</span>+ </div>+ </article>+ <article class="wl-demo wl-reveal">+ <div class="wl-frame">+ <div class="wl-frame-stage">+ <iframe+ src="/walk-embed?env=night&controls=joystick&autoplay=true"+ title="Interactive demo — walk the avatar through a night scene"+ loading="lazy"+ allow="accelerometer; gyroscope"+ ></iframe>+ </div>+ </div>+ <div class="wl-demo-caption">+ <span class="wl-demo-name">Night</span>+ <span class="wl-demo-desc">Moonlit, deep blue</span>+ </div>+ </article>+ <article class="wl-demo wl-reveal">+ <div class="wl-frame">+ <div class="wl-frame-stage">+ <iframe+ src="/walk-embed?env=grid&controls=joystick&autoplay=true"+ title="Interactive demo — walk the avatar on a holographic grid"+ loading="lazy"+ allow="accelerometer; gyroscope"+ ></iframe>+ </div>+ </div>+ <div class="wl-demo-caption">+ <span class="wl-demo-name">Grid</span>+ <span class="wl-demo-desc">Clean studio grid</span>+ </div>+ </article>+ </div>+ </section>++ <!-- ── 3. HOW IT WORKS ── -->+ <section class="wl-section" aria-labelledby="wl-steps-title">+ <div class="wl-section-head wl-reveal">+ <h2 class="wl-section-title" id="wl-steps-title">How it works</h2>+ <p class="wl-section-sub">From a blank page to a walking avatar in three steps.</p>+ </div>+ <ol class="wl-steps" style="list-style:none;padding:0;margin:0">+ <li class="wl-step wl-reveal">+ <div class="wl-frame-stage">+ <iframe+ src="/walk-embed?env=studio&autoplay=true&controls=none&orbit=false"+ title="Step preview — a generated avatar idling in the studio"+ loading="lazy"+ ></iframe>+ </div>+ <div class="wl-step-body">+ <span class="wl-step-num">1</span>+ <h3 class="wl-step-title">Create your avatar</h3>+ <p class="wl-step-desc">Generate one from a selfie or a text prompt in Forge — or use any humanoid GLB. It comes back fully rigged and animation-ready.</p>+ </div>+ </li>+ <li class="wl-step wl-reveal">+ <div class="wl-frame-stage">+ <iframe+ src="/walk-embed?env=sunset&autoplay=true&controls=none&orbit=false"+ title="Step preview — an avatar walking at sunset"+ loading="lazy"+ ></iframe>+ </div>+ <div class="wl-step-body">+ <span class="wl-step-num">2</span>+ <h3 class="wl-step-title">Walk on three.ws</h3>+ <p class="wl-step-desc">Open the Walk app and drive your avatar with WASD or a touch joystick. Drag to orbit the camera, sprint to run — real locomotion, not a turntable.</p>+ </div>+ </li>+ <li class="wl-step wl-reveal">+ <div class="wl-frame-stage">+ <iframe+ src="/walk-embed?env=void&autoplay=true&controls=none&orbit=false"+ title="Step preview — an avatar walking, ready to embed"+ loading="lazy"+ ></iframe>+ </div>+ <div class="wl-step-body">+ <span class="wl-step-num">3</span>+ <h3 class="wl-step-title">Embed it anywhere</h3>+ <p class="wl-step-desc">Copy one iframe tag onto any site, or install the Chrome extension so your avatar follows you across the entire web.</p>+ </div>+ </li>+ </ol>+ </section>++ <!-- ── 4. CHROME EXTENSION ── -->+ <section class="wl-section" aria-labelledby="wl-ext-title">+ <div class="wl-ext wl-reveal">+ <div>+ <div class="wl-ext-icon" aria-hidden="true">+ <img src="/three.svg" alt="" />+ </div>+ <h2 class="wl-ext-title" id="wl-ext-title">Walk the entire web.</h2>+ <ul class="wl-ext-list">+ <li>+ <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M5 13l4 4L19 7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>+ Your avatar walks over any page you visit — articles, docs, social feeds.+ </li>+ <li>+ <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M5 13l4 4L19 7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>+ It reads pages aloud as it strolls — a living browsing companion.+ </li>+ <li>+ <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M5 13l4 4L19 7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>+ Pick any of your three.ws avatars from the popup. Switch in one click.+ </li>+ <li>+ <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M5 13l4 4L19 7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>+ Minimal permissions, no tracking. Privacy details on the extension page.+ </li>+ </ul>+ <div class="wl-cta-row">+ <a class="btn btn--primary btn--lg" href="/extension">+ Add to Chrome <span class="btn-arrow" aria-hidden="true">→</span>+ </a>+ <a class="btn btn--ghost" href="/extension/privacy">Privacy & permissions</a>+ </div>+ </div>++ <div class="wl-ext-mock" role="img" aria-label="A three.ws avatar walking on top of a real web page, driven by the Chrome extension">+ <div class="wl-ext-mock-bar" aria-hidden="true">+ <span class="wl-frame-dot"></span>+ <span class="wl-frame-dot"></span>+ <span class="wl-frame-dot"></span>+ <span class="wl-ext-mock-url">a page on the web</span>+ </div>+ <div class="wl-ext-mock-stage">+ <div class="wl-ext-mock-page" aria-hidden="true">+ <span class="wl-ext-mock-line is-head"></span>+ <span class="wl-ext-mock-line is-mid"></span>+ <span class="wl-ext-mock-line"></span>+ <span class="wl-ext-mock-line is-short"></span>+ <span class="wl-ext-mock-line is-mid"></span>+ <span class="wl-ext-mock-line is-short"></span>+ </div>+ <div class="wl-ext-mock-frame">+ <iframe+ src="/walk-embed?autoplay=true&controls=none&orbit=false&ground=false"+ title="A walking avatar overlaid on a web page"+ loading="lazy"+ ></iframe>+ </div>+ </div>+ </div>+ </div>+ </section>++ <!-- ── 5. EMBED FOR DEVELOPERS ── -->+ <section class="wl-section" aria-labelledby="wl-dev-title">+ <div class="wl-section-head wl-reveal">+ <h2 class="wl-section-title" id="wl-dev-title">One tag. Any site.</h2>+ <p class="wl-section-sub">No SDK, no build step. Paste the iframe, set the avatar and world with query params, and you have a live walking avatar.</p>+ </div>+ <div class="wl-dev">+ <div class="wl-code wl-reveal">+ <div class="wl-code-bar">+ <span class="wl-frame-dot"></span>+ <span class="wl-frame-dot"></span>+ <span class="wl-frame-dot"></span>+ <span class="wl-code-label">your-site.html</span>+ <button class="wl-copy-btn" id="wl-copy" type="button" aria-label="Copy embed snippet to clipboard">Copy</button>+ </div>+<pre id="wl-snippet"><code><span class="wl-tok-com"><!-- three.ws Walk — drop in anywhere --></span>+<span class="wl-tok-tag"><iframe</span>+ <span class="wl-tok-attr">src</span>=<span class="wl-tok-val">"https://three.ws/walk-embed?env=void&autoplay=true"</span>+ <span class="wl-tok-attr">width</span>=<span class="wl-tok-val">"360"</span> <span class="wl-tok-attr">height</span>=<span class="wl-tok-val">"480"</span>+ <span class="wl-tok-attr">style</span>=<span class="wl-tok-val">"border:0;background:transparent"</span>+ <span class="wl-tok-attr">title</span>=<span class="wl-tok-val">"three.ws walking avatar"</span><span class="wl-tok-tag">></iframe></span></code></pre>+ </div>+ <div class="wl-dev-preview wl-reveal">+ <div class="wl-frame">+ <div class="wl-frame-chrome" aria-hidden="true">+ <span class="wl-frame-dot"></span>+ <span class="wl-frame-dot"></span>+ <span class="wl-frame-dot"></span>+ <span class="wl-frame-label">live preview</span>+ </div>+ <div class="wl-frame-stage">+ <iframe+ src="/walk-embed?env=void&autoplay=true&controls=joystick"+ title="Live preview of the embed snippet — an interactive walking avatar"+ loading="lazy"+ allow="accelerometer; gyroscope"+ ></iframe>+ </div>+ </div>+ </div>+ </div>+ </section>++ <!-- ── 6. LEADERBOARD TEASER ── -->+ <section class="wl-section" aria-labelledby="wl-board-title">+ <div class="wl-section-head wl-reveal">+ <h2 class="wl-section-title" id="wl-board-title">Top walkers</h2>+ <p class="wl-section-sub">The longest strolls on three.ws, all-time. Lace up and climb the board.</p>+ </div>+ <div class="wl-board wl-reveal" id="wl-board" aria-live="polite" aria-busy="true">+ <div class="wl-skeleton"></div>+ <div class="wl-skeleton"></div>+ <div class="wl-skeleton"></div>+ </div>+ <div style="text-align:center;margin-top:var(--space-6)" class="wl-reveal">+ <a class="btn btn--ghost" href="/walk-leaderboard">See the full leaderboard <span class="btn-arrow" aria-hidden="true">→</span></a>+ </div>+ </section>++ <!-- ── 7. SOCIAL PROOF ── -->+ <section class="wl-section" aria-labelledby="wl-social-title">+ <div class="wl-section-head wl-reveal">+ <h2 class="wl-section-title" id="wl-social-title">From the team</h2>+ <p class="wl-section-sub">What three.ws is shipping with Walk.</p>+ </div>+ <div class="wl-social wl-reveal" id="wl-social" aria-live="polite"></div>+ </section>++ <!-- ── 8. FOOTER CTA ── -->+ <section class="wl-final wl-reveal" aria-labelledby="wl-final-title">+ <h2 id="wl-final-title">Start walking now.</h2>+ <p>Free to try — bring any avatar and a browser.</p>+ <div class="wl-cta-row">+ <a class="btn btn--primary btn--lg" href="/walk/app">+ Start walking <span class="btn-arrow" aria-hidden="true">→</span>+ </a>+ <a class="btn btn--ghost btn--lg" href="/extension">Get the extension</a>+ </div>+ </section>+ </main>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script src="/brand.js" defer></script>++ <script type="module">+ // ── Copy button ──────────────────────────────────────────────+ // Copies the literal embed snippet (not the syntax-highlighted DOM).+ const copyBtn = document.getElementById('wl-copy');+ if (copyBtn) {+ const SNIPPET =+ '<!-- three.ws Walk — drop in anywhere -->\n' ++ '<iframe\n' ++ ' src="https://three.ws/walk-embed?env=void&autoplay=true"\n' ++ ' width="360" height="480"\n' ++ ' style="border:0;background:transparent"\n' ++ ' title="three.ws walking avatar"></iframe>';+ copyBtn.addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(SNIPPET);+ } catch {+ // Clipboard API unavailable (insecure context / denied) —+ // fall back to a selection-based copy so the button still works.+ const ta = document.createElement('textarea');+ ta.value = SNIPPET;+ ta.style.position = 'fixed';+ ta.style.opacity = '0';+ document.body.appendChild(ta);+ ta.select();+ try { document.execCommand('copy'); } catch {}+ ta.remove();+ }+ copyBtn.textContent = 'Copied';+ copyBtn.classList.add('is-copied');+ copyBtn.addEventListener('animationend', () => {}, { once: true });+ window.clearTimeout(copyBtn._t);+ copyBtn._t = window.setTimeout(() => {+ copyBtn.textContent = 'Copy';+ copyBtn.classList.remove('is-copied');+ }, 1800);+ });+ }++ // ── Scroll reveal ────────────────────────────────────────────+ const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;+ const reveals = document.querySelectorAll('.wl-reveal');+ if (reduceMotion || !('IntersectionObserver' in window)) {+ reveals.forEach((el) => el.classList.add('is-in'));+ } else {+ const io = new IntersectionObserver(+ (entries) => {+ for (const e of entries) {+ if (e.isIntersecting) {+ e.target.classList.add('is-in');+ io.unobserve(e.target);+ }+ }+ },+ { threshold: 0.12, rootMargin: '0px 0px -60px 0px' },+ );+ reveals.forEach((el) => io.observe(el));+ }++ // ── Leaderboard (real fetch, graceful states) ────────────────+ const board = document.getElementById('wl-board');+ const MEDALS = ['1', '2', '3'];++ function escapeHtml(s) {+ return String(s).replace(/[&<>"']/g, (c) => ({+ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''',+ })[c]);+ }++ function formatDistance(meters) {+ const m = Number(meters);+ if (!Number.isFinite(m) || m <= 0) return '—';+ if (m >= 1000) return (m / 1000).toFixed(m >= 10000 ? 0 : 1) + ' km';+ return Math.round(m) + ' m';+ }++ function renderBoard(rows) {+ board.setAttribute('aria-busy', 'false');+ if (!rows.length) {+ board.innerHTML =+ '<div class="wl-state"><strong>No walks logged yet.</strong>' ++ 'Be the first to put down some distance.' ++ '<div><a class="btn btn--primary" href="/walk/app">Start walking →</a></div></div>';+ return;+ }+ board.innerHTML = rows.slice(0, 3).map((r, i) => {+ const name = escapeHtml(r.name || r.handle || r.wallet_short || ('Walker #' + (i + 1)));+ const dist = escapeHtml(formatDistance(r.distance ?? r.value ?? r.meters));+ const img = r.image_url || r.avatar || r.image;+ const av = img+ ? '<img class="wl-rank-av" src="' + escapeHtml(img) + '" alt="" loading="lazy" />'+ : '<span class="wl-rank-av" aria-hidden="true"></span>';+ const href = r.url || r.profile_url || r.walk_url;+ const inner =+ '<span class="wl-rank-medal" aria-hidden="true">' + MEDALS[i] + '</span>' ++ av ++ '<span class="wl-rank-meta"><span class="wl-rank-name">' + name + '</span>' ++ '<span class="wl-rank-dist">' + dist + ' walked</span></span>';+ return href+ ? '<a class="wl-rank wl-rank--' + (i + 1) + '" href="' + escapeHtml(href) + '">' + inner + '</a>'+ : '<div class="wl-rank wl-rank--' + (i + 1) + '">' + inner + '</div>';+ }).join('');+ }++ function renderBoardError() {+ board.setAttribute('aria-busy', 'false');+ board.innerHTML =+ '<div class="wl-state"><strong>The leaderboard is taking a breather.</strong>' ++ 'We could not load the top walkers just now.' ++ '<div><button class="btn btn--ghost" type="button" id="wl-board-retry">Try again</button></div></div>';+ const retry = document.getElementById('wl-board-retry');+ if (retry) retry.addEventListener('click', loadBoard);+ }++ async function loadBoard() {+ board.setAttribute('aria-busy', 'true');+ board.innerHTML = '<div class="wl-skeleton"></div><div class="wl-skeleton"></div><div class="wl-skeleton"></div>';+ try {+ const res = await fetch('/api/walk/leaderboard?period=all-time&metric=distance', {+ headers: { accept: 'application/json' },+ });+ if (!res.ok) throw new Error('HTTP ' + res.status);+ const data = await res.json();+ // Accept a few reasonable shapes the parallel endpoint may ship:+ // { leaders: [...] } | { walkers: [...] } | { entries: [...] } | [...]+ const rows = Array.isArray(data)+ ? data+ : data.leaders || data.walkers || data.entries || data.results || data.data || [];+ renderBoard(Array.isArray(rows) ? rows : []);+ } catch {+ renderBoardError();+ }+ }+ loadBoard();++ // ── Social proof (curated, platform-owned only) ──────────────+ const social = document.getElementById('wl-social');+ function renderSocialEmpty() {+ social.innerHTML =+ '<div class="wl-state"><strong>Nothing here yet.</strong>' ++ 'Share your walk and tag <a href="https://x.com/trythreews" rel="noopener" style="color:var(--color-text-bright)">@trythreews</a>.</div>';+ }+ // The curated entries live in data/walk-social.json (source). The build+ // copies it to a root-served path; try the public root first, then the+ // raw data/ path, so the section populates regardless of how it's wired.+ async function fetchSocial() {+ for (const url of ['/walk-social.json', '/data/walk-social.json']) {+ try {+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (res.ok) return res.json();+ } catch { /* try next */ }+ }+ throw new Error('walk-social.json unavailable');+ }+ async function loadSocial() {+ try {+ const items = await fetchSocial();+ if (!Array.isArray(items) || !items.length) { renderSocialEmpty(); return; }+ social.innerHTML = items.slice(0, 6).map((it) => {+ const quote = escapeHtml(it.quote || '');+ const author = escapeHtml(it.author || '');+ const handle = escapeHtml(it.handle || '');+ const url = it.url ? escapeHtml(it.url) : null;+ const av = it.avatar+ ? '<img class="wl-quote-av" src="' + escapeHtml(it.avatar) + '" alt="" loading="lazy" />'+ : '<span class="wl-quote-av" aria-hidden="true"></span>';+ const body =+ '<p class="wl-quote-text">' + quote + '</p>' ++ '<span class="wl-quote-author">' + av ++ '<span><span class="wl-quote-name">' + author + '</span><br />' ++ '<span class="wl-quote-handle">' + handle + '</span></span></span>';+ return url+ ? '<a class="wl-quote" href="' + url + '" target="_blank" rel="noopener noreferrer">' + body + '</a>'+ : '<div class="wl-quote">' + body + '</div>';+ }).join('');+ } catch {+ renderSocialEmpty();+ }+ }+ loadSocial();+ </script>+ </body>+</html>diff --git a/pages/walk-leaderboard.html b/pages/walk-leaderboard.htmlnew file mode 100644index 000000000..7241048d5--- /dev/null+++ b/pages/walk-leaderboard.html@@ -0,0 +1,336 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash */(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, viewport-fit=cover" />+ <title>Walk Leaderboard · three.ws</title>+ <meta name="description" content="The three.ws walk leaderboard — walkers ranked by distance walked, sites visited, and time spent walking, daily, this week, and all-time. Lace up and climb." />+ <link rel="canonical" href="https://three.ws/walk-leaderboard" />+ <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" />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/walk-leaderboard" />+ <meta property="og:title" content="Walk Leaderboard · three.ws" />+ <meta property="og:description" content="Walkers ranked by distance walked, sites visited, and time spent walking — daily, weekly, all-time." />+ <meta property="og:image" content="https://three.ws/og-image.png" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Walk Leaderboard · three.ws" />+ <meta name="twitter:description" content="Walkers ranked by distance, sites, and time — daily, weekly, all-time." />+ <meta name="twitter:image" content="https://three.ws/og-image.png" />+ <meta name="theme-color" content="#0a0a0a" />+ <style>+ .wlb-shell { max-width: 980px; margin: 0 auto; padding: var(--space-lg) var(--space-md) var(--space-2xl); }++ .wlb-hero { padding: var(--space-xl) 0 var(--space-md); }+ .wlb-kicker {+ display: inline-flex; align-items: center; gap: var(--space-xs);+ font: var(--weight-semibold) var(--text-2xs)/1.2 var(--font-mono);+ letter-spacing: 0.06em; text-transform: uppercase; color: var(--color-text-dim);+ margin: 0 0 var(--space-sm);+ }+ .wlb-live-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--color-success); box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-success) 60%, transparent); animation: wlb-pulse 1.8s ease infinite; }+ @keyframes wlb-pulse { 0%,100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-success) 55%, transparent); } 70% { box-shadow: 0 0 0 6px transparent; } }+ .wlb-title { font: var(--weight-bold) var(--text-2xl)/1.05 var(--font-display); color: var(--color-text-bright); margin: 0 0 var(--space-sm); letter-spacing: -0.02em; }+ .wlb-sub { font: var(--weight-regular) var(--text-base)/var(--leading-normal) var(--font-body); color: var(--color-text-dim); margin: 0; max-width: 60ch; }++ .wlb-controls { display: flex; flex-wrap: wrap; gap: var(--space-sm); align-items: center; justify-content: space-between; margin: var(--space-lg) 0 var(--space-md); }+ .wlb-seg { display: inline-flex; gap: var(--space-3xs); padding: var(--space-3xs); background: var(--surface-1); border: 1px solid var(--color-border); border-radius: var(--radius-pill); }+ .wlb-seg-btn {+ appearance: none; border: 0; background: transparent; cursor: pointer;+ padding: var(--space-xs) var(--space-md); border-radius: var(--radius-pill);+ font: var(--weight-medium) var(--text-md)/1 var(--font-body); color: var(--color-text-dim);+ transition: color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard);+ }+ .wlb-seg-btn:hover { color: var(--color-text); }+ .wlb-seg-btn.is-active { background: var(--surface-3); color: var(--color-text-bright); }+ .wlb-seg-btn:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: var(--focus-ring-offset); }++ .wlb-board { border: 1px solid var(--color-border); border-radius: var(--radius-lg); background: var(--surface-1); overflow: hidden; }+ .wlb-head, .wlb-row {+ display: grid;+ grid-template-columns: 56px 1fr 120px 110px;+ align-items: center; gap: var(--space-sm);+ padding: var(--space-sm) var(--space-md);+ }+ .wlb-head { background: var(--surface-2); border-bottom: 1px solid var(--color-border); font: var(--weight-semibold) var(--text-2xs)/1 var(--font-mono); text-transform: uppercase; letter-spacing: 0.06em; color: var(--color-text-faint); }+ .wlb-col-num { text-align: right; }+ .wlb-row { border-bottom: 1px solid var(--color-border); transition: background var(--duration-fast) var(--ease-standard); }+ .wlb-row:last-child { border-bottom: 0; }+ .wlb-row:hover { background: var(--surface-2); }+ .wlb-rank { font: var(--weight-bold) var(--text-md)/1 var(--font-mono); color: var(--color-text-dim); }+ .wlb-rank.is-top { color: var(--color-text-bright); }+ .wlb-medal { font-size: 16px; }+ .wlb-walker { display: flex; align-items: center; gap: var(--space-sm); min-width: 0; }+ .wlb-avatar { width: 34px; height: 34px; border-radius: 50%; object-fit: cover; background: var(--surface-3); flex: none; border: 1px solid var(--color-border); }+ .wlb-avatar-fallback { display: flex; align-items: center; justify-content: center; font: var(--weight-semibold) var(--text-sm)/1 var(--font-body); color: var(--color-text-dim); }+ .wlb-handle { font: var(--weight-medium) var(--text-md)/1.2 var(--font-body); color: var(--color-text); text-decoration: none; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ a.wlb-handle:hover { color: var(--color-text-bright); text-decoration: underline; }+ .wlb-value { font: var(--weight-semibold) var(--text-md)/1 var(--font-mono); color: var(--color-text-bright); text-align: right; }+ .wlb-delta { text-align: right; font: var(--weight-medium) var(--text-sm)/1 var(--font-mono); }+ .wlb-delta.up { color: var(--color-success); }+ .wlb-delta.down { color: var(--color-danger); }+ .wlb-delta.flat { color: var(--color-text-faint); }++ .wlb-me { position: sticky; bottom: 0; z-index: 5; margin-top: var(--space-md); border: 1px solid color-mix(in srgb, var(--accent) 28%, var(--color-border)); border-radius: var(--radius-lg); background: var(--surface-3); backdrop-filter: blur(var(--blur-md)); -webkit-backdrop-filter: blur(var(--blur-md)); box-shadow: var(--shadow-2); }+ .wlb-me .wlb-row { border-bottom: 0; }+ .wlb-me-tag { font: var(--weight-semibold) var(--text-2xs)/1 var(--font-mono); text-transform: uppercase; letter-spacing: 0.06em; color: var(--color-text-faint); padding: var(--space-xs) var(--space-md) 0; }++ .wlb-loadmore { display: block; margin: var(--space-md) auto 0; appearance: none; cursor: pointer; padding: var(--space-sm) var(--space-lg); border-radius: var(--radius-md); border: 1px solid var(--color-border); background: var(--surface-1); color: var(--color-text); font: var(--weight-medium) var(--text-md)/1 var(--font-body); transition: background var(--duration-fast) var(--ease-standard); }+ .wlb-loadmore:hover { background: var(--surface-2); }+ .wlb-loadmore:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: var(--focus-ring-offset); }+ .wlb-loadmore[disabled] { opacity: var(--disabled-opacity); cursor: var(--disabled-cursor); }++ /* States */+ .wlb-state { padding: var(--space-2xl) var(--space-md); text-align: center; }+ .wlb-state-title { font: var(--weight-semibold) var(--text-lg)/1.2 var(--font-display); color: var(--color-text-bright); margin: 0 0 var(--space-xs); }+ .wlb-state-msg { font: var(--weight-regular) var(--text-md)/var(--leading-normal) var(--font-body); color: var(--color-text-dim); margin: 0 auto var(--space-md); max-width: 46ch; }+ .wlb-state .wlb-cta { display: inline-flex; align-items: center; gap: var(--space-xs); padding: var(--space-sm) var(--space-lg); border-radius: var(--radius-md); background: var(--accent); color: #0a0a0a; font: var(--weight-semibold) var(--text-md)/1 var(--font-body); text-decoration: none; transition: opacity var(--duration-fast) var(--ease-standard); }+ .wlb-state .wlb-cta:hover { opacity: 0.85; }++ .wlb-skel-row { display: grid; grid-template-columns: 56px 1fr 120px 110px; gap: var(--space-sm); align-items: center; padding: var(--space-sm) var(--space-md); border-bottom: 1px solid var(--color-border); }+ .wlb-skel { height: 14px; border-radius: var(--radius-sm); background: linear-gradient(90deg, var(--surface-2) 25%, var(--surface-3) 37%, var(--surface-2) 63%); background-size: 400% 100%; animation: wlb-shimmer 1.4s ease infinite; }+ .wlb-skel.circle { width: 34px; height: 34px; border-radius: 50%; }+ @keyframes wlb-shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }+ @media (prefers-reduced-motion: reduce) { .wlb-skel, .wlb-live-dot { animation: none; } }++ @media (max-width: 640px) {+ .wlb-head, .wlb-row, .wlb-skel-row { grid-template-columns: 40px 1fr 84px; }+ .wlb-delta, .wlb-col-delta { display: none; }+ .wlb-title { font-size: var(--text-xl); }+ }+ </style>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="wlb-shell" aria-labelledby="wlb-title">+ <section class="wlb-hero">+ <p class="wlb-kicker"><span class="wlb-live-dot" aria-hidden="true"></span> Gamified · updates live</p>+ <h1 id="wlb-title" class="wlb-title">Walk Leaderboard</h1>+ <p class="wlb-sub">Every step your avatar takes on three.ws counts. Ranked by distance walked, sites visited, and time on your feet — today, this week, and all-time.</p>+ </section>++ <section class="wlb-controls" aria-label="Leaderboard filters">+ <div class="wlb-seg" role="tablist" aria-label="Time window" id="wlb-period">+ <button class="wlb-seg-btn" data-period="daily" role="tab" aria-selected="false">Today</button>+ <button class="wlb-seg-btn is-active" data-period="weekly" role="tab" aria-selected="true">This Week</button>+ <button class="wlb-seg-btn" data-period="all-time" role="tab" aria-selected="false">All Time</button>+ </div>+ <div class="wlb-seg" role="tablist" aria-label="Metric" id="wlb-metric">+ <button class="wlb-seg-btn is-active" data-metric="distance" role="tab" aria-selected="true">Distance</button>+ <button class="wlb-seg-btn" data-metric="sites" role="tab" aria-selected="false">Sites</button>+ <button class="wlb-seg-btn" data-metric="time" role="tab" aria-selected="false">Time</button>+ </div>+ </section>++ <section class="wlb-board" aria-label="Ranked walkers" aria-busy="true">+ <div class="wlb-head" role="row" aria-hidden="true">+ <span>#</span>+ <span>Walker</span>+ <span class="wlb-col-num" id="wlb-metric-label">Distance</span>+ <span class="wlb-col-num wlb-col-delta">vs. yesterday</span>+ </div>+ <div id="wlb-rows" aria-live="polite"></div>+ </section>++ <button type="button" id="wlb-loadmore" class="wlb-loadmore" hidden>Show more</button>++ <div id="wlb-me-wrap" class="wlb-me" hidden>+ <div class="wlb-me-tag">Your rank</div>+ <div id="wlb-me-row"></div>+ </div>+ </main>++ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>++ <script type="module">+ const rowsEl = document.getElementById('wlb-rows');+ const boardEl = rowsEl.closest('.wlb-board');+ const metricLabelEl = document.getElementById('wlb-metric-label');+ const loadMoreEl = document.getElementById('wlb-loadmore');+ const meWrap = document.getElementById('wlb-me-wrap');+ const meRow = document.getElementById('wlb-me-row');+ const periodSeg = document.getElementById('wlb-period');+ const metricSeg = document.getElementById('wlb-metric');++ const METRIC_HEAD = { distance: 'Distance', sites: 'Sites', time: 'Time' };+ const PAGE = 50;+ let state = { period: 'weekly', metric: 'distance', offset: 0, total: 0, loading: false };++ const esc = (s) => String(s).replace(/[<>&"']/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' }[c]));++ // Stable anon id mirrors src/walk.js so an anonymous walker sees their own+ // pinned rank here too.+ function anonId() {+ try {+ let id = localStorage.getItem('twx_walk_anon');+ return id || null;+ } catch { return null; }+ }++ function fmtValue(metric, v) {+ if (metric === 'distance') {+ return v >= 1000 ? (v / 1000).toFixed(2) + ' km' : Math.round(v) + ' m';+ }+ if (metric === 'time') {+ const s = Math.round(v);+ if (s >= 3600) return (s / 3600).toFixed(1) + ' h';+ if (s >= 60) return Math.round(s / 60) + ' min';+ return s + ' s';+ }+ return String(Math.round(v)); // sites+ }++ function fmtDelta(metric, d) {+ if (!d) return '<span class="wlb-delta flat">—</span>';+ const cls = d > 0 ? 'up' : 'down';+ const sign = d > 0 ? '+' : '−';+ const abs = Math.abs(d);+ let body;+ if (metric === 'distance') body = abs >= 1000 ? (abs / 1000).toFixed(1) + ' km' : Math.round(abs) + ' m';+ else if (metric === 'time') body = abs >= 60 ? Math.round(abs / 60) + ' min' : Math.round(abs) + ' s';+ else body = String(Math.round(abs));+ return `<span class="wlb-delta ${cls}">${sign}${body}</span>`;+ }++ function medal(rank) {+ if (rank === 1) return '<span class="wlb-medal" aria-hidden="true">🥇</span>';+ if (rank === 2) return '<span class="wlb-medal" aria-hidden="true">🥈</span>';+ if (rank === 3) return '<span class="wlb-medal" aria-hidden="true">🥉</span>';+ return '';+ }++ function avatarCell(r) {+ if (r.avatar) return `<img class="wlb-avatar" src="${esc(r.avatar)}" alt="" loading="lazy" />`;+ const ch = esc((r.handle || '?').replace(/^@/, '')[0] || '?').toUpperCase();+ return `<span class="wlb-avatar wlb-avatar-fallback" aria-hidden="true">${ch}</span>`;+ }++ function rowHtml(r, metric, isMe) {+ const handle = r.profileUrl+ ? `<a class="wlb-handle" href="${esc(r.profileUrl)}">${esc(r.handle)}</a>`+ : `<span class="wlb-handle">${esc(r.handle)}${isMe ? ' (you)' : ''}</span>`;+ const rankCls = r.rank && r.rank <= 3 ? 'wlb-rank is-top' : 'wlb-rank';+ const rankText = r.rank == null ? '—' : (medal(r.rank) || '#' + r.rank);+ return `+ <div class="wlb-row" role="row">+ <span class="${rankCls}">${rankText}</span>+ <span class="wlb-walker">${avatarCell(r)} ${handle}</span>+ <span class="wlb-value">${fmtValue(metric, r.value)}</span>+ <span class="wlb-col-delta">${fmtDelta(metric, r.deltaFromYesterday)}</span>+ </div>`;+ }++ function skeleton() {+ let h = '';+ for (let i = 0; i < 8; i++) {+ h += `<div class="wlb-skel-row"><span class="wlb-skel" style="width:24px"></span><span style="display:flex;align-items:center;gap:10px"><span class="wlb-skel circle"></span><span class="wlb-skel" style="width:120px"></span></span><span class="wlb-skel" style="width:70px;justify-self:end"></span><span class="wlb-skel wlb-col-delta" style="width:50px;justify-self:end"></span></div>`;+ }+ rowsEl.innerHTML = h;+ }++ function showState(title, msg, cta) {+ rowsEl.innerHTML = `<div class="wlb-state"><p class="wlb-state-title">${esc(title)}</p><p class="wlb-state-msg">${esc(msg)}</p>${cta ? `<a class="wlb-cta" href="${esc(cta.href)}">${esc(cta.label)}</a>` : ''}</div>`;+ }++ function renderMe(me, metric) {+ if (!me) { meWrap.hidden = true; return; }+ meWrap.hidden = false;+ meRow.innerHTML = rowHtml(me, metric, true);+ }++ async function load({ reset = true } = {}) {+ if (state.loading) return;+ state.loading = true;+ if (reset) { state.offset = 0; skeleton(); meWrap.hidden = true; }+ boardEl.setAttribute('aria-busy', 'true');+ loadMoreEl.disabled = true;+ const params = new URLSearchParams({ period: state.period, metric: state.metric, limit: String(PAGE), offset: String(state.offset) });+ const aid = anonId();+ if (aid) params.set('anonId', aid);+ try {+ const res = await fetch('/api/walk/leaderboard?' + params.toString(), { credentials: 'include' });+ if (!res.ok) throw new Error('HTTP ' + res.status);+ const data = await res.json();+ state.total = data.total || 0;+ const metric = data.metric || state.metric;+ metricLabelEl.textContent = METRIC_HEAD[metric] || 'Value';++ if (reset && (!data.rows || !data.rows.length)) {+ showState(+ 'No walkers ranked yet',+ 'Be the first on the board. Take your avatar for a walk and your distance, sites, and time will show up here.',+ { href: '/walk', label: 'Start walking →' },+ );+ renderMe(data.me && data.me.value > 0 ? data.me : null, metric);+ return;+ }++ const html = (data.rows || []).map((r) => rowHtml(r, metric, data.me && r.key === data.me.key)).join('');+ if (reset) rowsEl.innerHTML = html; else rowsEl.insertAdjacentHTML('beforeend', html);++ state.offset += (data.rows || []).length;+ loadMoreEl.hidden = !data.hasMore;+ renderMe(data.me, metric);+ } catch (err) {+ if (reset) {+ const wrap = document.createElement('div');+ wrap.className = 'wlb-state';+ wrap.innerHTML = `<p class="wlb-state-title">Couldn't load the leaderboard</p><p class="wlb-state-msg">${esc(err.message || 'Something went wrong.')}</p>`;+ const btn = document.createElement('button');+ btn.className = 'wlb-cta';+ btn.type = 'button';+ btn.textContent = 'Retry';+ btn.addEventListener('click', () => load({ reset: true }));+ wrap.appendChild(btn);+ rowsEl.replaceChildren(wrap);+ }+ } finally {+ state.loading = false;+ boardEl.setAttribute('aria-busy', 'false');+ loadMoreEl.disabled = false;+ }+ }++ function bindSeg(seg, key, onChange) {+ seg.addEventListener('click', (e) => {+ const btn = e.target.closest('.wlb-seg-btn');+ if (!btn || btn.classList.contains('is-active')) return;+ seg.querySelectorAll('.wlb-seg-btn').forEach((b) => { b.classList.remove('is-active'); b.setAttribute('aria-selected', 'false'); });+ btn.classList.add('is-active');+ btn.setAttribute('aria-selected', 'true');+ state[key] = btn.dataset[key];+ onChange();+ });+ // Keyboard: left/right move between tabs.+ seg.addEventListener('keydown', (e) => {+ if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;+ const btns = [...seg.querySelectorAll('.wlb-seg-btn')];+ const i = btns.findIndex((b) => b.classList.contains('is-active'));+ const next = btns[(i + (e.key === 'ArrowRight' ? 1 : btns.length - 1)) % btns.length];+ next.focus(); next.click();+ e.preventDefault();+ });+ }++ bindSeg(periodSeg, 'period', () => load({ reset: true }));+ bindSeg(metricSeg, 'metric', () => load({ reset: true }));+ loadMoreEl.addEventListener('click', () => load({ reset: false }));++ load({ reset: true });+ </script>+ </body>+</html>diff --git a/public/changelog.json b/public/changelog.jsonindex 6634fa2b4..98944efca 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T06:17:17.544Z",+ "generated_at": "2026-06-21T06:29:17.048Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -47,6 +47,16 @@"feature"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Clearer empty state on the $THREE live-trades feed",+ "summary": "Before the next trade lands, the live-trades panel on the $THREE token page now reads in plain language — 'Live trades will appear here' — with a short note on what it shows, and the technical detail tucked behind an info tooltip. Screen readers announce new trades as they stream in.",+ "link": "/three-token",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-21","type": "update",@@ -58,6 +68,16 @@"infra"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Empty pages now guide you instead of going blank",+ "summary": "Across the dashboard and marketplace, anywhere a list can be empty now explains what belongs there, why it's useful, and the next step — instead of a bare 'No data' line. Your Agents, Avatars, Analytics, Brain, embed policies, the marketplace, and My Agents each greet a fresh account with a short plain-language intro and a clear button to create your first one (plus a 'What's an agent?' link). Filtered searches that return nothing now say so and offer to clear the filter. It's the same designed component everywhere, so the whole platform feels consistent and never abandoned.",+ "link": "/dashboard",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-21","type": "update",@@ -159,6 +179,18 @@"improvement"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Payment hardening and a steadier holder leaderboard",+ "summary": "Two behind-the-scenes reliability and safety fixes. Agent payment invoices now verify that the wallet paying is actually linked to your account before an invoice is created, closing a gap that let bogus payment requests be generated against any agent. And the $THREE holder leaderboard, its share card, and the token stats panel no longer each kick off a full on-chain holder scan during a traffic spike — one scan now serves everyone and refreshes the shared snapshot, so the leaderboard stays fast and responsive under load. Nothing to do on your end.",+ "link": "/leaderboard",+ "tags": [+ "security",+ "fix",+ "infra"+ ]+ },{"date": "2026-06-21","type": "update",@@ -171,6 +203,16 @@"infra"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Profiles you can edit — and follow",+ "summary": "Your three.ws profile at three.ws/u/<your-username> is now a real social home. Edit it in place: add a bio, a profile picture and banner image, your location, and a website link — all from an Edit button on your own profile. You can now follow other creators and agents, and they can follow you; every profile shows live follower and following counts you can tap to browse the lists, with one-tap follow buttons throughout. And there's a new Feed at three.ws/feed that gathers the latest avatars, agents, and coin launches from everyone you follow, newest first. Find your profile and Feed links from your account page.",+ "link": "/feed",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-21","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 0df6f4c28..2977f7609 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -38,6 +38,14 @@<category>feature</category><description>The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set, and you can let it expire or revoke it anytime. Set a cap, top it up, or leave it off and keep signing each payment — your choice.</description></item>+ <item>+ <title>Clearer empty state on the $THREE live-trades feed</title>+ <link>https://three.ws/three-token</link>+ <guid isPermaLink="false">2026-06-21:Clearer empty state on the $THREE live-trades feed</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Before the next trade lands, the live-trades panel on the $THREE token page now reads in plain language — 'Live trades will appear here' — with a short note on what it shows, and the technical detail tucked behind an info tooltip. Screen readers announce new trades as they stream in.</description>+ </item><item><title>Discover and character feeds load faster under heavy traffic</title><link>https://three.ws/discover</link>@@ -46,6 +54,14 @@<category>improvement</category><description>The Discover grid and the published-agents (Characters) feed now serve from the edge cache, so a surge of visitors is absorbed at the CDN instead of re-running a database scan on every request. Pages stay fast and consistent even during a rush, and a stale-while-revalidate window keeps them warm between refreshes.</description></item>+ <item>+ <title>Empty pages now guide you instead of going blank</title>+ <link>https://three.ws/dashboard</link>+ <guid isPermaLink="false">2026-06-21:Empty pages now guide you instead of going blank</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Across the dashboard and marketplace, anywhere a list can be empty now explains what belongs there, why it's useful, and the next step — instead of a bare 'No data' line. Your Agents, Avatars, Analytics, Brain, embed policies, the marketplace, and My Agents each greet a fresh account with a short plain-language intro and a clear button to create your first one (plus a 'What's an agent?' link). Filtered searches that return nothing now say so and offer to clear the filter. It's the same designed component everywhere, so the whole platform feels consistent and never abandoned.</description>+ </item><item><title>Every Forge quality tier now runs on free engines</title><link>https://three.ws/forge</link>@@ -118,6 +134,14 @@<category>infra</category><description>The trending-tokens feed that powers the home card, communities, the token constellation, and the 3D visualizer is now resilient to upstream outages. If a market data provider goes down or rate-limits us, we transparently fall back to a second source; if both are briefly unavailable, the surfaces keep showing the last good data (clearly marked as a moment stale) instead of going blank. We also added a fast-fail circuit breaker so a slow provider can't drag the feed down during a traffic spike. Net effect: the live market views stay populated and snappy even when a data provider hiccups.</description></item>+ <item>+ <title>Payment hardening and a steadier holder leaderboard</title>+ <link>https://three.ws/leaderboard</link>+ <guid isPermaLink="false">2026-06-21:Payment hardening and a steadier holder leaderboard</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>security</category>+ <description>Two behind-the-scenes reliability and safety fixes. Agent payment invoices now verify that the wallet paying is actually linked to your account before an invoice is created, closing a gap that let bogus payment requests be generated against any agent. And the $THREE holder leaderboard, its share card, and the token stats panel no longer each kick off a full on-chain holder scan during a traffic spike — one scan now serves everyone and refreshes the shared snapshot, so the leaderboard stays fast and responsive under load. Nothing to do on your end.</description>+ </item><item><title>Platform-wide hardening: payment integrity, security, and scale</title><link>https://three.ws/changelog</link>@@ -126,6 +150,14 @@<category>security</category><description>A broad reliability pass across the parts of three.ws that move real money and serve heavy traffic. On the money side: bundle purchases and agent payments are now verified on-chain before anything unlocks, each payment is credited exactly once, withdrawals can't be processed twice, and recurring subscriptions can't be double-billed. On the security side: a set of input-handling and link-safety fixes across pages, stronger protection for custodial keys at rest, and tighter checks on outbound agent payments so funds only ever move in the expected asset. On the scale side: the busiest directory, profile, and feed pages now ride a short cache and run far fewer database queries, so they stay fast as the community grows. Most of this is invisible by design — it's the plumbing that keeps the platform correct and quick under load.</description></item>+ <item>+ <title>Profiles you can edit — and follow</title>+ <link>https://three.ws/feed</link>+ <guid isPermaLink="false">2026-06-21:Profiles you can edit — and follow</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Your three.ws profile at three.ws/u/<your-username> is now a real social home. Edit it in place: add a bio, a profile picture and banner image, your location, and a website link — all from an Edit button on your own profile. You can now follow other creators and agents, and they can follow you; every profile shows live follower and following counts you can tap to browse the lists, with one-tap follow buttons throughout. And there's a new Feed at three.ws/feed that gathers the latest avatars, agents, and coin launches from everyone you follow, newest first. Find your profile and Feed links from your account page.</description>+ </item><item><title>Provably-fair vanity grinder now listed in the x402 bazaar</title><link>https://three.ws/vanity/verify</link>diff --git a/public/features.json b/public/features.jsonindex 6b79036bf..f6fd6a009 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T06:17:17.655Z",+ "generated_at": "2026-06-21T06:29:17.034Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/my-agents/my-agents.css b/public/my-agents/my-agents.cssindex 404222a95..c4d988346 100644--- a/public/my-agents/my-agents.css+++ b/public/my-agents/my-agents.css@@ -673,29 +673,94 @@ a:hover {}/* ── State panels ────────────────────────────────────────────────────── */-.my-agents-state {+/* ── Shared state-kit empty-state shell (mirrors src/shared/state-kit.js) ──+ This page is served as a static document with an inline script, so it can't+ ES-import the component. These rules reproduce the tws-es-* shell so the+ empty/zero-results states render identically to the rest of the platform. */+.tws-es {+ display: flex;+ flex-direction: column;+ align-items: center;text-align: center;- padding: 64px 20px;- border: 1px dashed var(--d-border);- border-radius: 14px;- color: #888;-}--.my-agents-state__icon {- font-size: 40px;- margin-bottom: 12px;+ gap: 10px;+ padding: 56px 24px 48px;+ grid-column: 1 / -1;+}+.tws-es-icon {+ font-size: 36px;+ line-height: 1;+ margin-bottom: 4px;+ color: var(--ink-dim, #888);+ opacity: 0.7;}--.my-agents-state__title {- font-size: 17px;+.tws-es-title {+ margin: 0;+ font-size: 15px;font-weight: 600;- color: #ddd;- margin: 0 0 6px;+ color: var(--ink, #e8e8e8);+ letter-spacing: -0.01em;}--.my-agents-state__msg {+.tws-es-body {+ margin: 0;+ font-size: 13.5px;+ line-height: 1.55;+ color: var(--ink-dim, #888);+ max-width: 340px;+}+.tws-es-actions {+ display: flex;+ gap: 10px;+ flex-wrap: wrap;+ justify-content: center;+ margin-top: 8px;+}+.tws-es--compact {+ padding: 22px 16px 20px;+ gap: 7px;+}+.tws-es--compact .tws-es-icon {+ font-size: 26px;+ margin-bottom: 2px;+}+.tws-es--compact .tws-es-title {font-size: 14px;- margin: 0 0 18px;+}+.tws-es--compact .tws-es-body {+ font-size: 12.5px;+ line-height: 1.5;+}+.tws-es-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 6px;+ padding: 0.618rem 1rem;+ border-radius: var(--radius-control, 10px);+ font: 600 13px/1 var(--font-body, system-ui, sans-serif);+ cursor: pointer;+ border: 1px solid rgba(255, 255, 255, 0.1);+ background: rgba(255, 255, 255, 0.08);+ color: var(--ink, #e8e8e8);+ text-decoration: none;+ transition:+ background 0.15s ease,+ border-color 0.15s ease,+ transform 0.12s ease;+}+.tws-es-btn:hover {+ background: rgba(255, 255, 255, 0.12);+ border-color: rgba(255, 255, 255, 0.18);+}+.tws-es-btn:active {+ transform: translateY(1px);+}+.tws-es-btn--primary {+ background: rgba(255, 255, 255, 0.9);+ color: #0a0a0f;+ border-color: transparent;+}+.tws-es-btn--primary:hover {+ background: rgba(255, 255, 255, 0.88);}.my-agents-secondary {@@ -733,7 +798,3 @@ a:hover {font-size: 14px;}-/* ── Inline search empty-state variant ───────────────────────────────── */-.my-agents-state--inline {- padding: 48px 20px;-}diff --git a/public/my-agents/my-agents.js b/public/my-agents/my-agents.jsindex 1cfeff8fd..480ebeaa8 100644--- a/public/my-agents/my-agents.js+++ b/public/my-agents/my-agents.js@@ -239,13 +239,19 @@ function showState(icon, title, msg, cta = null, secondary = null) {toolbarEl.hidden = true;newTopBtn.hidden = true;grid.setAttribute('aria-busy', 'false');+ // Mirrors the shared state-kit empty-state shell (src/shared/state-kit.js+ // → emptyStateHTML): same tws-es-* class names so it renders identically.+ // my-agents-secondary is retained on the learn-more link for the page's+ // own styling.+ const actions = [];+ if (cta) actions.push(`<a class="tws-es-btn tws-es-btn--primary" href="${escapeHtml(cta.href)}">${escapeHtml(cta.label)}</a>`);+ if (secondary) actions.push(`<a class="tws-es-btn my-agents-secondary" href="${escapeHtml(secondary.href)}">${escapeHtml(secondary.label)}</a>`);grid.innerHTML = `- <div class="my-agents-state" style="grid-column: 1 / -1" role="status">- <div class="my-agents-state__icon" aria-hidden="true">${icon}</div>- <p class="my-agents-state__title">${escapeHtml(title)}</p>- <p class="my-agents-state__msg">${escapeHtml(msg)}</p>- ${cta ? `<a class="my-agents-btn" style="display:inline-block;width:auto;padding:9px 22px" href="${escapeHtml(cta.href)}">${escapeHtml(cta.label)}</a>` : ''}- ${secondary ? `<div><a class="my-agents-secondary" href="${escapeHtml(secondary.href)}">${escapeHtml(secondary.label)}</a></div>` : ''}+ <div class="tws-es" style="grid-column: 1 / -1" role="status">+ <div class="tws-es-icon" aria-hidden="true">${icon}</div>+ <h3 class="tws-es-title">${escapeHtml(title)}</h3>+ <p class="tws-es-body">${escapeHtml(msg)}</p>+ ${actions.length ? `<div class="tws-es-actions">${actions.join('')}</div>` : ''}</div>`;}@@ -502,11 +508,13 @@ function renderGrid() {const onchain = unimportedOnchain.filter(matchesQuery);if (searchQuery && native.length === 0 && onchain.length === 0) {+ // Filtered-empty: keep it short — the truly-empty state (showState)+ // carries the rich "what is an agent" explainer.grid.innerHTML = `- <div class="my-agents-state my-agents-state--inline" style="grid-column: 1 / -1" role="status">- <div class="my-agents-state__icon" aria-hidden="true">🔍</div>- <p class="my-agents-state__title">No agents match “${escapeHtml(searchQuery)}”</p>- <p class="my-agents-state__msg">Try a different name or clear the search.</p>+ <div class="tws-es tws-es--compact" style="grid-column: 1 / -1" aria-live="polite">+ <div class="tws-es-icon" aria-hidden="true">🔍</div>+ <h3 class="tws-es-title">No agents match “${escapeHtml(searchQuery)}”</h3>+ <p class="tws-es-body">Try a different name, or clear the search to see all your agents.</p></div>`;return;}@@ -550,7 +558,7 @@ async function loadAgents() {showState('🤖','No agents yet',- 'Create your first agent to get started.',+ 'Agents are AI characters with their own wallet, attachable skills, and an on-chain identity. Create your first one, or browse what the community has shipped.',{ label: 'Create an agent', href: '/create' },{ label: 'Or browse community agents →', href: '/discover' },);diff --git a/public/pay/c/index.html b/public/pay/c/index.htmlindex faa814edc..593f8deff 100644--- a/public/pay/c/index.html+++ b/public/pay/c/index.html@@ -229,8 +229,10 @@$('description').style.display = '';}const payBtn = $('payBtn');- payBtn.textContent = `Pay · ${sku.action_name}`;- payBtn.disabled = false;+ // Stay disabled until loadPrice() confirms a real price + ≥1 payable network.+ // Never let a buyer click Pay before they can see what they'd be charged.+ payBtn.textContent = 'Loading price…';+ payBtn.disabled = true;payBtn.addEventListener('click', () => runCheckout(sku));}@@ -250,7 +252,17 @@}const challenge = await res.json();const accepts = challenge?.accepts || [];+ if (!accepts.length) {+ // A payable 402 with no accepts[] is a payable state with no price —+ // keep Pay disabled rather than charge against an unknown amount.+ renderMeta(`<div class="error">This checkout link has no payment options available right now.</div>`);+ return;+ }renderMeta(metaHtml(accepts));+ // Price is now on screen — enable Pay.+ const payBtn = $('payBtn');+ payBtn.textContent = `Pay · ${sku.action_name}`;+ payBtn.disabled = false;} catch (err) {renderMeta(`<div class="error">Couldn't reach the endpoint: ${escapeHtml(err.message)}</div>`);}diff --git a/public/pumpfun.html b/public/pumpfun.htmlindex 9d3d3e6a4..f36dd3941 100644--- a/public/pumpfun.html+++ b/public/pumpfun.html@@ -128,6 +128,19 @@.pf-status .cta { display: inline-block; margin-top: 10px; padding: 8px 14px; background: var(--accent); color: #fff; border-radius: 6px; font-size: 13px; }.pf-status .cta:hover { filter: brightness(1.1); text-decoration: none; }.pf-status button.cta { border: 0; cursor: pointer; font: inherit; line-height: 1.55; }+ /* Shared state-kit empty-state shell (mirrors src/shared/state-kit.js).+ This inline picker script can't ES-import the component, so these+ rules reproduce the tws-es-* shell for an identical empty state. */+ .tws-es { display: flex; flex-direction: column; align-items: center; text-align: center; gap: 10px; padding: 40px 20px 36px; grid-column: 1 / -1; }+ .tws-es-icon { font-size: 32px; line-height: 1; margin-bottom: 4px; color: var(--muted, #888); opacity: .7; }+ .tws-es-title { margin: 0; font-size: 15px; font-weight: 600; color: var(--ink, #eee); letter-spacing: -.01em; }+ .tws-es-body { margin: 0; font-size: 13px; line-height: 1.55; color: var(--muted, #888); max-width: 320px; }+ .tws-es-actions { display: flex; gap: 10px; flex-wrap: wrap; justify-content: center; margin-top: 8px; }+ .tws-es-btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 8px 16px; border-radius: 10px; font: 600 13px/1 system-ui, sans-serif; cursor: pointer; border: 1px solid rgba(255,255,255,.1); background: rgba(255,255,255,.08); color: var(--ink, #eee); text-decoration: none; transition: background .15s ease, border-color .15s ease, transform .12s ease; }+ .tws-es-btn:hover { background: rgba(255,255,255,.12); border-color: rgba(255,255,255,.18); }+ .tws-es-btn:active { transform: translateY(1px); }+ .tws-es-btn--primary { background: var(--accent, #fff); color: #fff; border-color: transparent; }+ .tws-es-btn--primary:hover { filter: brightness(1.1); }.pf-loadmore { display: block; margin: 16px auto 0; background: #171717; color: #eee; border: 1px solid #2b2b2b; border-radius: 6px; padding: 8px 16px; font-size: 13px; cursor: pointer; }.pf-loadmore:hover { background: #212121; }.pf-loadmore[disabled] { opacity: 0.5; cursor: wait; }@@ -1073,10 +1086,22 @@if (picker.query) items = items.filter((a) => a.name.toLowerCase().includes(picker.query));if (!items.length) {- const msg = tab === 'mine'- ? `No avatars yet. <br><a class="cta" href="/create">Create your first agent</a>`- : picker.query ? `No matches for "${escapeHtml(picker.query)}".` : 'Nothing here yet.';- body.innerHTML = `<div class="pf-status">${msg}</div>`;+ if (tab === 'mine' && !picker.query) {+ body.innerHTML = `<div class="tws-es" role="status">+ <div class="tws-es-icon" aria-hidden="true">🎭</div>+ <h3 class="tws-es-title">No avatars yet</h3>+ <p class="tws-es-body">Avatars are the 3D characters you can launch as a pump.fun agent. Create one to give your token a face, then mint it here.</p>+ <div class="tws-es-actions"><a class="tws-es-btn tws-es-btn--primary" href="/create">Create your first agent</a></div>+ </div>`;+ } else {+ const msg = picker.query+ ? `No matches for “${escapeHtml(picker.query)}”. Try a different name or clear the search.`+ : 'Nothing here yet.';+ body.innerHTML = `<div class="tws-es tws-es--compact" aria-live="polite">+ <div class="tws-es-icon" aria-hidden="true">🔍</div>+ <p class="tws-es-body">${msg}</p>+ </div>`;+ }return;}diff --git a/public/style.css b/public/style.cssindex a84d306d8..4bb66c93b 100644--- a/public/style.css+++ b/public/style.css@@ -5526,94 +5526,6 @@ body[data-viewer-mode='explore'] #layout-switch {max-width: 180px;}-/* ── First-agent empty state (no agent created yet) ──────────────────────── */--.agent-home-empty-panel {- padding: var(--space-lg) var(--space-md);-}--.agent-home-empty-cta {- display: flex;- flex-direction: column;- align-items: center;- text-align: center;- gap: var(--space-xs);-}--.agent-home-empty-ring {- width: 48px;- height: 48px;- border-radius: 50%;- display: grid;- place-items: center;- background: var(--accent-soft, rgba(123, 97, 255, 0.16));- border: 1px solid rgba(255, 255, 255, 0.1);- margin-bottom: var(--space-xs);-}--.agent-home-empty-emoji {- font-size: 22px;- line-height: 1;- color: var(--accent, #8a73ff);-}--.agent-home-empty-title {- font-size: 14px;- font-weight: 600;- letter-spacing: -0.01em;- color: var(--ink, rgba(255, 255, 255, 0.95));-}--.agent-home-empty-sub {- margin: 0 0 var(--space-xs);- max-width: 210px;- font-size: 11px;- line-height: 1.5;- color: rgba(255, 255, 255, 0.5);-}--.agent-home-empty-btn {- display: inline-flex;- align-items: center;- gap: 6px;- padding: 8px 16px;- border-radius: var(--radius-control, 10px);- background: var(--accent, #7b61ff);- color: #fff;- font-size: 12px;- font-weight: 600;- text-decoration: none;- box-shadow: 0 4px 16px rgba(123, 97, 255, 0.3);- transition: transform 0.12s ease, filter 0.12s ease, box-shadow 0.12s ease;-}--.agent-home-empty-btn:hover {- filter: brightness(1.08);- transform: translateY(-1px);- box-shadow: 0 6px 20px rgba(123, 97, 255, 0.4);-}--.agent-home-empty-btn:active {- transform: translateY(0);-}--.agent-home-empty-btn:focus-visible {- outline: 2px solid var(--focus-ring-color, #8a73ff);- outline-offset: 2px;-}--.agent-home-empty-link {- margin-top: 4px;- font-size: 10px;- color: rgba(255, 255, 255, 0.4);- text-decoration: none;- transition: color 0.12s ease;-}--.agent-home-empty-link:hover {- color: rgba(255, 255, 255, 0.7);-}-.agent-timeline-item {display: flex;align-items: flex-start;diff --git a/public/walk-social.json b/public/walk-social.jsonnew file mode 100644index 000000000..7bef37b15--- /dev/null+++ b/public/walk-social.json@@ -0,0 +1,26 @@+[+ {+ "author": "three.ws",+ "handle": "@trythreews",+ "avatar": "/three.svg",+ "url": "https://x.com/trythreews",+ "quote": "Your avatar now walks anywhere on the web. Drop it on any page with one tag, drive it with WASD or a joystick, and let it read articles aloud as it strolls.",+ "platform": "x"+ },+ {+ "author": "three.ws Walk",+ "handle": "@trythreews",+ "avatar": "/three.svg",+ "url": "https://three.ws/walk-embed?env=void&autoplay=true&controls=none",+ "quote": "Six built-in worlds, real-time animation retargeting onto any humanoid rig, and a postMessage API so your site can steer the avatar. No app install — it just runs in the browser.",+ "platform": "x"+ },+ {+ "author": "three.ws Extension",+ "handle": "@trythreews",+ "avatar": "/three.svg",+ "url": "https://three.ws/extension",+ "quote": "Install the Chrome extension and your avatar follows you across the entire web — walking over real pages, narrating what you read, a living 3D browsing companion.",+ "platform": "x"+ }+]diff --git a/public/x402.js b/public/x402.jsindex 1df9493b5..f01c13b7f 100644--- a/public/x402.js+++ b/public/x402.js@@ -667,6 +667,38 @@ const STYLES = `font-size: 11px; color: #5a6378; text-align: center;margin-top: 8px; line-height: 1.4;}++.x402-insuff-title { font-size: 16px; font-weight: 700; color: #0f0f0f; letter-spacing: -0.01em; }+.x402-insuff-sub { font-size: 13px; color: #5a6378; margin-top: 4px; line-height: 1.45; }+.x402-insuff-actions { display: flex; gap: 8px; margin-top: 12px; }+.x402-insuff-actions > * { flex: 1; }+.x402-mini-btn {+ padding: 9px 12px; background: #ffffff; color: #0f0f0f;+ border: 1.5px solid #e2e5ec; border-radius: 10px;+ font-size: 13px; font-weight: 600; font-family: inherit;+ cursor: pointer; text-align: center; text-decoration: none;+ display: inline-flex; align-items: center; justify-content: center;+ transition: border-color 0.12s, background 0.12s;+}+.x402-mini-btn:hover { border-color: #0a84ff; background: #f7faff; text-decoration: none; }+.x402-mini-btn:focus-visible { outline: 2px solid #0a84ff; outline-offset: 2px; }++.x402-payee { font-size: 12px; color: #8a90a8; text-align: center; margin: 0 0 10px; }+.x402-payee-addr { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: #0a84ff; text-decoration: none; border-bottom: 1px dotted rgba(10,132,255,0.4); }+.x402-payee-addr:hover { border-bottom-style: solid; text-decoration: none; }+.x402-payee-addr:focus-visible { outline: 2px solid #0a84ff; outline-offset: 2px; border-radius: 2px; }+.x402-trust { font-size: 11px; color: #8a90a8; text-align: center; margin-top: 12px; line-height: 1.45; }++/* Keyboard focus indicator on every interactive control in the money modal. */+.x402-overlay button:focus-visible,+.x402-overlay a:focus-visible,+.x402-overlay input:focus-visible,+.x402-overlay [tabindex]:focus-visible {+ outline: 2px solid #0a84ff;+ outline-offset: 2px;+ border-radius: 8px;+}+.x402-modal:focus { outline: none; }.x402-siwx-fallback {font-size: 12px; color: #b45309; line-height: 1.45;padding: 8px 10px; border-radius: 8px;@@ -825,45 +857,115 @@ class CheckoutModal {const overlay = document.createElement('div');overlay.className = 'x402-overlay';overlay.innerHTML = `- <div class="x402-modal" role="dialog" aria-modal="true" aria-label="x402 payment">+ <div class="x402-modal" role="dialog" aria-modal="true" aria-label="x402 payment" tabindex="-1"><div class="x402-head"><div class="x402-merchant"><div class="x402-name" data-merchant>${escapeHtml(this.opts.merchant || 'Payment')}</div><div class="x402-action" data-action>${escapeHtml(this.opts.action || 'Pay-per-call')}</div></div>- <button class="x402-close" data-close aria-label="Close">✕</button>+ <button class="x402-close" data-close aria-label="Close payment">✕</button></div><div class="x402-price-row"><div class="x402-price" data-price>—<span class="x402-currency"> USDC</span></div><div class="x402-network" data-network>resolving…</div></div>- <div class="x402-body" data-body></div>+ <div class="x402-body" data-body role="status" aria-live="polite"></div><div class="x402-foot"><span class="x402-secure">x402 · onchain settled</span><a href="https://three.ws" target="_blank" rel="noopener">Powered by three.ws</a></div></div>`;+ // Remember what to restore focus to when the modal closes.+ this.previouslyFocused =+ typeof document !== 'undefined' && document.activeElement instanceof HTMLElement+ ? document.activeElement+ : null;document.body.appendChild(overlay);this.overlay = overlay;+ this.modalEl = overlay.querySelector('.x402-modal');this.bodyEl = overlay.querySelector('[data-body]');this.priceEl = overlay.querySelector('[data-price]');this.networkEl = overlay.querySelector('[data-network]');+ // Make the rest of the page inert to AT + tab order while the money modal is+ // open, so focus can't wander behind it mid-payment. Restored in close().+ this._inerted = [];+ for (const child of Array.from(document.body.children)) {+ if (child !== overlay && !child.hasAttribute('inert')) {+ child.setAttribute('inert', '');+ child.setAttribute('aria-hidden', 'true');+ this._inerted.push(child);+ }+ }overlay.querySelector('[data-close]').addEventListener('click', () => this.close('cancelled'));overlay.addEventListener('click', (e) => { if (e.target === overlay) this.close('cancelled'); });- this.onKey = (e) => { if (e.key === 'Escape') this.close('cancelled'); };+ this.onKey = (e) => {+ if (e.key === 'Escape') { this.close('cancelled'); return; }+ if (e.key === 'Tab') this._trapTab(e);+ };document.addEventListener('keydown', this.onKey);- requestAnimationFrame(() => overlay.classList.add('x402-open'));+ requestAnimationFrame(() => {+ overlay.classList.add('x402-open');+ this._focusFirst();+ });return new Promise((resolve, reject) => {this.resolve = resolve;this.reject = reject;});}+ // All tabbable elements currently visible inside the modal.+ _focusable() {+ if (!this.modalEl) return [];+ return Array.from(+ this.modalEl.querySelectorAll(+ 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',+ ),+ ).filter((el) => el.offsetParent !== null || el === document.activeElement);+ }++ // On open (and after re-renders the caller cares about) land focus on the+ // primary action — wallet/retry/pay button — rather than the ✕, so keyboard+ // users reach the thing they came to do first.+ _focusFirst() {+ if (!this.modalEl) return;+ const primary = this.modalEl.querySelector(+ '[data-wallet]:not([disabled]), [data-retry], .x402-pay-btn:not([disabled])',+ );+ (primary || this._focusable()[0] || this.modalEl).focus();+ }++ // Cycle Tab / Shift+Tab within the modal; pull stray focus back inside.+ _trapTab(e) {+ const f = this._focusable();+ if (!f.length) { e.preventDefault(); this.modalEl.focus(); return; }+ const first = f[0];+ const last = f[f.length - 1];+ const active = document.activeElement;+ const inside = this.modalEl.contains(active);+ if (e.shiftKey) {+ if (active === first || !inside) { e.preventDefault(); last.focus(); }+ } else if (active === last || !inside) {+ e.preventDefault();+ first.focus();+ }+ }+close(reason) {if (this.disposed) return;this.disposed = true;document.removeEventListener('keydown', this.onKey);+ // Un-inert the rest of the page and restore focus to the trigger.+ if (this._inerted) {+ for (const el of this._inerted) {+ el.removeAttribute('inert');+ el.removeAttribute('aria-hidden');+ }+ this._inerted = null;+ }+ if (this.previouslyFocused && typeof this.previouslyFocused.focus === 'function') {+ try { this.previouslyFocused.focus(); } catch (_) { /* element gone — ignore */ }+ }this.overlay.classList.remove('x402-open');setTimeout(() => this.overlay.remove(), 180);if (reason === 'cancelled' && this.reject) {@@ -988,11 +1090,26 @@ class CheckoutModal {: '';const givingBox = this.solanaGiving ? this.renderGivingBox(this.solanaGiving) : '';this.givingShown = !!this.solanaGiving;+ // Trust signal: show WHO the buyer is paying (on-chain recipient) before they+ // pick a wallet. The primary accept's payTo; link to the address explorer.+ const payeeAccept = this.accept || solanaAccept || evmAccept;+ const payTo = payeeAccept?.payTo;+ const payeeUrl = payTo ? addressExplorerUrl(payeeAccept.network, payTo) : null;+ const payeeShort = payTo ? `${payTo.slice(0, 6)}…${payTo.slice(-4)}` : '';+ const payeeBox = payTo+ ? `<div class="x402-payee">Pays to ${+ payeeUrl+ ? `<a class="x402-payee-addr" href="${payeeUrl}" target="_blank" rel="noopener" title="${escapeHtml(payTo)}">${escapeHtml(payeeShort)} ↗</a>`+ : `<span class="x402-payee-addr">${escapeHtml(payeeShort)}</span>`+ }</div>`+ : '';this.bodyEl.innerHTML = `${this.renderSteps('connect', { discover: 'done' })}+ ${payeeBox}${fallbackBox}${givingBox}<div class="x402-wallet-buttons">${buttons.join('')}</div>+ <div class="x402-trust">You approve the payment in your own wallet — funds move only when the service runs, settled on-chain.</div>`;const giveEl = this.bodyEl.querySelector('[data-giving]');if (giveEl) giveEl.addEventListener('change', (e) => { this.includeDonation = !!e.target.checked; });@@ -1060,6 +1177,53 @@ class CheckoutModal {this.bodyEl.querySelector('[data-retry]').addEventListener('click', () => this.start());}+ // Dedicated, actionable state for the most common payment failure: the wallet+ // can't cover the price. Shows needed / balance / shortfall, the connected+ // wallet (copy + explorer), and a retry that re-runs once the buyer tops up.+ renderInsufficientFunds(info) {+ const addr = info.owner || '';+ const addrShort = addr ? `${addr.slice(0, 6)}…${addr.slice(-4)}` : '—';+ const viewUrl = addressExplorerUrl(info.network, addr);+ const netLabel = networkLabel(info.network);+ const sym = escapeHtml(info.symbol);+ this.bodyEl.innerHTML = `+ ${this.renderSteps('authorize', {+ discover: 'done',+ connect: 'done',+ authorize: 'error',+ authorize_meta: 'insufficient funds',+ })}+ <div class="x402-insuff-title">Not enough ${sym}</div>+ <div class="x402-insuff-sub">Add ${sym} to your wallet on ${escapeHtml(netLabel)}, then try again — nothing was charged.</div>+ <div class="x402-receipt" style="margin-top:12px">+ <div class="x402-receipt-row"><span class="x402-k">needed</span><span class="x402-v">${escapeHtml(info.required)} ${sym}</span></div>+ <div class="x402-receipt-row"><span class="x402-k">your balance</span><span class="x402-v">${escapeHtml(info.balance)} ${sym}</span></div>+ <div class="x402-receipt-row"><span class="x402-k">short by</span><span class="x402-v" style="color:#e5484d;font-weight:700">${escapeHtml(info.shortfall)} ${sym}</span></div>+ <div class="x402-receipt-row"><span class="x402-k">wallet</span><span class="x402-v">${escapeHtml(addrShort)}</span></div>+ </div>+ <div class="x402-insuff-actions">+ <button class="x402-mini-btn" data-copy type="button" aria-label="Copy wallet address">Copy address</button>+ ${viewUrl ? `<a class="x402-mini-btn" href="${viewUrl}" target="_blank" rel="noopener">View wallet ↗</a>` : ''}+ </div>+ <button class="x402-pay-btn" data-retry style="margin-top:10px">I've added funds — try again</button>+ `;+ const copyBtn = this.bodyEl.querySelector('[data-copy]');+ if (copyBtn) {+ copyBtn.addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(addr);+ copyBtn.textContent = 'Copied ✓';+ setTimeout(() => {+ copyBtn.textContent = 'Copy address';+ }, 1500);+ } catch (_) {+ /* clipboard blocked — non-fatal */+ }+ });+ }+ this.bodyEl.querySelector('[data-retry]').addEventListener('click', () => this.start());+ }+renderDone({ result, payment, siwx }) {const resultStr = typeof result === 'string' ? result : JSON.stringify(result, null, 2);let receiptHtml;@@ -1201,6 +1365,10 @@ class CheckoutModal {browserRollbackReservation(this.spendReservation);this.spendReservation = null;}+ if (err?.code === 'insufficient_funds') {+ this.renderInsufficientFunds(err.insufficient);+ return;+ }this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));}}@@ -1241,6 +1409,8 @@ class CheckoutModal {}}+ this.renderProgress('authorize', { text: 'Checking your balance…' });+ await assertBalance({ accept, owner: payerAddress, provider: eth });this.renderProgress('authorize', { text: `Authorize ${formatAmount(accept.amount)} USDC…` });// EIP-3009 transferWithAuthorization typed-data signature.@@ -1315,6 +1485,10 @@ class CheckoutModal {browserRollbackReservation(this.spendReservation);this.spendReservation = null;}+ if (err?.code === 'insufficient_funds') {+ this.renderInsufficientFunds(err.insufficient);+ return;+ }this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));}}@@ -1734,6 +1908,7 @@ function readOptsFrom(el) {}export function init() {+ if (typeof document === 'undefined') return;document.querySelectorAll('[data-x402-endpoint]').forEach(bindElement);}diff --git a/scripts/probe-app-empty-state.mjs b/scripts/probe-app-empty-state.mjsdeleted file mode 100644index b677ab1b8..000000000--- a/scripts/probe-app-empty-state.mjs+++ /dev/null@@ -1,53 +0,0 @@-// One-off probe: what does a brand-new (no-agent, signed-out) user see at /app?-// Captures the agent-home container, sidebar text, console errors, and a shot.-import { chromium } from 'playwright';--const URL = process.env.PROBE_URL || 'http://localhost:3000/app';-const browser = await chromium.launch({- args: [- '--use-gl=angle',- '--use-angle=swiftshader',- '--enable-unsafe-swiftshader',- '--disable-gpu-sandbox',- '--no-sandbox',- ],-});-const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 } });-const page = await ctx.newPage();--const errors = [];-page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });-page.on('pageerror', (e) => errors.push('PAGEERROR: ' + e.message));--// Fresh user: no localStorage, no session.-await page.addInitScript(() => { try { localStorage.clear(); sessionStorage.clear(); } catch {} });-await page.goto(URL, { waitUntil: 'domcontentloaded', timeout: 45000 }).catch((e) => errors.push('GOTO: ' + e.message));-// The agent-home container is populated asynchronously after the app boots —-// poll for it rather than relying on networkidle (the 3D app holds connections open).-await page.waitForFunction(() => {- const el = document.getElementById('agent-home-container');- return el && (el.innerHTML || '').trim().length > 0;-}, { timeout: 20000 }).catch((e) => errors.push('WAIT_CONTAINER: ' + e.message));--const report = await page.evaluate(() => {- const home = document.getElementById('agent-home-container');- const authGate = document.querySelector('[data-auth-gate], #auth-gate, .auth-gate, #signin, .signin');- const sidebar = document.querySelector('#sidebar, .sidebar, aside');- const visible = (el) => !!el && el.offsetParent !== null && (el.textContent || '').trim().length > 0;- return {- homeExists: !!home,- homeHasContent: home ? (home.innerHTML || '').trim().length : -1,- homeText: home ? (home.textContent || '').trim().slice(0, 200) : null,- authGateVisible: visible(authGate),- authGateText: authGate ? (authGate.textContent || '').trim().slice(0, 160) : null,- sidebarText: sidebar ? (sidebar.textContent || '').trim().slice(0, 200) : null,- bodyHasCreateCTA: /create.*(your )?(first )?agent|get started|sign in|log in/i.test(document.body.textContent || ''),- };-});--console.log(JSON.stringify({ report, errors: errors.slice(0, 20) }, null, 2));-await page- .screenshot({ path: '/tmp/app-fresh-user.png', fullPage: false, timeout: 5000, animations: 'disabled' })- .then(() => console.log('screenshot: /tmp/app-fresh-user.png'))- .catch(() => console.log('screenshot: skipped (animating canvas)'));-await browser.close();diff --git a/scripts/x402-modal/.gitignore b/scripts/x402-modal/.gitignoreindex 11ff966ae..99d0bcd52 100644--- a/scripts/x402-modal/.gitignore+++ b/scripts/x402-modal/.gitignore@@ -1,2 +1,3 @@key.jsonbrowser-*.png+modal-*.pngdiff --git a/scripts/x402-modal/screenshot.mjs b/scripts/x402-modal/screenshot.mjsnew file mode 100644index 000000000..ad4a47eb1--- /dev/null+++ b/scripts/x402-modal/screenshot.mjs@@ -0,0 +1,61 @@+#!/usr/bin/env node+// Visual smoke test for the redesigned modal: opens it against the local+// merchant and screenshots the connect screen (token picker + wallet + trust+// line) in light and dark. Needs no funds — it stops before signing.+//+// node scripts/x402-modal/screenshot.mjs++import { spawn } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import bs58 from 'bs58';+import { chromium } from 'playwright';+import { loadBuyer } from './_lib.mjs';++const __dirname = dirname(fileURLToPath(import.meta.url));+const PORT = Number(process.env.PORT || 8412);+const BASE = `http://localhost:${PORT}`;+const buyer = loadBuyer();+const pub = buyer.publicKey.toBase58();++function startMerchant() {+ const child = spawn('node', [join(__dirname, 'merchant-server.mjs')], {+ env: { ...process.env, PORT: String(PORT), BUYER: pub, X402_TEST_KEY: bs58.encode(buyer.secretKey) },+ stdio: ['ignore', 'pipe', 'inherit'],+ });+ return new Promise((resolve, reject) => {+ const to = setTimeout(() => reject(new Error('merchant did not start')), 10000);+ child.stdout.on('data', (d) => { if (String(d).includes('merchant+settler on')) { clearTimeout(to); resolve(child); } });+ });+}++const merchant = await startMerchant();+const browser = await chromium.launch({ headless: true });+let failed = false;+try {+ for (const scheme of ['light', 'dark']) {+ const ctx = await browser.newContext({ colorScheme: scheme, viewport: { width: 480, height: 820 } });+ const page = await ctx.newPage();+ await page.emulateMedia({ colorScheme: scheme });+ await page.addInitScript(({ secret, pubkey }) => {+ window.__X402_SECRET = secret; window.__X402_PUBKEY = pubkey;+ }, { secret: Array.from(buyer.secretKey), pubkey: pub });+ await page.goto(BASE, { waitUntil: 'networkidle' });+ await page.waitForFunction(() => window.__startPay && window.solana?.isPhantom, null, { timeout: 15000 });+ await page.evaluate(() => window.__startPay('USDC'));+ await page.waitForSelector('.x402-wallet-btn', { timeout: 15000 });+ await page.waitForSelector('.x402-trust', { timeout: 5000 }).catch(() => {});+ await page.waitForTimeout(400); // let the enter animation settle+ const out = join(__dirname, `modal-connect-${scheme}.png`);+ await page.screenshot({ path: out });+ console.log(`✓ ${scheme}: ${out}`);+ await ctx.close();+ }+} catch (e) {+ failed = true;+ console.error('✗ screenshot failed:', e.message);+} finally {+ await browser.close().catch(() => {});+ merchant.kill();+}+process.exit(failed ? 1 : 0);diff --git a/src/a-me.js b/src/a-me.jsindex ae0fc3507..0eaa379d2 100644--- a/src/a-me.js+++ b/src/a-me.js@@ -159,6 +159,10 @@ function renderHub(main, me, agents, avatars, billing) {<div class="ame-hero-left"><h1 class="ame-title">${esc(displayName)}'s Agents</h1><p class="ame-subtitle">Manage your AI agents, avatars, skills, memory, and monetization.</p>+ <div class="ame-section-actions" style="margin-top:.9rem">+ ${me.username ? `<a class="ame-btn small" href="/u/${encodeURIComponent(me.username)}">View public profile</a>` : ''}+ <a class="ame-btn small" href="/feed">Feed</a>+ </div></div><div class="ame-hero-stats"><div class="ame-stat"><span class="ame-stat-val">${agents.length}</span><span class="ame-stat-label">Agents</span></div>diff --git a/src/agent-home.js b/src/agent-home.jsindex 96becd499..1979780ba 100644--- a/src/agent-home.js+++ b/src/agent-home.js@@ -81,42 +81,8 @@ export class AgentHome {// ── Identity Card ─────────────────────────────────────────────────────────- // Brand-new owner with no agent yet — the activation call-to-action that- // replaces the empty identity card, so the sidebar always tells a first-time- // user what to do next instead of rendering a placeholder "Agent / no wallet".- _buildEmptyState() {- const panel = document.createElement('div');- panel.className = 'agent-home-panel agent-home-empty-panel';- panel.innerHTML = `- <div class="agent-home-empty-cta" role="region" aria-label="Get started">- <div class="agent-home-empty-ring" aria-hidden="true">- <span class="agent-home-empty-emoji">◎</span>- </div>- <div class="agent-home-empty-title">Create your first agent</div>- <p class="agent-home-empty-sub">Give a 3D character a name, a brain, and its own on-chain wallet — live in under a minute.</p>- <a class="agent-home-empty-btn" href="/create">- <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" focusable="false"><path d="M11 11V5h2v6h6v2h-6v6h-2v-6H5v-2z"/></svg>- Create your agent- </a>- <a class="agent-home-empty-link" href="/discover">or explore what others built →</a>- </div>- `;- this.container.appendChild(panel);- this._panel = panel;- }-_buildPanel() {const id = this.identity;-- // No real agent id yet (a freshly signed-in owner who hasn't created one):- // the normal identity card would render a meaningless "Agent / no wallet"- // phantom. Show the create-your-first-agent CTA instead. Real agents and- // visitor-viewed agents always carry an id, so they are unaffected.- if (!id.id) {- this._buildEmptyState();- return;- }-const skills = id.skills || [];// Shared agent-wallet chip for the identity card. Default-deny ownership:diff --git a/src/dashboard-next/pages/analytics.js b/src/dashboard-next/pages/analytics.jsindex 89c3aafe7..1ae241e35 100644--- a/src/dashboard-next/pages/analytics.js+++ b/src/dashboard-next/pages/analytics.js@@ -6,7 +6,7 @@import { mountShell } from '../shell.js';import { requireUser, get, esc, relTime, formatUsdc, ApiError } from '../api.js';-import { errorStateHTML, ensureStateKitStyles } from '../../shared/state-kit.js';+import { errorStateHTML, emptyStateHTML, ensureStateKitStyles } from '../../shared/state-kit.js';const RANGES = [{ key: '7d', days: 7, label: '7 days', granularity: 'day' },@@ -449,7 +449,16 @@ function renderAgentTable(agents, widgets, widgetStats) {panel.className = 'dn-panel';if (!agents.length) {- panel.innerHTML = `<div class="dn-panel-title">Agent Performance</div><div class="ana-chart-empty">No agents yet. <a href="/dashboard/agents">Create one</a></div>`;+ panel.innerHTML = `<div class="dn-panel-title">Agent Performance</div>${emptyStateHTML({+ icon: '🤖',+ title: 'No agents yet',+ body: 'Per-agent views, chats, and conversion rates show up here once you have an agent live. Create one to start tracking how it performs.',+ actions: [+ { label: '+ Create your first agent', href: '/dashboard/agents', id: 'create-agent', primary: true },+ { label: "What's an agent?", href: '/docs/agents-vs-avatars', id: 'learn-agents' },+ ],+ compact: true,+ })}`;return panel;}diff --git a/src/dashboard-next/pages/api.js b/src/dashboard-next/pages/api.jsindex 8e1c373e8..57a37544b 100644--- a/src/dashboard-next/pages/api.js+++ b/src/dashboard-next/pages/api.js@@ -20,7 +20,7 @@import { mountShell } from '../shell.js';import { requireUser, get, post, del, put, esc, relTime, ApiError } from '../api.js';-import { errorStateHTML, ensureStateKitStyles } from '../../shared/state-kit.js';+import { errorStateHTML, emptyStateHTML, ensureStateKitStyles } from '../../shared/state-kit.js';// Scopes accepted by /api/keys — match api/keys/index.js ALLOWED_SCOPES exactly.const SCOPES = [@@ -1048,7 +1048,16 @@ function renderPolicy(host, state) {</div>${agents.map((a, i) => renderPolicyRow(a, i)).join('')}</div>`- : `<div class="dn-empty"><h3>No agents yet</h3><p>Create an agent before locking down where it can be embedded.</p></div>`}+ : emptyStateHTML({+ icon: '🤖',+ title: 'No agents yet',+ body: 'Embed policies let you restrict which sites each agent can run on. Create an agent first, then come back to lock down where it can be embedded.',+ actions: [+ { label: '+ Create your first agent', href: '/dashboard/agents', id: 'create-agent', primary: true },+ { label: "What's an agent?", href: '/docs/agents-vs-avatars', id: 'learn-agents' },+ ],+ compact: true,+ })}</div>`;diff --git a/src/dashboard-next/pages/avatars.js b/src/dashboard-next/pages/avatars.jsindex 3d5493d1f..c9b269aef 100644--- a/src/dashboard-next/pages/avatars.js+++ b/src/dashboard-next/pages/avatars.js@@ -13,6 +13,8 @@ import { createFromTemplate } from '../../shared/template-picker.js';import { onchainBadgeHTML, ensureOnchainBadgeStyles } from '../../shared/onchain-badge.js';import { walletChipHTML, wireWalletChips } from '../../shared/agent-wallet-chip.js';import { rigBadgeHTML, matchesRigFilter, RIG_FILTERS } from '../../shared/rig-status.js';+import { emptyStateEl, ensureStateKitStyles } from '../../shared/state-kit.js';+ensureStateKitStyles();const PAGE_SIZE = 24;const VISIBILITIES = ['public', 'unlisted', 'private'];@@ -1173,20 +1175,18 @@ function renderSkeletons(grid, n) {}function emptyBlock() {- const wrap = document.createElement('div');- wrap.className = 'dn-empty';- wrap.style.gridColumn = '1 / -1';- wrap.innerHTML = `- <h3>No avatars yet.</h3>- <p>Build your first 3D agent — describe it in a sentence and watch it generate, start from a ready-made template, sculpt one from scratch, or drop a selfie.</p>- <div style="display:flex;gap:8px;flex-wrap:wrap;justify-content:center">- <a class="dn-btn primary" href="/create/prompt">Describe it · prompt → 3D</a>- <button type="button" class="dn-btn" data-empty-template>Start from a template</button>- <a class="dn-btn" href="/create/studio">Build from scratch</a>- <a class="dn-btn" href="/create/selfie">Create from selfie</a>- </div>- `;- wrap.querySelector('[data-empty-template]')?.addEventListener('click', () => createFromTemplate());+ const wrap = emptyStateEl({+ icon: '🎭',+ title: 'No avatars yet',+ body: 'Avatars are the 3D bodies your agents wear — embeddable, animated characters you own. Make your first one: describe it in a sentence and watch it generate, start from a ready-made template, sculpt one from scratch, or drop a selfie.',+ actions: [+ { label: 'Describe it · prompt → 3D', href: '/create/prompt', id: 'create-prompt', primary: true },+ { label: 'Start from a template', id: 'create-template' },+ { label: 'Build from scratch', href: '/create/studio', id: 'create-studio' },+ { label: 'Create from selfie', href: '/create/selfie', id: 'create-selfie' },+ ],+ });+ wrap.querySelector('[data-sk-action="create-template"]')?.addEventListener('click', () => createFromTemplate());return wrap;}diff --git a/src/dashboard-next/pages/developers.js b/src/dashboard-next/pages/developers.jsindex 82e05bb9d..4c09859e3 100644--- a/src/dashboard-next/pages/developers.js+++ b/src/dashboard-next/pages/developers.js@@ -406,8 +406,17 @@ curl "${location.origin}/api/avatar/render" | jq .`,});}- avatarInput.addEventListener('input', updateUrl);- sizeInput.addEventListener('input', updateUrl);+ // updateUrl() regenerates every code example (HTML, React, Vue, …) from+ // scratch, so firing it on each keystroke rebuilds all of them per character+ // and spams the URL preview. Debounce the free-text inputs; the format select+ // is a discrete change and stays immediate.+ let _updateTimer;+ const debouncedUpdate = () => {+ clearTimeout(_updateTimer);+ _updateTimer = setTimeout(updateUrl, 150);+ };+ avatarInput.addEventListener('input', debouncedUpdate);+ sizeInput.addEventListener('input', debouncedUpdate);formatSelect.addEventListener('change', updateUrl);sceneGrid.addEventListener('click', (e) => {diff --git a/src/dashboard-next/pages/library/brain.js b/src/dashboard-next/pages/library/brain.jsindex b6332d588..001452164 100644--- a/src/dashboard-next/pages/library/brain.js+++ b/src/dashboard-next/pages/library/brain.js@@ -3,6 +3,8 @@// and live-test the brain against streaming responses — all from the dashboard.import { get, put, esc } from '../../api.js';+import { emptyStateHTML, ensureStateKitStyles } from '../../../shared/state-kit.js';+ensureStateKitStyles();// ── Model registry ─────────────────────────────────────────────────────────────// Mirrors the MODELS table in api/llm/anthropic.js.@@ -350,12 +352,15 @@ export async function renderBrain(host) {if (!agents.length) {agentSel.innerHTML = '<option value="">No agents yet</option>';- contentEl.innerHTML = `- <div class="dn-empty">- <h3>No agents yet</h3>- <p>Create an agent first, then configure its brain here.</p>- <div style="margin-top:12px"><a class="dn-btn primary" href="/create">Create an agent</a></div>- </div>`;+ contentEl.innerHTML = emptyStateHTML({+ icon: '🤖',+ title: 'No agents yet',+ body: 'The brain is where you pick an agent\'s LLM, write its system prompt, and live-test how it responds. Create an agent first, then tune its brain here.',+ actions: [+ { label: '+ Create your first agent', href: '/dashboard/agents', id: 'create-agent', primary: true },+ { label: "What's an agent?", href: '/docs/agents-vs-avatars', id: 'learn-agents' },+ ],+ });return;}diff --git a/src/dashboard/dashboard.js b/src/dashboard/dashboard.jsindex e357645a9..2152ffde6 100644--- a/src/dashboard/dashboard.js+++ b/src/dashboard/dashboard.js@@ -4,6 +4,7 @@import { mountAgentSolanaWalletCard } from '/src/agent-solana-wallet.js';import { mountAgentVanityGrinderCard } from '/src/agent-vanity-grinder.js';import { onchainBadgeHTML } from '/src/shared/onchain-badge.js';+import { emptyStateHTML } from '/src/shared/state-kit.js';import { renderError as renderAsyncError } from '/src/shared/async-state.js';import { log } from '../shared/log.js';import { safeUrl } from '../safe-url.js';@@ -338,19 +339,16 @@ async function renderAgents(root) {}function renderAgentsEmpty(list, createHost) {- list.innerHTML = `- <div class="empty" style="grid-column:1/-1; padding:48px 28px; text-align:center;">- <div style="font-size:48px; line-height:1; margin-bottom:14px;" aria-hidden="true">🤖</div>- <h2 style="margin:0 0 8px; font-size:20px; color:#eee;">No agents yet</h2>- <p style="margin:0 0 22px; color:#888; max-width:460px; margin-left:auto; margin-right:auto;">- Create your first three.ws agent — it gets a wallet, a set of skills, and can be deployed on-chain as an ERC-8004 identity.- </p>- <div style="display:flex; gap:10px; justify-content:center; flex-wrap:wrap;">- <button class="btn-primary" id="agents-empty-new">Create agent</button>- <a href="/my-agents" class="btn-primary" style="background:#222230; color:#ddd;">Import from wallet</a>- </div>- </div>`;- list.querySelector('#agents-empty-new').addEventListener('click', () =>+ list.innerHTML = emptyStateHTML({+ icon: '🤖',+ title: 'No agents yet',+ body: 'Agents are AI characters you create here — each gets its own wallet, a set of attachable skills, and can be deployed on-chain as an ERC-8004 identity. Create one, or import an agent already in your wallet.',+ actions: [+ { label: 'Create agent', id: 'agents-empty-new', primary: true },+ { label: 'Import from wallet', href: '/my-agents' },+ ],+ });+ list.querySelector('[data-sk-action="agents-empty-new"]').addEventListener('click', () =>openCreateForm(createHost, list),);}diff --git a/src/forge.js b/src/forge.jsindex b8361bb3a..8da2fb0c6 100644--- a/src/forge.js+++ b/src/forge.js@@ -311,7 +311,7 @@ function startElapsed() {if (els.genProgress) els.genProgress.dataset.over = String(over);els.genMeta.innerHTML = over? `Elapsed <strong>${s}s</strong> · longer than usual, still working`- : `Elapsed <strong>${s}s</strong> · ~${typical}s typical`;+ : `Elapsed <strong>${s}s</strong> · ~${Math.max(1, typical - s)}s left`;} else {// Unknown duration — the bar travels (indeterminate) and we report only// the honest elapsed count.@@ -1349,6 +1349,17 @@ async function startJob({ prompt, imageUrls, skipValidation, payment }) {e.gate = data;throw e;}+ // Free lane shed this request at the fleet concurrency cap — an influx of+ // demand, not the user's quota. Recoverable with a short auto-retry, framed as+ // "high demand" rather than a failure the user caused. (provider_busy comes+ // from an explicit free-engine pick at capacity; free_lane_unavailable from the+ // Spaces chain being briefly all-down.)+ if (data.error === 'provider_busy' || data.error === 'free_lane_unavailable') {+ const e = new Error(data.message || 'The free 3D engines are at capacity right now.');+ e.kind = 'busy';+ e.retryAfter = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 15;+ throw e;+ }if (!res.ok) {throw new Error(data.message || `The generator returned ${res.status}.`);}@@ -1809,7 +1820,7 @@ function stopRateLimitCountdown() {}}-function showRateLimited({ retryAfter = 10, unavailable = false }) {+function showRateLimited({ retryAfter = 10, unavailable = false, busy = false }) {stopElapsed();stopRateLimitCountdown();if (els.generateAnyway) els.generateAnyway.classList.add('is-hidden');@@ -1821,9 +1832,11 @@ function showRateLimited({ retryAfter = 10, unavailable = false }) {if (els.refineLocally) els.refineLocally.classList.toggle('is-hidden', !canRefineLocally);let remaining = Math.max(1, Math.ceil(retryAfter));- const base = unavailable- ? 'The generator is temporarily unavailable.'- : 'You’ve hit the generation limit.';+ const base = busy+ ? 'High demand — the free 3D engines are all busy right now.'+ : unavailable+ ? 'The generator is temporarily unavailable.'+ : 'You’ve hit the generation limit.';const tail = canRefineLocally ? ' Or refine your current model now — instant and unlimited.' : '';const render = () => {@@ -1995,6 +2008,13 @@ async function run(cfg) {showRateLimited({ retryAfter: err.retryAfter, unavailable: err.unavailable });return;}+ // Free lane at capacity under load — same recoverable countdown UI, framed as+ // high demand. Auto-retry lands the user in line as slots free up, and the+ // local-refine escape hatch still applies when a model is already on screen.+ if (err.kind === 'busy') {+ showRateLimited({ retryAfter: err.retryAfter, busy: true });+ return;+ }// High-tier $THREE gate: open the designed upsell (Get $THREE / what you hold// vs. need — plus the working Pay-per-use CTA) and reset to the idle composer// so the user can switch tier, hold, or pay.diff --git a/src/marketplace.js b/src/marketplace.jsindex 61a6adcc0..02ec1a6f5 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -22,7 +22,7 @@ import { safeUrl } from './safe-url.js';import { walletChipHTML, walletChipEl, wireWalletChips } from './shared/agent-wallet-chip.js';import { seeInWorldHref, hasCustomAvatar } from './shared/agent-3d.js';import { coinChipHTML } from './shared/agent-coin.js';-import { skeletonHTML, errorStateHTML, ensureStateKitStyles } from './shared/state-kit.js';+import { skeletonHTML, emptyStateHTML, errorStateHTML, ensureStateKitStyles } from './shared/state-kit.js';import { log } from './shared/log.js';import { track, trackError, ANALYTICS_EVENTS } from './analytics.js';ensureStateKitStyles();@@ -4239,12 +4239,16 @@ function renderMineGrid() {: '';}if (!mineState.items.length) {- grid.innerHTML = `<div class="market-empty-cta">- <h3>No agents yet</h3>- <p>Create your first agent — it'll appear here as draft, then publish when you're ready.</p>- <button id="mine-empty-new">+ New Agent</button>- </div>`;- $('mine-empty-new')?.addEventListener('click', () => {+ grid.innerHTML = emptyStateHTML({+ icon: '🤖',+ title: 'No agents yet',+ body: "Agents you create show up here as drafts first, then go live once you publish. Each gets an on-chain identity, its own wallet, and attachable skills.",+ actions: [+ { label: '+ New Agent', id: 'mine-empty-new', primary: true },+ { label: "What's an agent?", href: '/docs/agents-vs-avatars' },+ ],+ });+ grid.querySelector('[data-sk-action="mine-empty-new"]')?.addEventListener('click', () => {location.href = '/agent/new';});return;diff --git a/src/three-token-page.js b/src/three-token-page.jsindex 5dac2ddca..70f2185b0 100644--- a/src/three-token-page.js+++ b/src/three-token-page.js@@ -10,6 +10,7 @@ import { createThreeTokenData, THREE_MINT } from './pump/three-token-data.js';import { mountBondingCurve } from './widgets/bonding-curve.js';import { openSwapModal } from './swap-jupiter.js';import { trackFunnelStep, ANALYTICS_EVENTS } from './analytics.js';+import { emptyStateHTML, ensureStateKitStyles } from './shared/state-kit.js';const SOL_MINT = 'So11111111111111111111111111111111111111112';const PUMP_URL = `https://pump.fun/coin/${THREE_MINT}`;@@ -320,6 +321,7 @@ let _lastThreePrice = null;// ── boot ─────────────────────────────────────────────────────────────────────function boot() {injectStyles();+ ensureStateKitStyles();document.title = '$THREE · Live price, chart & trades · three.ws';// $THREE holder funnel, step 1: the token page is in view.@@ -352,7 +354,14 @@ function boot() {<div class="tk-card"><h2 style="display:flex;align-items:center;justify-content:space-between">Live trades <span class="tk-status" data-tape-status></span></h2><div class="tk-tape" data-tape>- <div class="tk-empty" data-empty>Waiting for the next trade…</div>+ <div data-empty>${emptyStateHTML({+ compact: true,+ live: true,+ icon: '',+ title: 'Live trades will appear here',+ body: 'As people buy and sell $THREE, each trade streams in here in real time.',+ tip: 'Streaming live from the $THREE bonding curve via the Solana RPC trade feed.',+ })}</div></div></div></div>diff --git a/src/walk-companion-transitions.js b/src/walk-companion-transitions.jsindex f5bcff4e8..69c0e0e90 100644--- a/src/walk-companion-transitions.js+++ b/src/walk-companion-transitions.js@@ -392,6 +392,7 @@ function isEligibleLink(e) {let _clickHandler = null;let _getAvatarEl = null;+let _onNavStart = null;function onClickCapture(e) {if (!transitionsEnabled()) return; // honour the toggle; native nav proceeds@@ -400,7 +401,16 @@ function onClickCapture(e) {const url = isEligibleLink(e);if (!url) return;// Take ownership of the navigation so we can play the themed cover first.+ // Because we run in the capture phase *and* preventDefault, the SDK+ // companion's own _onLinkClick (task 32: wave + greet flag) would otherwise+ // bail on `e.defaultPrevented`. So we drive that behaviour explicitly via the+ // onNavStart hook — exactly once, no double-trigger.e.preventDefault();+ try {+ _onNavStart?.(url);+ } catch {+ /* greeting is a nicety — never let it block navigation */+ }runTransition(url, { x: e.clientX, y: e.clientY }, _getAvatarEl);}@@ -449,11 +459,15 @@ function syncToggleVisual(btn) {* element used by the camera-zoom-into-avatar preset.* @param {() => (HTMLElement|null)} [opts.getHostEl] returns the companion host* for injecting the settings toggle (defaults to getAvatarEl).+ * @param {(destUrl: URL) => void} [opts.onNavStart] called once when a themed+ * navigation begins, so the caller can reproduce the task-32 wave + greet+ * flag the SDK's own link handler would have run.* @returns {() => void} uninstall function.*/-export function installTransitions({ getAvatarEl, getHostEl } = {}) {+export function installTransitions({ getAvatarEl, getHostEl, onNavStart } = {}) {if (typeof document === 'undefined') return () => {};_getAvatarEl = typeof getAvatarEl === 'function' ? getAvatarEl : () => null;+ _onNavStart = typeof onNavStart === 'function' ? onNavStart : null;// Idempotent: a re-mount (playground return) shouldn't double-bind.if (!_clickHandler) {diff --git a/src/walk-companion.js b/src/walk-companion.jsindex a624b9434..c7644b569 100644--- a/src/walk-companion.js+++ b/src/walk-companion.js@@ -34,6 +34,29 @@ window.__walkCompanion = walk;// settings pill into the companion's existing control cluster. We read it lazily// off the live instance so this survives avatar swaps and playground round-trips.const companionHost = () => walk.instance?.host || null;-installTransitions({ getAvatarEl: companionHost, getHostEl: companionHost });++// When a themed transition takes over a link click it preventDefaults, which+// would suppress the SDK companion's own _onLinkClick (task 32: wave goodbye ++// set the sessionStorage greet flag the destination reads to wave hello). We+// reproduce that single behaviour here so it still fires exactly once.+const GREET_KEY = walk.config?.keys?.greet || 'walk:companion:greet';+function onTransitionNavStart() {+ try {+ walk.instance?.controller?.playWave();+ } catch {+ /* controller may not be ready — non-fatal */+ }+ try {+ sessionStorage.setItem(GREET_KEY, '1');+ } catch {+ /* private mode / disabled storage — non-fatal */+ }+}++installTransitions({+ getAvatarEl: companionHost,+ getHostEl: companionHost,+ onNavStart: onTransitionNavStart,+});walk.bootstrap();diff --git a/src/walk.js b/src/walk.jsindex 26b25c9b5..23a8f0250 100644--- a/src/walk.js+++ b/src/walk.js@@ -2148,6 +2148,11 @@ function tick() {// 6. Update minimapupdateMinimapFrame();+ // 7. Accumulate walk metrics (distance + session time) for the leaderboard+ // and per-creator analytics. Reads the resolved horizontal displacement+ // this frame; flushes on a timer + pagehide (see the walk-metrics block).+ accumulateWalkMetrics(dt);+renderer.render(scene, camera);requestAnimationFrame(tick);}@@ -2159,6 +2164,290 @@ function lerpAngle(a, b, t) {return a + diff * t;}+// ── Walk metrics (leaderboard + per-creator analytics) ─────────────────────+//+// Accumulates the two signals the leaderboard (task 39) and embed analytics+// (task 40) rank/aggregate on — horizontal distance travelled and time spent+// actually walking — straight from the controller's resolved per-frame+// displacement, and flushes a compact batch to POST /api/walk/metrics every+// ~60s plus once on pagehide (sendBeacon, so it survives the unload). The same+// batch carries any achievement thresholds crossed this session so the server+// awards each badge exactly once.+//+// Attribution: a signed-in session is resolved server-side from the request+// cookie; anonymous walkers are attributed by a stable, locally-persisted+// anonymous id so they still appear on the leaderboard. The avatar in use and+// the current environment ride along so a creator's analytics attribute walks+// to the right avatar and the "all environments" badge can be detected.+const WALK_METRICS_ENDPOINT = '/api/walk/metrics';+const WALK_ANON_KEY = 'twx_walk_anon';+const WALK_ACHIEVED_KEY = 'twx_walk_achieved';+const WALK_FLUSH_INTERVAL_MS = 60_000;++// Stable anonymous walker id — generated once and persisted, so an unauthenticated+// walker accrues a continuous track record across sessions/visits.+function getWalkAnonId() {+ try {+ let id = localStorage.getItem(WALK_ANON_KEY);+ if (!id) {+ id =+ typeof crypto !== 'undefined' && crypto.randomUUID+ ? `anon_${crypto.randomUUID()}`+ : `anon_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`;+ localStorage.setItem(WALK_ANON_KEY, id);+ }+ return id;+ } catch {+ // Private mode / storage disabled — fall back to a per-page id so the batch+ // is still attributable (just not continuous across reloads).+ if (!getWalkAnonId._mem) {+ getWalkAnonId._mem = `anon_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`;+ }+ return getWalkAnonId._mem;+ }+}++// The avatar whose walks we attribute. Seeded from ?avatar and kept in sync when+// the in-page picker swaps avatars (see the picker block, which calls+// setWalkMetricsAvatarId). Only forwarded when it is a real UUID — the default+// avatar has no id.+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+let walkMetricsAvatarId = (() => {+ const id = new URLSearchParams(location.search).get('avatar');+ return id && UUID_RE.test(id) ? id : null;+})();+function setWalkMetricsAvatarId(id) {+ walkMetricsAvatarId = id && UUID_RE.test(id) ? id : null;+}++// Per-session accumulators. `pending*` hold metrics earned since the last flush;+// `session*` hold lifetime-of-session totals used for achievement thresholds and+// the distinct-environment set.+const walkMetrics = {+ pendingDistance: 0, // metres since last flush+ pendingDuration: 0, // seconds of walking since last flush+ sessionDistance: 0, // metres this session (for the 1 km / 5 km badges)+ sessionEnvs: new Set(), // distinct environments walked in this session+ prevX: null,+ prevZ: null,+ counted: false, // whether this session has produced any metric yet (session count)+ sessionFlushed: false, // the single session count has been sent+};++// Locally-remembered unlocked achievements so a toast fires only on the crossing,+// not on every subsequent flush. The server is the source of truth for awarding;+// this just gates the UI + avoids re-sending.+function loadAchievedSet() {+ try {+ const raw = localStorage.getItem(WALK_ACHIEVED_KEY);+ return new Set(raw ? JSON.parse(raw) : []);+ } catch {+ return new Set();+ }+}+function persistAchievedSet(set) {+ try {+ localStorage.setItem(WALK_ACHIEVED_KEY, JSON.stringify([...set]));+ } catch {+ /* storage disabled — toasts still fire from the in-memory set */+ }+}+const walkAchieved = loadAchievedSet();+// Achievements crossed this session but not yet flushed to the server.+const walkPendingAchievements = new Set();++const WALK_ACHIEVEMENTS = [+ { code: 'distance_1km', label: '1 km walked', test: () => walkMetrics.sessionDistance >= 1000 },+ { code: 'distance_5km', label: '5 km walked', test: () => walkMetrics.sessionDistance >= 5000 },+ {+ code: 'all_environments',+ label: 'Walked in all 6 environments',+ test: () => walkMetrics.sessionEnvs.size >= 6,+ },+];++function checkWalkAchievements() {+ for (const a of WALK_ACHIEVEMENTS) {+ if (walkAchieved.has(a.code)) continue;+ if (!a.test()) continue;+ walkAchieved.add(a.code);+ walkPendingAchievements.add(a.code);+ persistAchievedSet(walkAchieved);+ showAchievementToast(a.label);+ }+}++// Lightweight, self-contained achievement toast. Uses design-token colours via+// inline custom-property reads so it stays on-brand without a dedicated stylesheet+// (the walk page is canvas-first and ships no toast component).+let walkToastHost = null;+function showAchievementToast(label) {+ try {+ if (!walkToastHost) {+ walkToastHost = document.createElement('div');+ walkToastHost.className = 'walk-toast-host';+ walkToastHost.setAttribute('aria-live', 'polite');+ walkToastHost.style.cssText =+ 'position:fixed;left:50%;top:calc(env(safe-area-inset-top,0) + 18px);transform:translateX(-50%);z-index:60;display:flex;flex-direction:column;gap:8px;pointer-events:none;';+ document.body.appendChild(walkToastHost);+ }+ const el = document.createElement('div');+ el.className = 'walk-toast';+ el.setAttribute('role', 'status');+ el.style.cssText =+ 'display:flex;align-items:center;gap:10px;padding:10px 16px;border-radius:999px;' ++ 'background:rgba(17,17,17,0.92);border:1px solid rgba(255,215,0,0.45);' ++ 'color:#fafafa;font:600 13px/1.2 var(--font-body,Inter,system-ui,sans-serif);' ++ 'box-shadow:0 8px 32px rgba(0,0,0,0.5);backdrop-filter:blur(16px);' ++ '-webkit-backdrop-filter:blur(16px);opacity:0;transform:translateY(-8px);' ++ 'transition:opacity .22s ease,transform .22s ease;';+ el.innerHTML = `<span aria-hidden="true" style="font-size:16px;line-height:1">🏆</span><span>Achievement unlocked · ${esc(label)}</span>`;+ walkToastHost.appendChild(el);+ requestAnimationFrame(() => {+ el.style.opacity = '1';+ el.style.transform = 'translateY(0)';+ });+ setTimeout(() => {+ el.style.opacity = '0';+ el.style.transform = 'translateY(-8px)';+ el.addEventListener('transitionend', () => el.remove(), { once: true });+ }, 4200);+ } catch {+ /* DOM unavailable — non-fatal; the unlock is still flushed to the server */+ }+}++// Called once per frame from the render loop. Integrates horizontal displacement+// into distance and accumulates walking time whenever the avatar is moving.+function accumulateWalkMetrics(dt) {+ if (!avatar) return;+ const x = avatarRig.position.x;+ const z = avatarRig.position.z;+ if (walkMetrics.prevX === null) {+ walkMetrics.prevX = x;+ walkMetrics.prevZ = z;+ return;+ }+ const dx = x - walkMetrics.prevX;+ const dz = z - walkMetrics.prevZ;+ walkMetrics.prevX = x;+ walkMetrics.prevZ = z;+ const stepped = Math.hypot(dx, dz);+ // Ignore teleports/world-swaps (a single frame moving > 5 m is not a walk) and+ // sub-millimetre jitter so a standing avatar accrues no phantom distance.+ const moving = currentMotion === 'walk' || currentMotion === 'run';+ if (stepped > 0.001 && stepped < 5 && moving) {+ walkMetrics.pendingDistance += stepped;+ walkMetrics.sessionDistance += stepped;+ walkMetrics.pendingDuration += dt;+ if (!walkMetrics.counted) walkMetrics.counted = true;+ if (currentEnvName) walkMetrics.sessionEnvs.add(currentEnvName);+ checkWalkAchievements();+ }+}++// Build the flush payload (or null if there's nothing to send). `final` marks the+// pagehide flush, which counts the session exactly once.+function buildWalkMetricsBatch({ final = false } = {}) {+ const distance = walkMetrics.pendingDistance;+ const duration = walkMetrics.pendingDuration;+ const achievements = [...walkPendingAchievements];+ // Count the session once, on the first flush that carries real movement.+ const session = walkMetrics.counted && !walkMetrics.sessionFlushed ? 1 : 0;+ if (distance <= 0 && duration <= 0 && !achievements.length && session === 0) return null;+ return {+ distanceMeters: Math.round(distance * 100) / 100,+ durationSec: Math.round(duration * 10) / 10,+ sessions: session,+ envId: currentEnvName || null,+ avatarId: walkMetricsAvatarId || undefined,+ anonId: getWalkAnonId(),+ achievements,+ _final: final,+ };+}++// Flush via fetch (keepalive) on the interval; via sendBeacon on pagehide so the+// last batch survives the unload. Resets the pending accumulators on dispatch.+function flushWalkMetrics({ beacon = false } = {}) {+ const batch = buildWalkMetricsBatch({ final: beacon });+ if (!batch) return;+ const final = batch._final;+ delete batch._final;+ const body = JSON.stringify(batch);++ let sent = false;+ if (beacon && typeof navigator !== 'undefined' && navigator.sendBeacon) {+ try {+ sent = navigator.sendBeacon(+ WALK_METRICS_ENDPOINT,+ new Blob([body], { type: 'application/json' }),+ );+ } catch {+ sent = false;+ }+ }+ if (!sent) {+ fetch(WALK_METRICS_ENDPOINT, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body,+ credentials: 'include',+ keepalive: true,+ }).catch(() => {+ /* metrics are best-effort; never surface a flush failure to the walker */+ });+ }++ // Reset pending counters now that the batch is dispatched. The session is+ // marked flushed once its single count has been sent.+ walkMetrics.pendingDistance = 0;+ walkMetrics.pendingDuration = 0;+ if (batch.sessions > 0) walkMetrics.sessionFlushed = true;+ walkPendingAchievements.clear();+}++// Fire a creator-defined conversion event for the embed analytics dashboard.+// Posts immediately (events are sparse, unlike the batched metric flush) and is+// attributed server-side to the current avatar + walker the same way metrics are.+// window.ThreeWalkAvatar.track('subscribe', { value: 9 })+function trackWalkEvent(eventName, opts = {}) {+ const name = typeof eventName === 'string' ? eventName.trim().slice(0, 64) : '';+ if (!name) return;+ const value = typeof opts.value === 'number' && Number.isFinite(opts.value) ? opts.value : undefined;+ const body = JSON.stringify({+ eventName: name,+ value,+ avatarId: walkMetricsAvatarId || undefined,+ anonId: getWalkAnonId(),+ });+ fetch(WALK_METRICS_ENDPOINT, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body,+ credentials: 'include',+ keepalive: true,+ }).catch(() => {+ /* event tracking is best-effort */+ });+}++function startWalkMetrics() {+ // Expose the embed SDK tracking API. Idempotent — merges onto any existing+ // global so a host page that defined a stub before load keeps working.+ window.ThreeWalkAvatar = Object.assign(window.ThreeWalkAvatar || {}, {+ track: trackWalkEvent,+ });+ setInterval(() => flushWalkMetrics({ beacon: false }), WALK_FLUSH_INTERVAL_MS);+ // pagehide is the reliable unload signal on mobile Safari + modern browsers;+ // visibilitychange→hidden covers tab-switch/app-background where pagehide may+ // not fire. Both route through the beacon path.+ window.addEventListener('pagehide', () => flushWalkMetrics({ beacon: true }));+ document.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'hidden') flushWalkMetrics({ beacon: true });+ });+}+// ── Multiplayer ───────────────────────────────────────────────────────────//// The server is best-effort. /walk works fully as a single-player page if@@ -3629,6 +3918,9 @@ loadAvatar().then(async () => {requestAnimationFrame(tick);startNet();+ // Begin the leaderboard / analytics metrics pipeline: per-frame distance ++ // time accumulate in the tick loop; this starts the 60s + pagehide flush.+ startWalkMetrics();// Stage the world: manifest → ?env / saved / default scene (terrain set// synchronously, scenery + HDR streamed in). Degrades to the default// ground/lighting if the manifest can't be reached.@@ -3750,6 +4042,7 @@ if (import.meta.env?.DEV) {.forEach((b) => b.classList.remove('is-active'));btn.classList.add('is-active');currentAvatarId = btn.dataset.avatarId || null;+ setWalkMetricsAvatarId(currentAvatarId);setStatus('Switching avatar...');try {diff --git a/tasks/site-overhaul/C-ux-newcomers/C06-designed-empty-states.md b/tasks/site-overhaul/C-ux-newcomers/C06-designed-empty-states.mddeleted file mode 100644index 4a2d26422..000000000--- a/tasks/site-overhaul/C-ux-newcomers/C06-designed-empty-states.md+++ /dev/null@@ -1,41 +0,0 @@-# C06 — Designed empty states site-wide--**Track:** UX for Newcomers · **Size:** M · **Priority:** P2 · **Depends on:** B04 (card/surface)--## Goal-Replace bare "No X yet" one-liners with designed empty states that explain *what the thing is,-why it's useful, and the next action* — everywhere a list can be empty.--## Why it matters-`CLAUDE.md`: "Empty state is designed and helpful (tells user what to do, not just 'no data')."-The audit found minimal empty states across dashboard agents/avatars, my-agents, pump dashboard,-club, three-live.--## Context-- Examples to fix: dashboard agents ("No agents yet — create your first one."), avatars, my-agents, pump dashboard ("No custom agents yet — click + New agent."), club tips, three-live ("Listening to the $THREE bonding curve…").-- A shared empty-state component (icon/illustration + title + one-line value + primary CTA + optional "learn more") keeps them consistent.--## Scope-- Build one shared empty-state component (Track B styled). Migrate the listed surfaces to it.-- Each empty state: says what populates here, why it matters in plain words, and a CTA to the action (e.g. "Agents are AI characters you can embed and chat with. [Create your first agent →] [What's an agent?]").-- The `three-live` empty state must be plain ("Live trades will appear here") with the technical detail tucked behind a tooltip.--## Definition of done-- Every listed surface shows a guided empty state via the shared component; no bare "No data" strings remain on user-facing lists.--## Verify-- With a fresh account (no agents/avatars), visit each surface — each explains and guides, not just states emptiness.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/site-overhaul/C-ux-newcomers/C06-designed-empty-states.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tests/api/three-holders-snapshot.test.js b/tests/api/three-holders-snapshot.test.jsindex a167f198e..124cded94 100644--- a/tests/api/three-holders-snapshot.test.js+++ b/tests/api/three-holders-snapshot.test.js@@ -71,4 +71,24 @@ describe('threeHolderBalances', () => {expect(map.get('walletLive')).toBe(7n);expect(fetchHolderBalances).toHaveBeenCalledTimes(1);});++ it('coalesces concurrent cold reads into ONE scan (stampede guard)', async () => {+ // Every sql call returns a null/cold snapshot so both callers miss cache.+ h.sql.mockResolvedValue([{ snapshot_at: null, holder_count: 0 }]);+ let resolveScan;+ fetchHolderBalances.mockImplementationOnce(+ () => new Promise((r) => { resolveScan = r; }),+ );+ // Fire two concurrent reads against the cold snapshot.+ const p1 = threeHolderBalances();+ const p2 = threeHolderBalances();+ // Let both reach the in-process single-flight before the scan resolves.+ await new Promise((r) => setTimeout(r, 10));+ resolveScan(new Map([['walletLive', 9n]]));+ const [m1, m2] = await Promise.all([p1, p2]);+ expect(m1.get('walletLive')).toBe(9n);+ expect(m2.get('walletLive')).toBe(9n);+ // The whole point: a burst of cold reads fires the expensive scan once.+ expect(fetchHolderBalances).toHaveBeenCalledTimes(1);+ });});diff --git a/tests/public/x402-modal-dom.test.js b/tests/public/x402-modal-dom.test.jsnew file mode 100644index 000000000..bcc0a5c67--- /dev/null+++ b/tests/public/x402-modal-dom.test.js@@ -0,0 +1,145 @@+// @vitest-environment jsdom+//+// DOM-level smoke tests for the drop-in payment modal (public/x402.js). Drives+// the real flow through window.X402.pay() with a stubbed 402 endpoint and a+// faked Phantom provider, asserting the trust + accessibility behavior added for+// the user influx: payee disclosure, trust copy, background inert, focus trap,+// ESC-to-cancel + focus restore, and the dedicated insufficient-funds state.+//+// Fixtures use $THREE (the only coin) as the Solana asset/payTo, per CLAUDE.md.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { pay } from '../../public/x402.js';++const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const PAYER = 'Payer1111111111111111111111111111111111111';++const solanaAccept = {+ scheme: 'exact',+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+ amount: '10000', // 0.01 USDC+ asset: THREE_MINT,+ payTo: THREE_MINT,+ maxTimeoutSeconds: 60,+ resource: 'https://three.ws/api/x402/demo',+ extra: { name: 'USDC', decimals: 6, feePayer: THREE_MINT },+};++function stub402(accepts = [solanaAccept]) {+ return {+ status: 402,+ headers: { get: () => null },+ json: async () => ({ accepts }),+ text: async () => '{"error":"payment required"}',+ };+}++// Let queued microtasks + the rAF the modal uses to focus settle.+function flush() {+ return new Promise((resolve) => setTimeout(resolve, 0));+}++describe('x402 payment modal — trust + a11y', () => {+ let background;++ beforeEach(() => {+ document.body.innerHTML = '';+ // A pre-existing page element the modal must make inert while open.+ background = document.createElement('button');+ background.id = 'bg-btn';+ background.textContent = 'background';+ document.body.appendChild(background);+ background.focus();++ // Fake Phantom so a Solana accept renders a usable wallet button.+ window.phantom = { solana: { isPhantom: true } };+ global.fetch = vi.fn(async () => stub402());+ global.requestAnimationFrame = (cb) => setTimeout(() => cb(Date.now()), 0);+ });++ afterEach(() => {+ delete window.phantom;+ vi.restoreAllMocks();+ });++ it('opens a dialog showing the payee and a trust statement', async () => {+ const p = pay({ endpoint: 'https://three.ws/api/x402/demo', merchant: 'Acme', action: 'Run' });+ p.catch(() => {}); // pending until cancel; swallow the eventual cancel rejection+ await flush();++ const dialog = document.querySelector('.x402-modal[role="dialog"]');+ expect(dialog).toBeTruthy();+ expect(dialog.getAttribute('aria-modal')).toBe('true');++ // Payee disclosure: truncated payTo with an explorer link.+ const payee = document.querySelector('.x402-payee');+ expect(payee?.textContent).toContain('Pays to');+ expect(payee.textContent).toContain(THREE_MINT.slice(0, 6));+ expect(document.querySelector('.x402-payee-addr')?.getAttribute('href')).toContain(THREE_MINT);++ // Trust statement present.+ expect(document.querySelector('.x402-trust')?.textContent || '').toMatch(/your own wallet/i);++ // Live region for screen-reader progress.+ expect(document.querySelector('[data-body]')?.getAttribute('aria-live')).toBe('polite');+ });++ it('makes the rest of the page inert while open and restores it on close', async () => {+ const p = pay({ endpoint: 'https://three.ws/api/x402/demo', merchant: 'Acme', action: 'Run' });+ p.catch(() => {});+ await flush();++ expect(background.hasAttribute('inert')).toBe(true);+ expect(background.getAttribute('aria-hidden')).toBe('true');++ // ESC cancels → promise rejects with code 'cancelled', page is restored.+ document.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape' }));+ await expect(p).rejects.toMatchObject({ code: 'cancelled' });+ await flush();+ expect(background.hasAttribute('inert')).toBe(false);+ expect(background.getAttribute('aria-hidden')).toBe(null);+ // Focus returns to the element that opened the modal.+ expect(document.activeElement).toBe(background);+ });++ it('lands initial focus on the primary action, not the close button', async () => {+ const p = pay({ endpoint: 'https://three.ws/api/x402/demo', merchant: 'Acme', action: 'Run' });+ p.catch(() => {});+ await flush();++ const active = document.activeElement;+ expect(active?.getAttribute('data-wallet')).toBe('phantom');+ document.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape' }));+ await p.catch(() => {});+ });++ it('shows a dedicated insufficient-funds state on a positive shortfall', async () => {+ // Phantom connects, but the wallet holds 0 USDC (empty token-accounts read).+ window.phantom.solana.connect = async () => ({ publicKey: { toString: () => PAYER } });+ window.phantom.solana.signTransaction = async () => {+ throw new Error('should not reach signing when underfunded');+ };+ global.fetch = vi.fn(async (url) => {+ if (String(url).includes('mainnet')) {+ return { ok: true, json: async () => ({ result: { value: [] } }) }; // 0 balance+ }+ return stub402();+ });++ const p = pay({ endpoint: 'https://three.ws/api/x402/demo', merchant: 'Acme', action: 'Run' });+ p.catch(() => {});+ await flush();+ // Click the Phantom wallet button to start the Solana flow.+ document.querySelector('[data-wallet="phantom"]').click();+ await flush();+ await flush();++ expect(document.querySelector('.x402-insuff-title')?.textContent).toMatch(/not enough/i);+ expect(document.body.textContent).toContain('short by');+ // A retry control exists; nothing was signed.+ expect(document.querySelector('[data-retry]')).toBeTruthy();++ document.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape' }));+ await p.catch(() => {});+ });+});diff --git a/tests/public/x402-pay-core.test.js b/tests/public/x402-pay-core.test.jsindex 062f51e13..40efe751e 100644--- a/tests/public/x402-pay-core.test.js+++ b/tests/public/x402-pay-core.test.js@@ -24,6 +24,10 @@ import {friendlyError,isMobileBrowser,walletDeeplink,+ formatTokenAmount,+ insufficientFundsError,+ erc20BalanceOfCalldata,+ assertSufficientBalance,} from '../../public/x402-pay-core.js';const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';@@ -264,3 +268,59 @@ describe('walletDeeplink', () => {expect(walletDeeplink('phantom', '')).toBe(null);});});++describe('pre-flight balance guard', () => {+ const sol = {+ scheme: 'exact',+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+ asset: THREE_MINT,+ amount: '10000', // 0.01 at 6 decimals+ payTo: THREE_MINT,+ extra: { name: 'USDC', decimals: 6 },+ };++ it('formats atomic amounts BigInt-safely', () => {+ expect(formatTokenAmount('1000', 6)).toBe('0.001');+ expect(formatTokenAmount('10000', 6)).toBe('0.01');+ expect(formatTokenAmount('1500000', 6)).toBe('1.5');+ expect(formatTokenAmount('0', 6)).toBe('0');+ // Beyond Number.MAX_SAFE_INTEGER — must not lose precision.+ expect(formatTokenAmount('123456789012345678', 6)).toBe('123456789012.345678');+ });++ it('builds a structured insufficient-funds error with a shortfall', () => {+ const err = insufficientFundsError({ required: '10000', balance: '2500', accept: sol });+ expect(err.code).toBe('insufficient_funds');+ expect(err.insufficient.requiredFormatted).toBe('0.01');+ expect(err.insufficient.balanceFormatted).toBe('0.0025');+ expect(err.insufficient.shortfallFormatted).toBe('0.0075');+ expect(err.insufficient.symbol).toBe('USDC');+ });++ it('encodes ERC-20 balanceOf calldata (selector + padded address)', () => {+ const data = erc20BalanceOfCalldata('0x00000000000000000000000000000000000000Ab');+ expect(data.startsWith('0x70a08231')).toBe(true);+ expect(data).toHaveLength(10 + 64);+ expect(data.endsWith('ab')).toBe(true);+ });++ it('never blocks when the balance read is inconclusive (fail-open)', async () => {+ // Solana reader hits the network; force it to return null via an unreachable RPC.+ await expect(+ assertSufficientBalance({ accept: sol, owner: THREE_MINT, rpcUrl: 'http://127.0.0.1:0' }),+ ).resolves.toBeNull();+ });++ it('throws on a positively-read EVM shortfall, passes when covered', async () => {+ const evm = { ...sol, network: 'eip155:8453', asset: SYNTH_EVM };+ const providerWith = (atomicHex) => ({ request: async () => atomicHex });+ // balance 0x0 (= 0) < required 10000 → throws+ await expect(+ assertSufficientBalance({ accept: evm, owner: SYNTH_EVM, provider: providerWith('0x0') }),+ ).rejects.toMatchObject({ code: 'insufficient_funds' });+ // balance 0x4e20 (= 20000) >= required 10000 → ok+ await expect(+ assertSufficientBalance({ accept: evm, owner: SYNTH_EVM, provider: providerWith('0x4e20') }),+ ).resolves.not.toThrow?.();+ });+});diff --git a/vercel.json b/vercel.jsonindex 7af1c11b9..b77d24820 100644--- a/vercel.json+++ b/vercel.json@@ -844,6 +844,22 @@},"dest": "/walk-embed.html"},+ {+ "src": "/walk/app/?",+ "dest": "/walk-embed.html"+ },+ {+ "src": "/walk/?",+ "dest": "/walk-landing.html"+ },+ {+ "src": "/walk-leaderboard/?",+ "dest": "/walk-leaderboard.html"+ },+ {+ "src": "/walk-analytics/?",+ "dest": "/walk-analytics.html"+ },{"src": "/pose/?","dest": "/pose.html"@@ -2442,6 +2458,10 @@"src": "/u/([^/]+)","dest": "/profile.html"},+ {+ "src": "/feed",+ "dest": "/feed.html"+ },{"src": "/avatars/([^/]+\\.glb)","headers": {@@ -2524,10 +2544,22 @@"src": "/threews/claim","dest": "/threews-claim.html"},+ {+ "src": "/api/users/me/feed",+ "dest": "/api/users/me/feed"+ },{"src": "/api/users/([^/]+)/avatar","dest": "/api/users/[username]/avatar?username=$1"},+ {+ "src": "/api/users/([^/]+)/follow",+ "dest": "/api/users/[username]/follow?username=$1"+ },+ {+ "src": "/api/users/([^/]+)/follows",+ "dest": "/api/users/[username]/follows?username=$1"+ },{"src": "/api/users/([^/]+)","dest": "/api/users/[username]?username=$1"diff --git a/vite.config.js b/vite.config.jsindex 37240fbd5..1bdf477d8 100644--- a/vite.config.js+++ b/vite.config.js@@ -375,6 +375,7 @@ const appConfig = {'launch-week': resolve(__dirname, 'pages/three-ws-launch-week.html'),community: resolve(__dirname, 'pages/community.html'),profile: resolve(__dirname, 'pages/profile.html'),+ feed: resolve(__dirname, 'pages/feed.html'),'threews-claim': resolve(__dirname, 'pages/threews-claim.html'),'events-build-3d-agents-live': resolve(__dirname, 'pages/events/build-3d-agents-live.html'),'avatar-page': resolve(__dirname, 'pages/avatar-page.html'),@@ -397,6 +398,9 @@ const appConfig = {communities: resolve(__dirname, 'pages/communities.html'),clash: resolve(__dirname, 'pages/clash.html'),'walk-embed': resolve(__dirname, 'pages/walk-embed.html'),+ 'walk-landing': resolve(__dirname, 'pages/walk-landing.html'),+ 'walk-leaderboard': resolve(__dirname, 'pages/walk-leaderboard.html'),+ 'walk-analytics': resolve(__dirname, 'pages/walk-analytics.html'),city: resolve(__dirname, 'pages/city.html'),play: resolve(__dirname, 'pages/play.html'),'play-agent-wallet': resolve(__dirname, 'pages/play/agent-wallet.html'),@@ -805,6 +809,14 @@ support: resolve(__dirname, 'pages/support.html'),'/smart-money/': resolve(root, 'pages/smart-money.html'),'/walk-embed': resolve(root, 'pages/walk-embed.html'),'/walk-embed/': resolve(root, 'pages/walk-embed.html'),+ '/walk': resolve(root, 'pages/walk-landing.html'),+ '/walk/': resolve(root, 'pages/walk-landing.html'),+ '/walk/app': resolve(root, 'pages/walk-embed.html'),+ '/walk/app/': resolve(root, 'pages/walk-embed.html'),+ '/walk-leaderboard': resolve(root, 'pages/walk-leaderboard.html'),+ '/walk-leaderboard/': resolve(root, 'pages/walk-leaderboard.html'),+ '/walk-analytics': resolve(root, 'pages/walk-analytics.html'),+ '/walk-analytics/': resolve(root, 'pages/walk-analytics.html'),'/demo': resolve(root, 'pages/demo-economy.html'),'/demo/': resolve(root, 'pages/demo-economy.html'),'/live': resolve(root, 'pages/live.html'),@@ -1147,6 +1159,11 @@ support: resolve(__dirname, 'pages/support.html'),// /@<handle> → public live profile pageelse if (!filePath && /^\/@[a-z0-9_-]{3,30}\/?$/i.test(path))filePath = resolve(root, 'pages/handle.html');+ else if (+ !filePath &&+ /^\/u\/(?:0x[0-9a-fA-F]{40}|[a-z0-9_-]{3,30})\/?$/i.test(path)+ )+ filePath = resolve(root, 'pages/profile.html');// /a/<chainId>/<agentId> or /a/<chainId>/<registry>/<agentId>else if (!filePath && /^\/a\/[^/]+(?:\/[^/]+){1,2}\/?$/.test(path))filePath = resolve(root, 'pages/app.html');diff --git a/x402-payment-modal/CHANGELOG.md b/x402-payment-modal/CHANGELOG.mdindex c32c67ea1..bd1b7e985 100644--- a/x402-payment-modal/CHANGELOG.md+++ b/x402-payment-modal/CHANGELOG.md@@ -3,6 +3,51 @@All notable changes to `@three-ws/x402-payment-modal` are documented here. Thisproject adheres to [Semantic Versioning](https://semver.org).+## 1.2.0++Hardening pass for scale and a UX/accessibility overhaul.++### Fixed++- **$THREE (and any Token-2022 mint) now settles.** `prepareSolanaCheckout`+ hardcoded the legacy SPL Token program, so building a $THREE payment threw+ `TokenInvalidAccountOwnerError`. The server now detects each mint's owning+ program (legacy vs Token-2022) and derives ATAs, the idempotent-create, and+ `transferChecked` against the right one.++### Added — reliability & scale++- **RPC failover** — `prepareSolanaCheckout` / `handleCheckout` accept `rpcUrls`+ (and `devnetRpcUrls`); each is tried in order on a transient RPC error.+ Connections are reused per URL, and unset RPC now warns (the public RPC is a+ load footgun).+- **Faster, cheaper prepare** — the independent RPC reads (decimals, recipient+ ATA existence, blockhash) run in parallel; USDC/THREE/wSOL decimals + program+ are short-circuited; recipient-ATA existence and mint metadata are cached+ (LRU-bounded). Cluster-scoped caches survive RPC failover.+- **Resilient crypto-helper loading** — the on-demand `@solana/web3.js` /+ `@noble/hashes` import now falls back across multiple independent CDNs with a+ per-attempt timeout, and is pre-warmed when the modal opens. A single CDN+ outage no longer breaks Solana payments. Set `configure({ esm })` to self-host.+- **Idempotency key** — one key per payment, reused across every retry and "Try+ again", sent as `Idempotency-Key` so a re-sent payment settles at most once.+- Unexpected checkout failures are now logged (root cause) instead of collapsing+ silently into a generic 502; pass `options.logger` to route them.++### Added — UX, UI & accessibility++- **Design-token theming** — the full palette is exposed as `--x402-*` CSS custom+ properties. `configure({ theme: 'light'|'dark'|'auto', cssVars, brand: { logo } })`+ forces a color scheme, brand-matches tokens at runtime, and shows a header logo.+- **Accessibility** — focus trap + focus restore, `aria-live` step announcements,+ `:focus-visible` rings, `prefers-reduced-motion` support, and WCAG-AA contrast.+- **Polish** — crisp inline SVG icons (close, lock, wallet, success check),+ an animated success receipt, step cross-fade, shimmer skeletons during+ discovery, a mobile bottom-sheet layout with safe-area insets, humanized error+ copy (no internal step ids), an install-a-wallet hint when none is detected,+ a "you authorize exactly X — nothing more" trust line, and prose rendering for+ string results.+## 1.1.0### Addeddiff --git a/x402-payment-modal/package.json b/x402-payment-modal/package.jsonindex 82fe3e120..a460efb6f 100644--- a/x402-payment-modal/package.json+++ b/x402-payment-modal/package.json@@ -1,6 +1,6 @@{"name": "@three-ws/x402-payment-modal",- "version": "1.1.0",+ "version": "1.2.0","description": "Drop-in x402 payment modal for any paid HTTP endpoint. One ES module, zero runtime dependencies — handles wallet connect (Phantom/Solana + EVM via EIP-3009), the 402 → sign → settle flow, SIWX re-entry, client-side spending caps, and a receipt. Vanilla JS, no bundler required.","type": "module","main": "./src/index.js",diff --git a/x402-payment-modal/src/index.js b/x402-payment-modal/src/index.jsindex e145c1ff1..92d50217c 100644--- a/x402-payment-modal/src/index.js+++ b/x402-payment-modal/src/index.js@@ -36,7 +36,7 @@// is configurable via `configure({...})` or `data-*` attributes on the script// tag — see CONFIG / configure() below and docs/api-reference.md.-const VERSION = '1.1.0';+const VERSION = '1.2.0';// ─────────────────────────────────────────────────────────── configuration ───// All host-specific knobs live here so the modal runs unchanged on any site.@@ -58,6 +58,10 @@ const CONFIG = {// ERC-8021 builder-code self-attribution echoed back when the 402 challenge// declares a builder-code extension. Set either field to '' to disable it.builderCode: { wallet: '3d_agent', service: '3d_agent_modal' },+ // Color scheme: 'auto' follows the OS; 'light'/'dark' force it.+ theme: 'auto',+ // Optional flat map of --x402-* design tokens for brand-matching at runtime.+ cssVars: null,// Primary CDN URLs for the crypto helpers loaded on demand (only when a Solana// or EVM sign-in payment is actually attempted). Each is tried first, then the// loader falls back across additional independent CDNs (see ESM_FALLBACKS) so a@@ -94,12 +98,19 @@ const ESM_IMPORT_TIMEOUT_MS = 12_000;*/export function configure(opts = {}) {if (!opts || typeof opts !== 'object') return CONFIG;- for (const key of ['checkoutOrigin', 'checkoutPath', 'footerNote']) {+ // theme: 'light' | 'dark' | 'auto' — force the modal's color scheme regardless+ // of the OS preference (auto = follow the OS, the default).+ for (const key of ['checkoutOrigin', 'checkoutPath', 'footerNote', 'theme']) {if (opts[key] !== undefined) CONFIG[key] = opts[key];}if (opts.brand && typeof opts.brand === 'object') Object.assign(CONFIG.brand, opts.brand);if (opts.builderCode && typeof opts.builderCode === 'object') Object.assign(CONFIG.builderCode, opts.builderCode);if (opts.esm && typeof opts.esm === 'object') Object.assign(CONFIG.esm, opts.esm);+ // cssVars: a flat map of x402 design tokens to brand-match without CSS files,+ // e.g. configure({ cssVars: { '--x402-accent': '#ff5c00', '--x402-radius': '8px' } }).+ if (opts.cssVars && typeof opts.cssVars === 'object') {+ CONFIG.cssVars = { ...(CONFIG.cssVars || {}), ...opts.cssVars };+ }return CONFIG;}@@ -889,6 +900,26 @@ const STYLES = `}`;+// Crisp inline SVG iconography — emoji/letter placeholders render differently+// per-OS and read as cheap; these inherit currentColor and stay sharp at any DPI.+const ICONS = {+ close: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>',+ lock: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>',+ check: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 13l4 4L19 7"/></svg>',+ shield: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3l7 3v6c0 4.5-3 7.4-7 9-4-1.6-7-4.5-7-9V6z"/><path d="M9 12l2 2 4-4"/></svg>',+ phantom: '<svg viewBox="0 0 24 24" aria-hidden="true"><rect width="24" height="24" rx="6" fill="#ab9ff2"/><path fill="#fff" d="M19 12.4c0 3.8-3.1 6.8-7 6.8-.6 0-1-.6-.7-1.1.2-.4 0-.9-.4-1.1-.4-.2-1 0-1.3.4-.5.7-1.3 1.1-2.2 1.1H6.7c-1.2 0-2.2-1-2.2-2.2v-1.7c0-4.1 3.4-7.4 7.5-7.4h-.1c3.9 0 7.1 2.6 7.1 5.9z"/><circle cx="9.4" cy="12.4" r="1" fill="#534bb1"/><circle cx="12.6" cy="12.4" r="1" fill="#534bb1"/></svg>',+ wallet: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="6" width="18" height="13" rx="2.5"/><path d="M3 10h18"/><circle cx="16.5" cy="14" r="1.3" fill="currentColor" stroke="none"/></svg>',+};++// Human-readable headings for the failure step shown in the error box. Never+// surface the internal step id ("authorize", "verify") to a buyer.+const STEP_LABELS = {+ discover: "Couldn't confirm the price",+ connect: "Couldn't connect your wallet",+ authorize: "Payment couldn't be authorized",+ verify: "Payment couldn't be completed",+};+function injectStyles() {if (document.getElementById(STYLE_ID)) return;const el = document.createElement('style');@@ -923,22 +954,40 @@ class CheckoutModal {injectStyles();const overlay = document.createElement('div');overlay.className = 'x402-overlay';+ // Forced color scheme (configure({ theme })) overrides the OS preference.+ if (CONFIG.theme === 'dark') overlay.classList.add('x402-theme-dark');+ else if (CONFIG.theme === 'light') overlay.classList.add('x402-theme-light');+ // Brand design-token overrides applied inline so they win without !important.+ if (CONFIG.cssVars && typeof CONFIG.cssVars === 'object') {+ for (const [k, v] of Object.entries(CONFIG.cssVars)) {+ if (/^--x402-[a-z0-9-]+$/i.test(k)) overlay.style.setProperty(k, String(v));+ }+ }+ const logo = CONFIG.brand?.logo+ ? `<img class="x402-brand-logo" src="${escapeHtml(CONFIG.brand.logo)}" alt="" />`+ : '';overlay.innerHTML = `- <div class="x402-modal" role="dialog" aria-modal="true" aria-label="x402 payment">+ <div class="x402-modal" role="dialog" aria-modal="true" aria-labelledby="x402-act" aria-describedby="x402-price"><div class="x402-head"><div class="x402-merchant">- <div class="x402-name" data-merchant>${escapeHtml(this.opts.merchant || 'Payment')}</div>- <div class="x402-action" data-action>${escapeHtml(this.opts.action || 'Pay-per-call')}</div>+ ${logo}+ <div class="x402-merchant-text">+ <div class="x402-name" data-merchant>${escapeHtml(this.opts.merchant || 'Payment')}</div>+ <div class="x402-action" id="x402-act" data-action>${escapeHtml(this.opts.action || 'Pay-per-call')}</div>+ </div></div>- <button class="x402-close" data-close aria-label="Close">✕</button>+ <button class="x402-close" data-close aria-label="Close payment">${ICONS.close}</button></div><div class="x402-price-row">- <div class="x402-price" data-price>—<span class="x402-currency"> USDC</span></div>+ <div class="x402-price-main">+ <div class="x402-price" id="x402-price" data-price>—<span class="x402-currency"> USDC</span></div>+ <div class="x402-price-sub" data-price-sub></div>+ </div><div class="x402-network" data-network>resolving…</div></div>- <div class="x402-body" data-body></div>+ <div class="x402-body" data-body aria-live="polite"></div><div class="x402-foot">- <span class="x402-secure">${escapeHtml(CONFIG.footerNote)}</span>+ <span class="x402-secure">${ICONS.lock}${escapeHtml(CONFIG.footerNote)}</span>${CONFIG.brand?.name ? `<a href="${escapeHtml(CONFIG.brand.url || '#')}" target="_blank" rel="noopener">Powered by ${escapeHtml(CONFIG.brand.name)}</a>` : ''}</div></div>@@ -947,24 +996,57 @@ class CheckoutModal {this.overlay = overlay;this.bodyEl = overlay.querySelector('[data-body]');this.priceEl = overlay.querySelector('[data-price]');+ this.priceSubEl = overlay.querySelector('[data-price-sub]');this.networkEl = overlay.querySelector('[data-network]');overlay.querySelector('[data-close]').addEventListener('click', () => this.close('cancelled'));overlay.addEventListener('click', (e) => { if (e.target === overlay) this.close('cancelled'); });- this.onKey = (e) => { if (e.key === 'Escape') this.close('cancelled'); };+ // Remember what had focus so we can restore it on close (a11y).+ this.previouslyFocused = typeof document !== 'undefined' ? document.activeElement : null;+ this.onKey = (e) => {+ if (e.key === 'Escape') { this.close('cancelled'); return; }+ if (e.key === 'Tab') this.trapTab(e);+ };document.addEventListener('keydown', this.onKey);- requestAnimationFrame(() => overlay.classList.add('x402-open'));+ requestAnimationFrame(() => {+ overlay.classList.add('x402-open');+ this.focusFirst();+ });return new Promise((resolve, reject) => {this.resolve = resolve;this.reject = reject;});}+ // All visible, enabled, focusable elements inside the modal, in DOM order.+ focusables() {+ if (!this.overlay) return [];+ const sel = 'button:not([disabled]), [href], input:not([disabled]), select, textarea, [tabindex]:not([tabindex="-1"])';+ return Array.from(this.overlay.querySelectorAll(sel)).filter((el) => el.offsetParent !== null);+ }++ focusFirst() {+ const list = this.focusables();+ (list.find((el) => !el.hasAttribute('data-close')) || list[0])?.focus?.();+ }++ // Keep Tab within the dialog — a modal must not leak focus to the page behind.+ trapTab(e) {+ const list = this.focusables();+ if (!list.length) return;+ const first = list[0];+ const last = list[list.length - 1];+ if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }+ else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }+ }+close(reason) {if (this.disposed) return;this.disposed = true;document.removeEventListener('keydown', this.onKey);this.overlay.classList.remove('x402-open');setTimeout(() => this.overlay.remove(), 180);+ // Restore focus to whatever triggered the modal.+ this.previouslyFocused?.focus?.();if (reason === 'cancelled' && this.reject) {const err = new Error('cancelled');err.code = 'cancelled';@@ -1063,7 +1145,7 @@ class CheckoutModal {: networkLabel(solanaAccept.network, solanaAccept);buttons.push(`<button class="x402-wallet-btn" data-wallet="phantom" ${phantomDetected ? '' : 'disabled'}>- <div class="x402-wallet-icon x402-phantom">P</div>+ <div class="x402-wallet-icon">${ICONS.phantom}</div><span class="x402-wallet-name">${phantomDetected ? 'Phantom' : 'Phantom (not detected)'}</span><span class="x402-wallet-meta" data-sol-meta>${escapeHtml(solMeta)}</span></button>@@ -1072,21 +1154,35 @@ class CheckoutModal {if (evmAccept) {buttons.push(`<button class="x402-wallet-btn" data-wallet="evm" ${evmDetected ? '' : 'disabled'}>- <div class="x402-wallet-icon x402-metamask">M</div>+ <div class="x402-wallet-icon">${ICONS.wallet}</div><span class="x402-wallet-name">${evmDetected ? 'Browser wallet' : 'No EVM wallet detected'}</span><span class="x402-wallet-meta">${networkLabel(evmAccept.network, evmAccept)}</span></button>`);}+ // When nothing is installed, don't dead-end — point users to a wallet.+ const installHelp = (!phantomDetected && !evmDetected)+ ? `<div class="x402-wallet-install">No wallet detected — install+ ${solanaAccept ? `<a href="https://phantom.app/download" target="_blank" rel="noopener">Phantom</a>` : ''}${solanaAccept && evmAccept ? ' or ' : ''}${evmAccept ? `<a href="https://metamask.io/download" target="_blank" rel="noopener">MetaMask</a>` : ''}+ to continue.</div>`+ : '';const fallbackBox = this.siwxFallbackNotice? `<div class="x402-siwx-fallback">${escapeHtml(this.siwxFallbackNotice)}</div>`: '';+ // True for the exact scheme: the signed authorization can only move the+ // stated amount to the stated recipient — a strong, honest trust signal.+ const trustInfo = tokenInfo(this.accept);+ const trustAmt = formatAmount(this.accept.amount, trustInfo.decimals);+ const trustLine = `<div class="x402-trust">${ICONS.shield}<span>You authorize exactly ${escapeHtml(trustAmt)} ${escapeHtml(trustInfo.symbol)} — nothing more can be charged.</span></div>`;this.bodyEl.innerHTML = `${this.renderSteps('connect', { discover: 'done' })}${fallbackBox}${tokenChooser}<div class="x402-wallet-buttons">${buttons.join('')}</div>+ ${installHelp}+ ${(phantomDetected || evmDetected) ? trustLine : ''}`;+ requestAnimationFrame(() => this.focusFirst());const onClick = (e) => {const btn = e.target.closest('[data-wallet]');if (!btn || btn.disabled) return;@@ -1168,10 +1264,15 @@ class CheckoutModal {[stepId]: 'error',[`${stepId}_meta`]: 'failed',})}- <div class="x402-error-box"><strong>${escapeHtml(stepId)}:</strong> ${escapeHtml(message)}</div>+ <div class="x402-error-box">+ <div class="x402-error-title">${escapeHtml(STEP_LABELS[stepId] || 'Something went wrong')}</div>+ <div class="x402-error-detail">${escapeHtml(message)}</div>+ </div><button class="x402-pay-btn" data-retry>Try again</button>`;- this.bodyEl.querySelector('[data-retry]').addEventListener('click', () => this.start());+ const retry = this.bodyEl.querySelector('[data-retry]');+ retry.addEventListener('click', () => this.start());+ requestAnimationFrame(() => retry.focus());}renderDone({ result, payment, siwx }) {@@ -1181,7 +1282,8 @@ class CheckoutModal {const addrShort = siwx.address ? `${siwx.address.slice(0, 8)}…${siwx.address.slice(-6)}` : '—';receiptHtml = `<div class="x402-receipt">- <div class="x402-receipt-title">Welcome back!</div>+ <div class="x402-receipt-check">${ICONS.check}</div>+ <div class="x402-receipt-title">Welcome back</div><div class="x402-receipt-row"><span class="x402-k">network</span><span class="x402-v">${escapeHtml(networkLabel(siwx.network) || siwx.network || '—')}</span>@@ -1201,7 +1303,8 @@ class CheckoutModal {const txShort = payment?.transaction ? `${payment.transaction.slice(0, 8)}…${payment.transaction.slice(-6)}` : '—';receiptHtml = `<div class="x402-receipt">- <div class="x402-receipt-title">Payment confirmed!</div>+ <div class="x402-receipt-check">${ICONS.check}</div>+ <div class="x402-receipt-title">Payment confirmed</div><div class="x402-receipt-row"><span class="x402-k">network</span><span class="x402-v">${escapeHtml(networkLabel(payment?.network) || '—')}</span>@@ -1220,21 +1323,24 @@ class CheckoutModal {</div>`;}+ // A string result is human-readable content (a summary, an answer) — show it+ // as prose, not in a monospace JSON box. Objects stay as formatted JSON.+ const isProse = typeof result === 'string';this.bodyEl.innerHTML = `${receiptHtml}- <div class="x402-result">${escapeHtml(resultStr).slice(0, 4000)}</div>+ <div class="x402-result${isProse ? ' x402-prose' : ''}">${escapeHtml(resultStr).slice(0, 4000)}</div><button class="x402-pay-btn" data-done>Done</button>`;- this.bodyEl.querySelector('[data-done]').addEventListener('click', () => {- this.disposed = true;- document.removeEventListener('keydown', this.onKey);- this.overlay.classList.remove('x402-open');- setTimeout(() => this.overlay.remove(), 180);- });+ const doneBtn = this.bodyEl.querySelector('[data-done]');+ doneBtn.addEventListener('click', () => this.close('done'));+ requestAnimationFrame(() => doneBtn.focus());}async start() {this.bodyEl.innerHTML = this.renderSteps('discover');+ // Shimmer skeletons for the price/network while we fetch the challenge.+ this.priceEl.innerHTML = '<span class="x402-skeleton" style="display:inline-block;width:92px;height:26px;vertical-align:middle"></span>';+ this.networkEl.innerHTML = '<span class="x402-skeleton" style="display:inline-block;width:58px;height:11px;border-radius:99px"></span>';// Pre-warm the Solana web3 import now (while the user reads the modal and we// fetch the challenge) so a slow CDN doesn't stall at sign time. Best-effort.loadSolanaWeb3().catch(() => {});@@ -1433,6 +1539,9 @@ class CheckoutModal {this.renderProgress('verify', {text: attempt ? 'Retrying after upstream throttle…' : 'Calling merchant endpoint…',});+ // One idempotency key for this payment's whole lifetime (all retries and any+ // "Try again") so a re-sent X-PAYMENT settles at most once — no double charge.+ if (!this.idempotencyKey) this.idempotencyKey = `x402-${randomHex(16)}`;try {const res = await fetch(this.opts.endpoint, {method: this.opts.method || 'GET',@@ -1440,6 +1549,8 @@ class CheckoutModal {...(this.opts.headers || {}),...(this.opts.body && !this.opts.headers?.['content-type'] ? { 'content-type': 'application/json' } : {}),'X-PAYMENT': xPayment,+ 'Idempotency-Key': this.idempotencyKey,+ 'X-Idempotency-Key': this.idempotencyKey,},body: this.opts.body ? (typeof this.opts.body === 'string' ? this.opts.body : JSON.stringify(this.opts.body)) : undefined,});diff --git a/x402-payment-modal/types/index.d.ts b/x402-payment-modal/types/index.d.tsindex db52ab23e..dfdaa472a 100644--- a/x402-payment-modal/types/index.d.ts+++ b/x402-payment-modal/types/index.d.ts@@ -58,12 +58,17 @@ export interface PayResult {};}-/** Branding shown in the modal footer. */+/** Branding shown in the modal header/footer. */export interface BrandConfig {name?: string;url?: string;+ /** Logo shown in the modal header (URL). */+ logo?: string;}+/** Forced color scheme. `auto` (default) follows the OS preference. */+export type X402Theme = 'auto' | 'light' | 'dark';+/** ERC-8021 builder-code self-attribution echoed when the 402 challenge declares one. */export interface BuilderCodeConfig {wallet?: string;@@ -84,6 +89,10 @@ export interface X402Config {footerNote?: string;builderCode?: BuilderCodeConfig;esm?: EsmConfig;+ /** Force the modal's color scheme. Default `auto` (follow the OS). */+ theme?: X402Theme;+ /** Flat map of `--x402-*` design tokens to brand-match at runtime, e.g. `{ '--x402-accent': '#ff5c00' }`. */+ cssVars?: Record<string, string> | null;}/**