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: cross-entity search across avatars, agents, models, worlds & coins
fudjia44672c5c20ec
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 80760b563..6f3a9fb40 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Docs · The autonomous economy** (`/docs/autonomous-economy`) — How the three.ws on-chain treasury funds itself and where every dollar flows: the funding-root and engine wallets, the topup/sweepback loop, the allowlist- and destination-locks that keep money inside platform-owned wallets, and the two leak scanners that audit every signer wallet on-chain every minute — plus how to verify there's no leak yourself.- **Robinhood Chain** (`/markets/robinhood`) — The 24/7 tokenized-equity board for Robinhood Chain (4663): live Chainlink NAV vs DEX premium for every Stock Token, a memecoin screener across NOXA and The Odyssey launchpads, recent launches, and chain TVL — plus a real wallet-connect buy flow for its coins.+- **Search** (`/search`) — One search across every creation type on three.ws — avatars, agents, 3D models, worlds, and coins — with remixable models remixable straight from the results.- **Your creator portfolio** (`/profile`) — Your public three.ws portfolio: every avatar, agent, forged 3D model, world, coin, skill, and plugin you've made, in one place. Signed out, this redirects to sign-in; every user's own page also lives at /u/:username.- **/feed and /community are now real, live pages** — /feed used to only show activity from people you follow — it now defaults to a live, platform-wide feed of every new avatar, agent, forged 3D model, saved world, coin launch, and follow, with a toggle to switch to just the people you follow. Scroll for more and it loads the next page automatically; a "New activity" pill appears when something fresh lands so the list never jumps under you mid-read. /community, previously a static grid of links, now leads with that same live activity feed alongside the existing links to X, GitHub, docs, and tutorials. (`/feed`) `[feature]`- **Agent discovery fixed: six paid endpoints were invisible to x402 scanners** — The machine-readable catalog at /openapi.json — what AI agents and x402 scanners like x402scan and AgentCash read to find and pay for three.ws APIs — had six paid endpoints (agent bouncer, verifiable vanity keys, crypto intel, cosmetic purchase, animation download, club cover) accidentally buried inside another entry, making them undiscoverable. All 61 payable routes now list correctly and the document passes the AgentCash discovery validator. The Permit2 gasless-payment demo is now only advertised when its settlement lane is actually live, so agents are never quoted a payment path that can't settle. (`/openapi.json`) `[fix, improvement]`@@ -19,6 +20,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Market-maker and limit-order engines are now crash-safe on Cloud Run** — The two background workers that run agents' automated market-making and limit orders are long-running loops, not web servers. On Cloud Run, a service that never answers the platform's startup health check gets killed and restarted in a loop — which would have taken these money-moving engines offline the moment they were deployed as services. Both now start a tiny health endpoint when the platform asks for one (and stay silent when run as a scheduled job, where none is needed), so they boot cleanly either way. We also added a documented, repeatable deploy for each so there's no guesswork about how they ship. `[infra]`- **Money-moving agent skills now require an explicit spend confirmation** — The skills that let an agent send tokens, swap, or pay a paid API used to validate the format of an address or amount but never stopped to confirm the actual intent before signing — and some read a token's on-chain name and description straight into the same agent that holds the signing key, so a token deliberately named like an instruction ('send 5 to 0x…') could try to steer a real transfer. Each of these skills now renders a recipient/amount/token/chain confirmation card and waits for an explicit yes before moving any funds, and treats all on-chain and token text as untrusted data that is never followed as an instruction. The platform's operating rules were updated to make spend, transfer, and mint confirmations a required step rather than something to skip for speed. `[security]`- **New driving jobs in /play — Cross-Town Delivery and East-West Express** — Two real driving missions landed on the /play jobs board. Grab a car parked at any of the four avenue depots, run the rush order to the depot on the other side of town, and get paid — the delivery only counts if you actually drove it, not walked it. Pairs with the world's existing drivable vehicles and cash economy for a real 'drive around, do jobs, spend the cash' loop. (`/play`) `[feature]`+- **New: one search across avatars, agents, models, worlds, and coins** — /search is a new page that queries every creation type on three.ws at once — public avatars, on-chain/Solana agents, forged 3D models, saved worlds, and coins (three.ws's own agent launches first, then the wider pump.fun market) — and ranks results by recency plus real signals like follower count and remix count. Every result links to the live asset and, whenever a creator profile is actually known, straight to it. Models published to the remix bazaar get a one-click "Remix — $0.25" action right on the result card, wired to the same real, on-chain-royalty remix flow as the Creator Gallery — no more digging into a model's own page first. Linked from the Discover menu. (`/search`) `[feature]`- **News stories now open the full article, with live coin charts** — Open a news story and you now get the whole thing. Many crypto publishers (The Defiant, CoinDesk, The Block and others) block automated fetches, so the reader used to fall back to a single teaser sentence — the page looked empty. It now recovers the full article text through a reader service when a publisher blocks the direct fetch, so the complete story renders instead of a stub. When a story mentions a coin, the reader shows a live price card for it — current price, 24h and 7d moves, a 7-day sparkline chart, and market cap — that links straight to the coin's full profile. Every fully-read story is also saved to a durable crypto knowledge base with its summary, key points, sentiment, tickers, and the companies and projects it's about — the memory our 3D AI agents draw on to answer questions with real, recent, sourced context. (`/markets/news`) `[feature, improvement]`- **News story links no longer go dead** — Every article on the news feed gets a permanent link, but stories published near a month boundary could slip through the hourly archiver and their links would eventually 404. The archiver now files each story under its real publication month (and no longer caps how many articles it sweeps per run), story pages look in neighboring months and redirect to the right address when a link's month is off by one, and a link that truly can't be found now offers a one-click archive search for that story's title instead of a dead end. (`/markets/news`) `[fix, improvement]`- **Notification bell now covers remixes, royalties, DMs, and launch graduations** — The nav bell already tracked sales and purchases; it now also fires for real events that used to be invisible unless you happened to be watching: someone remixing one of your published 3D models (with the royalty payout amount if one settled on-chain), a friend DMing you while you're away, and a coin you launched hitting its funding target and graduating off the bonding curve. Dashboard → Settings has a new Notification preferences panel wired to the real per-category preference store, so you can mute any category (sales, purchases, social, IRL, market alerts, account) per channel — in-app, push, email, or Telegram — independently; in-app never turns off, so nothing is silently lost. A gear icon in the bell dropdown jumps straight there. (`/dashboard/settings`) `[feature]`diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 7231a2f6d..755f40642 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -26,6 +26,7 @@ bottom.| Diorama (text → 3D world) | [src/diorama/](src/diorama) `→ /diorama` | In-repo · backend [api/diorama.js](api/diorama.js) | One sentence → an explorable 3D diorama: Claude composes the scene, each object is forged to a real GLB, assembled live, saved to a public gallery + shareable permalink || Creator portfolio (human profile) | [pages/profile.html](pages/profile.html) `→ /u/:username` (self-view `/profile`), backend [api/users/[username].js](api/users/%5Busername%5D.js) + paginated [api/users/[username]/creations.js](api/users/%5Busername%5D/creations.js) `→ /api/users/:username/creations` | Live | Every three.ws user's public portfolio: avatars, agents, widgets, skills, plugins, coins, memories, items for sale, and (added 2026-07-12) a **Creations** tab merging forged 3D models + Scene Studio worlds — real, live, spinning `<model-viewer>` cards, cursor-paginated for 100+ items. `/forge` and `/diorama` stay anonymous by default (no login required); a signed-in creator's `user_id` is now attached to `forge_creations`/`dioramas` rows at generation/save time (migration [api/_lib/migrations/20260712010000_creator_portfolio_user_ids.sql](api/_lib/migrations/20260712010000_creator_portfolio_user_ids.sql)) so those creations surface here. The same opt-in attribution now links back from the diorama viewer HUD, the diorama gallery cards, and the forge result bar ("by @user") whenever a creation's creator is known. `/@:handle` ([pages/handle.html](pages/handle.html)) is a separate, narrower agent-embed page — not the human portfolio. || Labs (hidden-gems hub) | [pages/labs.html](pages/labs.html) + [src/labs.js](src/labs.js) `→ /labs` | In-repo | Data-driven discovery hub: renders every `data/pages.json` entry flagged `showcase: true` as a live card (status check + iframe preview), filterable by category |+| Cross-entity search | [pages/search.html](pages/search.html) `→ /search`, backend [api/search.js](api/search.js) + query layer [api/_lib/cross-search.js](api/_lib/cross-search.js) | Live | The one search across every creation type — avatars, on-chain/Solana agents, forged 3D models, worlds, and coins. Federates (not one SQL UNION — the stores are genuinely heterogeneous, two of five aren't even in the same database) five parallel queries, normalizes into one card shape, and ranks by recency plus real signals (follower count via `user_follows`, remix count, view count) — see the file header in `api/search.js` for the full unify-vs-federate writeup. Model results carry a working "Remix — $0.25" action against the existing paid rail ([api/x402/remix-asset.js](api/x402/remix-asset.js)), reused from [pages/creations.html](pages/creations.html) rather than re-derived. Coin search checks three.ws's own launch directory (`pump_agent_mints`) first, then falls back to market-wide pump.fun/Birdeye search for broader coverage (those external matches carry no verified timestamp or creator profile, and are ranked/labelled accordingly). Linked from the Discover nav menu. || OKX.AI marketplace services | [api/okx/3d/[service].js](api/okx/3d/%5Bservice%5D.js) `→ /api/okx/3d/*` | Live | 3D services sold to other agents on OKX.AI (agent #2632): Agent Identity Studio flagship + decomposed studio services. Catalog source of truth: [api/_lib/okx-catalog.js](api/_lib/okx-catalog.js); pipeline: [api/_okx3d/](api/_okx3d); showcase: [pages/agent-identities.html](pages/agent-identities.html) `→ /agent-identities`; docs: [docs/okx-marketplace.md](docs/okx-marketplace.md) || Crypto Data API docs / landing | [pages/crypto.html](pages/crypto.html) `→ /crypto` | In-repo · docs surface | Screenshot-worthy public docs + funnel-top for the free, keyless Crypto Data API (`/api/crypto/*` — token snapshot, security, holders, launches, bonding, whales, symbol, wallet, trending). Renders hero, endpoint table, tabbed quickstart (curl/JS/Python), per-endpoint request/response reference and a live "Try it" console. Probes production at runtime and marks each endpoint Live vs Coming soon (degrades gracefully while sibling endpoints roll out). CTAs funnel to paid uniques: [/launcher](pages/launcher.html), [/vanity-wallet](public/vanity-wallet.html), [/forge](pages/forge.html). Spec: [prompts/x402-overhaul/](prompts/x402-overhaul) || Free Crypto Data API + discovery | [api/crypto/index.js](api/crypto/index.js) `→ /api/crypto`, [api/crypto/openapi.js](api/crypto/openapi.js) `→ /api/crypto/openapi.json`, docs [docs/crypto-api.md](docs/crypto-api.md) `→ /docs/crypto-api` | Live · docs surface | Front door + OpenAPI 3.1 for the free, keyless Crypto Data API. Catalog assembler [api/_lib/crypto-catalog/index.js](api/_lib/crypto-catalog/index.js) merges `api/_lib/crypto-catalog/*.js` self-describing descriptors (currently `bonding`, `launches`, `symbol`, `token`, `trending`, `wallet`, `whales`) via a static import barrel — the production source of truth, since Vercel's bundler only ships what static imports reach — plus an additive dev-time directory glob; skips malformed/throwing entries, never throws, valid-empty when zero. New descriptor = drop the file AND add its import line to the barrel. OpenAPI built from the same catalog via [api/_lib/crypto-catalog/openapi.js](api/_lib/crypto-catalog/openapi.js). Index does HTML/JSON content negotiation. Endpoint handlers live in `api/crypto/*.js`. Spec: [prompts/x402-overhaul/](prompts/x402-overhaul) |diff --git a/api/_lib/cross-search.js b/api/_lib/cross-search.jsnew file mode 100644index 000000000..ba5a1c046--- /dev/null+++ b/api/_lib/cross-search.js@@ -0,0 +1,282 @@+// cross-search — the query layer behind GET /api/search (api/search.js), the+// cross-entity discovery surface (prompts/user-value/05-discovery-search.md).+//+// three.ws's creation types live in genuinely heterogeneous stores: avatars ++// on-chain/Solana agents in Postgres tables already served by api/explore.js,+// 3D models in forge_creations (api/_lib/forge-store.js), worlds in dioramas+// (api/_lib/diorama-store.js), and coins split between three.ws's own launch+// directory (pump_agent_mints) and the wider pump.fun/Birdeye market (external+// HTTP, no shared schema at all). A single SQL UNION across those is not+// possible — coins aren't even in the same database — so this module fans out+// N independent, narrow queries in parallel and normalizes each into one+// common card shape. That federated-fan-out choice (not a "one true query") is+// the honest one for this data layout; see the search.js file header for the+// full unify-vs-federate writeup.+//+// Every function here returns already-normalized SearchItem objects:+// { type, id, title, description, image, glbUrl, assetUrl, creator, remix,+// createdAt, signals }+// so api/search.js only has to merge + rank arrays, never branch on shape.++import { sql } from './db.js';+import { publicUrl, thumbnailUrl } from './r2.js';+import { listRemixable } from './forge-store.js';+import { listDioramas } from './diorama-store.js';+import { searchAgentLaunches } from './pump-agent-launches.js';+import { searchPumpTokens } from './pump-search.js';++function shortAddr(a) {+ if (!a || a.length < 10) return a || '';+ return `${a.slice(0, 6)}…${a.slice(-4)}`;+}++function likePattern(q) {+ return q ? `%${q}%` : null;+}++// ── avatars ──────────────────────────────────────────────────────────────────++export async function searchAvatars({ q, limit = 12 } = {}) {+ const search = likePattern(q);+ const capped = Math.min(Math.max(Number(limit) || 12, 1), 24);+ const rows = await sql`+ select a.id, a.slug, a.name, a.description, a.storage_key, a.thumbnail_key,+ a.created_at, a.model_category, coalesce(a.view_count, 0) as view_count,+ u.username as owner_username, u.display_name as owner_display_name+ from avatars a+ left join users u on u.id = a.owner_id and u.deleted_at is null+ where a.deleted_at is null and a.visibility = 'public'+ and (${search}::text is null or coalesce(a.name,'') ilike ${search} or coalesce(a.description,'') ilike ${search})+ order by coalesce(a.featured, false) desc, a.created_at desc+ limit ${capped}+ `;+ return rows.map((r) => ({+ type: 'avatar',+ id: r.id,+ title: r.name || 'Untitled avatar',+ description: r.description || '',+ image: thumbnailUrl(r.thumbnail_key),+ glbUrl: publicUrl(r.storage_key),+ assetUrl: `/discover/avatar/${r.id}`,+ creator: r.owner_username+ ? { label: `@${r.owner_username}`, url: `/u/${r.owner_username}` }+ : null,+ remix: null,+ createdAt: r.created_at,+ signals: { viewCount: Number(r.view_count) || 0 },+ }));+}++// ── on-chain + Solana agents ─────────────────────────────────────────────────++export async function searchAgents({ q, limit = 12 } = {}) {+ const search = likePattern(q);+ const capped = Math.min(Math.max(Number(limit) || 12, 1), 24);++ const [onchainRows, solanaRows] = await Promise.all([+ sql`+ select chain_id, agent_id, owner, name, description, image, registered_at+ from erc8004_agents_index+ where active = true+ and (${search}::text is null or coalesce(name,'') ilike ${search} or coalesce(description,'') ilike ${search})+ order by registered_at desc nulls last+ limit ${capped}+ `,+ sql`+ select ai.id, ai.name, ai.description, ai.wallet_address, ai.created_at,+ a.thumbnail_key as avatar_thumb,+ u.username as owner_username, u.display_name as owner_display_name+ from agent_identities ai+ left join avatars a on a.id = ai.avatar_id and a.deleted_at is null+ left join users u on u.id = ai.user_id and u.deleted_at is null+ where ai.deleted_at is null+ and ai.meta->>'chain_type' = 'solana' and ai.meta->>'network' = 'mainnet'+ and (${search}::text is null or coalesce(ai.name,'') ilike ${search} or coalesce(ai.description,'') ilike ${search})+ order by ai.created_at desc nulls last+ limit ${capped}+ `,+ ]);++ const onchainItems = onchainRows.map((r) => ({+ type: 'agent',+ id: `onchain:${r.chain_id}:${r.agent_id}`,+ title: r.name || `Agent #${r.agent_id}`,+ description: r.description || '',+ image: r.image || null,+ glbUrl: null,+ assetUrl: `/discover/a/${r.chain_id}/${r.agent_id}`,+ // No platform user_id on erc8004_agents_index (pure on-chain identity) —+ // the closest honest "creator" link is the owner's on-chain address, not+ // a fabricated three.ws profile.+ creator: r.owner ? { label: shortAddr(r.owner), url: null } : null,+ remix: null,+ createdAt: r.registered_at,+ signals: {},+ }));++ const solanaItems = solanaRows.map((r) => ({+ type: 'agent',+ id: `solana:${r.id}`,+ title: r.name || 'Solana Agent',+ description: r.description || '',+ image: thumbnailUrl(r.avatar_thumb),+ glbUrl: null,+ assetUrl: `/agent/${r.id}`,+ creator: r.owner_username+ ? { label: `@${r.owner_username}`, url: `/u/${r.owner_username}` }+ : r.wallet_address+ ? { label: shortAddr(r.wallet_address), url: null }+ : null,+ remix: null,+ createdAt: r.created_at,+ signals: {},+ }));++ return [...onchainItems, ...solanaItems];+}++// ── 3D models (remix bazaar) ─────────────────────────────────────────────────++export async function searchModels({ q, limit = 12 } = {}) {+ const rows = await listRemixable({ limit, q, sort: 'recent' });+ return rows.map((r) => ({+ type: 'model',+ id: r.id,+ title: r.prompt ? (r.prompt.length > 90 ? `${r.prompt.slice(0, 87)}…` : r.prompt) : 'A remixable 3D model',+ description: r.prompt || '',+ image: r.preview_image_url || null,+ glbUrl: r.glb_url,+ assetUrl: `https://three.ws/viewer?src=${encodeURIComponent(r.glb_url)}`,+ creator: r.ownerUsername+ ? { label: `@${r.ownerUsername}`, url: `/u/${r.ownerUsername}` }+ : { label: 'Lineage', url: `/creations#lineage=${r.id}` },+ remix: {+ endpoint: '/api/x402/remix-asset',+ sourceCreationId: r.id,+ priceUsd: 0.25,+ royaltyPercent: Math.round(((r.royaltyBps ?? 0) / 100) * 10) / 10,+ royaltyPayable: r.royaltyPayable,+ },+ createdAt: r.created_at,+ signals: { remixCount: r.remixCount || 0 },+ }));+}++// ── worlds (dioramas) ─────────────────────────────────────────────────────────++export async function searchWorlds({ q, limit = 12 } = {}) {+ const rows = await listDioramas({ scope: 'recent', limit, q });+ return rows.map((r) => ({+ type: 'world',+ id: r.id,+ title: r.title || 'Untitled world',+ description: r.prompt || '',+ image: null,+ glbUrl: r.thumbnailGlb,+ assetUrl: `/diorama?id=${encodeURIComponent(r.id)}`,+ creator: r.creatorUsername+ ? { label: `@${r.creatorUsername}`, url: `/u/${r.creatorUsername}` }+ : null,+ remix: null,+ createdAt: r.createdAt,+ signals: { viewCount: r.views || 0 },+ }));+}++// ── coins (three.ws launches, then market-wide pump.fun/Birdeye) ────────────++export async function searchCoins({ q, limit = 12 } = {}) {+ if (!q) return [];+ const capped = Math.min(Math.max(Number(limit) || 12, 1), 24);+ const [ownLaunches, external] = await Promise.all([+ searchAgentLaunches({ q, limit: capped }).catch(() => []),+ searchPumpTokens(q, capped).catch(() => []),+ ]);++ const ownItems = ownLaunches.map((l) => ({+ type: 'coin',+ id: `launch:${l.mint}`,+ title: l.name || l.symbol || 'Coin',+ description: l.symbol ? `$${l.symbol}` : '',+ image: l.agent?.avatar_thumbnail_url || null,+ glbUrl: null,+ assetUrl: `/launches/${l.mint}`,+ creator: l.agent ? { label: l.agent.name || 'Launching agent', url: l.agent.url } : null,+ remix: null,+ createdAt: l.createdAt,+ signals: {},+ }));++ const ownMints = new Set(ownLaunches.map((l) => l.mint));+ // External pump.fun/Birdeye matches have no three.ws-verified created_at and+ // no resolvable creator profile — never fabricate either; the market data is+ // still real, just less complete than our own launch directory.+ const externalItems = external+ .filter((t) => !ownMints.has(t.mint))+ .map((t) => ({+ type: 'coin',+ id: `market:${t.mint}`,+ title: t.name || t.symbol || 'Coin',+ description: t.symbol ? `$${t.symbol}` : '',+ image: t.logo || null,+ glbUrl: null,+ assetUrl: `/coin3d?mint=${encodeURIComponent(t.mint)}`,+ creator: { label: 'pump.fun ↗', url: `https://pump.fun/${t.mint}` },+ remix: null,+ createdAt: null,+ signals: {},+ }));++ return [...ownItems, ...externalItems];+}++// ── ranking signals: follower counts for resolved creator profiles ──────────+// Batches one extra query for every /u/:username link a result set surfaced,+// so ranking can weight "does this creator have an audience" without an N+1.+export async function attachFollowerCounts(items) {+ const usernames = [...new Set(items.map((i) => i.creator?.url).filter((u) => u?.startsWith('/u/')).map((u) => u.slice(3)))];+ if (!usernames.length) return items;+ const rows = await sql`+ select u.username, count(f.follower_id)::int as followers+ from users u+ left join user_follows f on f.following_id = u.id+ where lower(u.username) = any(${usernames.map((u) => u.toLowerCase())})+ group by u.username+ `.catch(() => []);+ const byUsername = new Map(rows.map((r) => [r.username.toLowerCase(), r.followers]));+ for (const item of items) {+ const uname = item.creator?.url?.startsWith('/u/') ? item.creator.url.slice(3).toLowerCase() : null;+ if (uname && byUsername.has(uname)) {+ item.signals = { ...item.signals, followerCount: byUsername.get(uname) };+ }+ }+ return items;+}++// ── ranking ───────────────────────────────────────────────────────────────────+// Recency is the primary signal (real for every type except external+// market-wide coin matches, which carry no verified timestamp). Real+// engagement signals — followers, remix count, views — nudge a result up by a+// capped amount so a genuinely popular older item can beat a brand-new one,+// without letting popularity fully override "when was this made". No signal+// is fabricated: items missing a signal simply get zero boost from it.+const DAY_MS = 24 * 60 * 60 * 1000;+// Undated external coin matches sink near the bottom but still surface.+const UNDATED_BASELINE_MS = Date.now() - 365 * DAY_MS;++export function rankItems(items) {+ return items+ .map((item) => {+ const base = item.createdAt ? new Date(item.createdAt).getTime() : UNDATED_BASELINE_MS;+ const followers = item.signals?.followerCount || 0;+ const remixes = item.signals?.remixCount || 0;+ const views = item.signals?.viewCount || 0;+ const boost =+ Math.min(followers * DAY_MS, 30 * DAY_MS) ++ Math.min(remixes * DAY_MS * 0.5, 15 * DAY_MS) ++ Math.min(views * DAY_MS * 0.05, 7 * DAY_MS);+ return { item, score: base + boost };+ })+ .sort((a, b) => b.score - a.score)+ .map((s) => s.item);+}diff --git a/api/_lib/diorama-store.js b/api/_lib/diorama-store.jsindex e079a5a6e..1a47effd6 100644--- a/api/_lib/diorama-store.js+++ b/api/_lib/diorama-store.js@@ -181,10 +181,14 @@ export async function bumpViews(id) {* scope: 'recent' (default) | 'featured'. Returns lightweight cards.* `before` (recent scope only) cursors by created_at for infinite scroll —* used by the platform-wide activity feed (api/users/me/feed.js, scope=all).+ * `q` (optional, recent scope only) does a case-insensitive substring match on+ * title/prompt — powers the cross-entity search endpoint (api/search.js);+ * additive and backward-compatible, ignored when scope='featured'.*/-export async function listDioramas({ scope = 'recent', limit = 24, before } = {}) {+export async function listDioramas({ scope = 'recent', limit = 24, before, q } = {}) {if (!(await ensureTable())) return [];const lim = Math.min(60, Math.max(1, Number(limit) || 24));+ const search = typeof q === 'string' && q.trim() ? `%${q.trim().slice(0, 120)}%` : null;try {const rows =scope === 'featured'@@ -204,6 +208,7 @@ export async function listDioramas({ scope = 'recent', limit = 24, before } = {}from dioramas dleft join users u on u.id = d.user_id and u.deleted_at is nullwhere d.created_at < ${before}+ and (${search}::text is null or d.title ilike ${search} or d.prompt ilike ${search})order by d.created_at desc limit ${lim}`: await sql`select d.id, d.title, d.prompt, d.mood, d.ground, d.views, d.featured, d.created_at,@@ -211,6 +216,7 @@ export async function listDioramas({ scope = 'recent', limit = 24, before } = {}u.username as creator_username, u.display_name as creator_display_name, u.avatar_url as creator_avatar_urlfrom dioramas dleft join users u on u.id = d.user_id and u.deleted_at is null+ where (${search}::text is null or d.title ilike ${search} or d.prompt ilike ${search})order by d.created_at desc limit ${lim}`;return rows.map(toCard);} catch (err) {diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.jsindex f7b926d08..318cbf268 100644--- a/api/_lib/forge-store.js+++ b/api/_lib/forge-store.js@@ -21,6 +21,7 @@ import { putObject, publicUrl } from './r2.js';import { recordGenerationEvent } from './forge-events.js';import { scoreGlbQuality } from './glb-quality.js';import { compressGlb } from './glb-compress.js';+import { recordDailyActivity, maybeAwardFirstCreation } from './streaks.js';// Stable, non-secret salt so a leaked DB row can't be trivially reversed to the// raw browser-local id. The id is anonymous to begin with; this is hygiene, not@@ -874,7 +875,8 @@ export async function listRemixable({ limit = 24, before, category, q, sort } =`select p.id, p.prompt, p.glb_url, p.preview_image_url, p.remix_royalty_bps,p.creator_wallet_solana, p.parent_creation_id, p.lineage_index,p.backend, p.model_category, p.created_at,- coalesce(rc.remix_count, 0) as remix_count+ coalesce(rc.remix_count, 0) as remix_count,+ u.username as owner_username, u.display_name as owner_display_name, u.avatar_url as owner_avatar_urlfrom forge_creations pleft join (select parent_creation_id, count(*) as remix_count@@ -882,6 +884,7 @@ export async function listRemixable({ limit = 24, before, category, q, sort } =where parent_creation_id is not null and status = 'done'group by parent_creation_id) rc on rc.parent_creation_id = p.id+ left join users u on u.id = p.user_id and u.deleted_at is nullwhere ${conds.join(' and ')}order by ${orderBy}limit ${limitParam}`,@@ -902,6 +905,11 @@ export async function listRemixable({ limit = 24, before, category, q, sort } =backend: r.backend ?? null,model_category: r.model_category ?? 'other',created_at: r.created_at,+ // Opt-in creator attribution — only when the model was made while+ // signed in (same contract as listRecentCreations / creator-portfolio).+ ownerUsername: r.owner_username || null,+ ownerDisplayName: r.owner_display_name || null,+ ownerAvatarUrl: r.owner_avatar_url || null,}));} catch (err) {if (isDbUnavailableError(err)) console.warn('[forge-store] listRemixable skipped (db unavailable):', err?.message);diff --git a/api/_lib/pump-agent-launches.js b/api/_lib/pump-agent-launches.jsindex 2a02358ed..263044c2e 100644--- a/api/_lib/pump-agent-launches.js+++ b/api/_lib/pump-agent-launches.js@@ -140,3 +140,47 @@ export async function queryAgentLaunches({return { launches, has_more: hasMore };}++/**+ * Name/symbol search over three.ws's own launch directory (pump_agent_mints) —+ * the platform-native half of the cross-entity search endpoint (api/search.js).+ * Distinct from searchPumpTokens (api/_lib/pump-search.js), which searches+ * pump.fun/Birdeye market-wide and has no creator or three.ws-verified+ * created_at; results here always carry a real launching agent and timestamp.+ */+export async function searchAgentLaunches({ q, network = 'mainnet', limit = 12 } = {}) {+ const search = typeof q === 'string' && q.trim() ? `%${q.trim().slice(0, 80)}%` : null;+ if (!search) return [];+ const capped = Math.min(Math.max(Number(limit) || 12, 1), 24);+ const rows = await sql`+ select pam.mint, pam.network, pam.name, pam.symbol, pam.created_at,+ ai.id as agent_id, ai.name as agent_name,+ a.thumbnail_key as avatar_thumbnail_key,+ a.visibility as avatar_visibility+ from pump_agent_mints pam+ left join agent_identities ai on ai.id = pam.agent_id and ai.deleted_at is null+ left join avatars a on a.id = ai.avatar_id and a.deleted_at is null+ where pam.network = ${network}+ and (coalesce(pam.name,'') ilike ${search} or coalesce(pam.symbol,'') ilike ${search})+ order by pam.created_at desc+ limit ${capped}+ `;+ return rows.map((r) => {+ const avatarPublic = r.avatar_visibility === 'public' || r.avatar_visibility === 'unlisted';+ return {+ mint: r.mint,+ network: r.network,+ name: r.name,+ symbol: r.symbol,+ createdAt: r.created_at,+ agent: r.agent_id+ ? {+ id: r.agent_id,+ name: r.agent_name,+ url: `/agents/${r.agent_id}`,+ avatar_thumbnail_url: r.avatar_thumbnail_key && avatarPublic ? r2PublicUrl(r.avatar_thumbnail_key) : null,+ }+ : null,+ };+ });+}diff --git a/api/search.js b/api/search.jsnew file mode 100644index 000000000..ca23a1f3c--- /dev/null+++ b/api/search.js@@ -0,0 +1,125 @@+// GET /api/search?q=<text>&type=<all|avatar|agent|model|world|coin>&limit=<n>+// ---------------------------------------------------------------------------+// The cross-entity discovery endpoint (prompts/user-value/05-discovery-search.md,+// wave 05). Every creation type on three.ws — avatars, on-chain/Solana agents,+// forged 3D models, saved worlds, and coins — had its own siloed browse+// surface (/discover, /gallery, /marketplace, /creations, /launches) with no+// single place to search "things like this" across all of them.+//+// Unify vs. federate: the underlying stores are genuinely heterogeneous —+// agents/avatars live in Postgres tables already served by api/explore.js,+// models in forge_creations, worlds in dioramas, and coins split between+// three.ws's own launch directory (pump_agent_mints, Postgres) and the wider+// pump.fun/Birdeye market (external HTTP APIs, no schema in common at all). A+// single SQL query spanning all five is not possible — two of the five+// sources aren't even in the same database. This endpoint FEDERATES: it fans+// out five independent, narrow queries in parallel (api/_lib/cross-search.js),+// normalizes each into one card shape, then merges and ranks server-side —+// so the CLIENT still only ever calls one endpoint and gets one ranked list,+// even though the backend fan-out is real. That's the honest middle ground:+// simpler than forcing a fake unified store, but not punting the merge to the+// browser either.+//+// Ranking: recency is the primary signal for every type except external+// (non-three.ws) coin matches, which have no verified timestamp. Real signals+// — follower count of a resolved creator profile (user_follows), remix count+// (forge_creations), view count (avatars/worlds) — nudge a result up by a+// capped amount; see rankItems() in cross-search.js for the exact formula. No+// signal is fabricated.+//+// Every avatar/agent/model/world/own-coin result carries a resolvable+// assetUrl (the live thing) and, whenever a creator is actually known, a+// creator.url (their three.ws profile). Where no platform profile exists+// (pure on-chain agent identities, anonymous model creations, external market+// coins) the creator field still points somewhere real (an explorer address,+// a lineage page, pump.fun) rather than being fabricated or omitted.+//+// Model results carry a `remix` block wired to the real, already-shipped paid+// remix flow (POST /api/x402/remix-asset) — the only type with a live remix+// rail today; other types don't get a fake Remix button.++import { cors, json, method, wrap, rateLimited } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { databaseConfigured } from './_lib/env.js';+import { forgeStoreEnabled } from './_lib/forge-store.js';+import { dioramaStoreEnabled } from './_lib/diorama-store.js';+import {+ searchAvatars,+ searchAgents,+ searchModels,+ searchWorlds,+ searchCoins,+ attachFollowerCounts,+ rankItems,+} from './_lib/cross-search.js';++const TYPES = new Set(['avatar', 'agent', 'model', 'world', 'coin']);++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) 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');+ // Strip control characters before they reach an ILIKE query (same guard as+ // api/explore.js — a NUL byte throws invalid-UTF8 out of Postgres as an+ // unhandled 500 on a public endpoint).+ // eslint-disable-next-line no-control-regex+ const q = (url.searchParams.get('q') || '')+ .replace(/[\u0000-\u001F\u007F-\u009F]/g, '')+ .trim()+ .slice(0, 80);+ const typeParam = (url.searchParams.get('type') || 'all').trim();+ const type = TYPES.has(typeParam) ? typeParam : 'all';+ const rawLimit = parseInt(url.searchParams.get('limit') || '18', 10);+ const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 4), 48) : 18;+ // Per-type fetch size: a mixed "all" query asks each source for a fraction+ // of the page so the merged, ranked result stays close to `limit` without+ // starving any one type; a scoped type search asks for the full limit.+ const perType = type === 'all' ? Math.max(6, Math.ceil(limit / 2)) : limit;++ const dbReady = databaseConfigured();+ if (!dbReady) {+ // Every source degrades to empty rather than throwing when storage isn't+ // configured (mirrors explore.js / forge-store.js / diorama-store.js) —+ // surface that as a designed "search is warming up" state, not a 500.+ return json(res, 200, { enabled: false, q, type, items: [] });+ }++ const wantsModels = forgeStoreEnabled() && (type === 'all' || type === 'model');+ const wantsWorlds = dioramaStoreEnabled() && (type === 'all' || type === 'world');++ const [avatarItems, agentItems, modelItems, worldItems, coinItems] = await Promise.all([+ type === 'all' || type === 'avatar' ? searchAvatars({ q: q || null, limit: perType }) : [],+ type === 'all' || type === 'agent' ? searchAgents({ q: q || null, limit: perType }) : [],+ wantsModels ? searchModels({ q: q || undefined, limit: perType }) : [],+ wantsWorlds ? searchWorlds({ q: q || undefined, limit: perType }) : [],+ // Coins require a query — there's no "browse all pump.fun tokens"+ // concept here (that's /launches / /trending's job), only search.+ q && (type === 'all' || type === 'coin') ? searchCoins({ q, limit: perType }) : [],+ ]);++ let items = [...avatarItems, ...agentItems, ...modelItems, ...worldItems, ...coinItems];+ items = await attachFollowerCounts(items);+ items = rankItems(items).slice(0, limit);++ const counts = {+ avatar: avatarItems.length,+ agent: agentItems.length,+ model: modelItems.length,+ world: worldItems.length,+ coin: coinItems.length,+ };++ return json(+ res,+ 200,+ { enabled: true, q, type, items, counts, total: items.length },+ // Short public cache — search is near-real-time but not personalized, and+ // this endpoint fans out to 5 sources per miss, so a brief edge cache+ // meaningfully protects the DB + upstream market APIs from repeat keystrokes.+ { 'cache-control': 'public, s-maxage=20, stale-while-revalidate=60' },+ );+});diff --git a/data/changelog.json b/data/changelog.jsonindex 184fef702..cd26fd2c4 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-12",+ "title": "New: one search across avatars, agents, models, worlds, and coins",+ "summary": "/search is a new page that queries every creation type on three.ws at once — public avatars, on-chain/Solana agents, forged 3D models, saved worlds, and coins (three.ws's own agent launches first, then the wider pump.fun market) — and ranks results by recency plus real signals like follower count and remix count. Every result links to the live asset and, whenever a creator profile is actually known, straight to it. Models published to the remix bazaar get a one-click \"Remix — $0.25\" action right on the result card, wired to the same real, on-chain-royalty remix flow as the Creator Gallery — no more digging into a model's own page first. Linked from the Discover menu.",+ "tags": [+ "feature"+ ],+ "link": "/search"+ },{"date": "2026-07-12","title": "/feed and /community are now real, live pages",diff --git a/data/pages.json b/data/pages.jsonindex e1ab8cfa2..043f2f6c9 100644--- a/data/pages.json+++ b/data/pages.json@@ -179,6 +179,14 @@"changefreq": "daily","added": "2026-05-04"},+ {+ "path": "/search",+ "title": "Search",+ "description": "One search across every creation type on three.ws — avatars, agents, 3D models, worlds, and coins — with remixable models remixable straight from the results.",+ "priority": 0.8,+ "changefreq": "daily",+ "added": "2026-07-12"+ },{"path": "/sitemap","title": "Sitemap",diff --git a/pages/search.html b/pages/search.htmlnew file mode 100644index 000000000..c3d3bcc4a--- /dev/null+++ b/pages/search.html@@ -0,0 +1,108 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Search · three.ws</title>+ <meta+ name="description"+ content="Search everything on three.ws in one place — avatars, agents, 3D models, worlds, and coins — and remix any published model straight from the results."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/search" />+ <meta property="og:title" content="Search · three.ws" />+ <meta+ property="og:description"+ content="One search across every creation type on three.ws — avatars, agents, 3D models, worlds, and coins."+ />+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&t=Search&d=One+search+across+every+creation+type+on+three.ws.&p=%2Fsearch" />+ <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="Search · three.ws" />+ <meta name="twitter:description" content="One search across every creation type on three.ws — avatars, agents, 3D models, worlds, and coins." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&t=Search&d=One+search+across+every+creation+type+on+three.ws.&p=%2Fsearch" />+ <meta name="theme-color" content="#0a0a0a" />+ <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="/manifest.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/search-page.css" />+ <link rel="stylesheet" href="/footer.css" />+ <script defer src="/footer-newsletter.js"></script>+ <link rel="canonical" href="https://three.ws/search" />+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"SearchResultsPage","name":"Search","description":"Search every creation type on three.ws — avatars, agents, 3D models, worlds, and coins.","url":"https://three.ws/search","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="Search — three.ws" />+ <script src="/model-viewer-meshopt.js"></script>+ <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js" integrity="sha384-sr9b4Ux0WhAUGclJ0ym0FSY2zSOMmNSn0bP/SA0e6bNCrpn/5W3QL8mm+LdlQMKw" crossorigin="anonymous"></script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="sr-shell">+ <section class="sr-hero">+ <p class="sr-kicker"><span aria-hidden="true">⌕</span> Cross-entity search</p>+ <h1 class="sr-title">Search <em>everything</em></h1>+ <p class="sr-sub">+ One query across every creation type on three.ws — avatars, agents, 3D models, worlds, and coins.+ Remixable models can be remixed straight from the results.+ </p>+ <div class="sr-controls">+ <label class="sr-search" for="sr-q">+ <svg viewBox="0 0 20 20" width="18" height="18" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="1.6" d="M13.6 13.6 18 18M9 15.5a6.5 6.5 0 1 1 0-13 6.5 6.5 0 0 1 0 13Z"/></svg>+ <input type="search" id="sr-q" placeholder="Search avatars, agents, models, worlds, coins…" autocomplete="off" maxlength="80" />+ </label>+ <div class="sr-types" id="sr-types" role="tablist" aria-label="Filter by type"></div>+ </div>+ </section>++ <section class="sr-feed-head">+ <h2 class="sr-section-h" style="font-family: var(--font-display, sans-serif); font-size: var(--text-lg, 1.05rem); font-weight: 600; margin: 0;">Results</h2>+ <span id="sr-count" class="sr-count" aria-live="polite"></span>+ </section>++ <section id="sr-grid" class="sr-grid" aria-label="Search results"></section>++ <div class="sr-quicklinks" id="sr-quicklinks">+ <a class="sr-quicklink" href="/creations">+ <span class="sr-quicklink-title">Creator Gallery →</span>+ <span class="sr-quicklink-desc">Browse and remix the live 3D creation bazaar</span>+ </a>+ <a class="sr-quicklink" href="/gallery">+ <span class="sr-quicklink-title">Avatar Gallery →</span>+ <span class="sr-quicklink-desc">Every public 3D avatar</span>+ </a>+ <a class="sr-quicklink" href="/agents">+ <span class="sr-quicklink-title">Agents Index →</span>+ <span class="sr-quicklink-desc">Browse every registered agent</span>+ </a>+ <a class="sr-quicklink" href="/play">+ <span class="sr-quicklink-title">Worlds →</span>+ <span class="sr-quicklink-desc">Every coin is a 3D world — drop in</span>+ </a>+ <a class="sr-quicklink" href="/launches">+ <span class="sr-quicklink-title">All Launches →</span>+ <span class="sr-quicklink-desc">Every agent-launched coin</span>+ </a>+ <a class="sr-quicklink" href="/trending">+ <span class="sr-quicklink-title">Trending →</span>+ <span class="sr-quicklink-desc">Top agents and top conviction coins right now</span>+ </a>+ </div>+ </main>++ <script type="module" src="/src/search-page.js"></script>+ <script src="/brand.js" defer></script>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/public/changelog.json b/public/changelog.jsonindex 77b0f6306..ec1e0fd0f 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-12T16:11:52.299Z",+ "generated_at": "2026-07-12T16:56:26.625Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -26,6 +26,16 @@"launch"]},+ {+ "date": "2026-07-12",+ "type": "launch",+ "title": "Search",+ "summary": "One search across every creation type on three.ws — avatars, agents, 3D models, worlds, and coins — with remixable models remixable straight from the results.",+ "link": "/search",+ "tags": [+ "launch"+ ]+ },{"date": "2026-07-12","type": "launch",@@ -140,6 +150,16 @@"feature"]},+ {+ "date": "2026-07-12",+ "type": "update",+ "title": "New: one search across avatars, agents, models, worlds, and coins",+ "summary": "/search is a new page that queries every creation type on three.ws at once — public avatars, on-chain/Solana agents, forged 3D models, saved worlds, and coins (three.ws's own agent launches first, then the wider pump.fun market) — and ranks results by recency plus real signals like follower count and remix count. Every result links to the live asset and, whenever a creator profile is actually known, straight to it. Models published to the remix bazaar get a one-click \"Remix — $0.25\" action right on the result card, wired to the same real, on-chain-royalty remix flow as the Creator Gallery — no more digging into a model's own page first. Linked from the Discover menu.",+ "link": "/search",+ "tags": [+ "feature"+ ]+ },{"date": "2026-07-12","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex c54db4715..7e98812a4 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -22,6 +22,14 @@<category>launch</category><description>The 24/7 tokenized-equity board for Robinhood Chain (4663): live Chainlink NAV vs DEX premium for every Stock Token, a memecoin screener across NOXA and The Odyssey launchpads, recent launches, and chain TVL — plus a real wallet-connect buy flow for its coins.</description></item>+ <item>+ <title>Search</title>+ <link>https://three.ws/search</link>+ <guid isPermaLink="false">2026-07-12:Search</guid>+ <pubDate>Sun, 12 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>One search across every creation type on three.ws — avatars, agents, 3D models, worlds, and coins — with remixable models remixable straight from the results.</description>+ </item><item><title>Your creator portfolio</title><link>https://three.ws/profile</link>@@ -110,6 +118,14 @@<category>feature</category><description>Two real driving missions landed on the /play jobs board. Grab a car parked at any of the four avenue depots, run the rush order to the depot on the other side of town, and get paid — the delivery only counts if you actually drove it, not walked it. Pairs with the world's existing drivable vehicles and cash economy for a real 'drive around, do jobs, spend the cash' loop.</description></item>+ <item>+ <title>New: one search across avatars, agents, models, worlds, and coins</title>+ <link>https://three.ws/search</link>+ <guid isPermaLink="false">2026-07-12:New: one search across avatars, agents, models, worlds, and coins</guid>+ <pubDate>Sun, 12 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>/search is a new page that queries every creation type on three.ws at once — public avatars, on-chain/Solana agents, forged 3D models, saved worlds, and coins (three.ws's own agent launches first, then the wider pump.fun market) — and ranks results by recency plus real signals like follower count and remix count. Every result links to the live asset and, whenever a creator profile is actually known, straight to it. Models published to the remix bazaar get a one-click "Remix — $0.25" action right on the result card, wired to the same real, on-chain-royalty remix flow as the Creator Gallery — no more digging into a model's own page first. Linked from the Discover menu.</description>+ </item><item><title>News stories now open the full article, with live coin charts</title><link>https://three.ws/markets/news</link>diff --git a/public/features.json b/public/features.jsonindex 66d016f82..48c1039ab 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-12T16:11:52.286Z",+ "generated_at": "2026-07-12T16:56:26.612Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -215,6 +215,16 @@"tags": [],"showcase": false},+ {+ "path": "/search",+ "title": "Search",+ "description": "One search across every creation type on three.ws — avatars, agents, 3D models, worlds, and coins — with remixable models remixable straight from the results.",+ "added": "2026-07-12",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/sitemap","title": "Sitemap",diff --git a/public/llms-full.txt b/public/llms-full.txtindex 7f6c40f13..5c17630dd 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -133,6 +133,12 @@ URL: https://three.ws/communityLive platform activity plus where to follow, contribute, and connect with three.ws creators.+### Search++URL: https://three.ws/search++One search across every creation type on three.ws — avatars, agents, 3D models, worlds, and coins — with remixable models remixable straight from the results.+### SitemapURL: https://three.ws/sitemapdiff --git a/public/llms.txt b/public/llms.txtindex b5e539bcc..747e4096b 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -31,6 +31,7 @@ Entry points into the product.- [My Collection](https://three.ws/collection): View all the skills and subscriptions you've unlocked on three.ws.- [Skills Marketplace](https://three.ws/skills): Browse, search, and install agent skills — tool packs, knowledge bases, and capabilities that make AI agents smarter.- [Community](https://three.ws/community): Live platform activity plus where to follow, contribute, and connect with three.ws creators.+- [Search](https://three.ws/search): One search across every creation type on three.ws — avatars, agents, 3D models, worlds, and coins — with remixable models remixable straight from the results.- [Sitemap](https://three.ws/sitemap): Human-readable index of every page on three.ws.- [Characters](https://three.ws/characters): Discover AI characters on three.ws. Chat, trade, and create.- [What is three.ws?](https://three.ws/what-is): Plain-English introduction to three.ws — what a 3D AI agent is, real use-cases, and where to begin.diff --git a/public/nav-data.js b/public/nav-data.jsindex 4e3dd28b7..23e073865 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -125,6 +125,11 @@ export const NAV_GROUPS = [{label: 'Start here',items: [+ {+ title: 'Search',+ href: '/search',+ desc: 'One search across avatars, agents, 3D models, worlds & coins — remix straight from the results',+ },{title: 'Trending',href: '/trending',@@ -495,6 +500,11 @@ export const NAV_GROUPS = [href: '/leaderboard',desc: 'Top traders ranked by a provable track record',},+ {+ title: 'Rankings',+ href: '/rankings',+ desc: 'Cross-surface leaderboard — creations, remixes, launches, followers, and walk distance, plus streaks and badges',+ },{title: 'The Arena',href: '/arena',diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 7ac2469cb..46f641d95 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 426 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 427 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 426 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 427 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -96,7 +96,7 @@</nav><section class="sm-section" id="main"><header>- <h2>Main<span class="sm-count" data-count>28</span></h2>+ <h2>Main<span class="sm-count" data-count>29</span></h2><p class="sm-section-desc">Entry points into the product.</p></header><ul class="sm-list">@@ -240,6 +240,13 @@<span class="sm-desc">Live platform activity plus where to follow, contribute, and connect with three.ws creators.</span></a></li>+ <li>+ <a href="/search">+ <span class="sm-title">Search</span>+ <span class="sm-path">/search</span>+ <span class="sm-desc">One search across every creation type on three.ws — avatars, agents, 3D models, worlds, and coins — with remixable models remixable straight from the results.</span>+ </a>+ </li><li><a href="/sitemap"><span class="sm-title">Sitemap</span>diff --git a/src/search-page.css b/src/search-page.cssnew file mode 100644index 000000000..648941e7c--- /dev/null+++ b/src/search-page.css@@ -0,0 +1,89 @@+/* /search — cross-entity discovery. Same monochrome shell + token vocabulary+ as /creations, /minted, /launches (ui-juice.css + tokens.css) so the fifth+ "browse" surface reads as part of the same family, not a bolt-on. */+@import './ui-juice.css';++.sr-shell { max-width: 1200px; margin: 0 auto; padding: var(--space-xl, 40px) var(--space-md, 16px) var(--space-2xl, 64px); }++.sr-hero { text-align: center; margin-bottom: var(--space-xl, 40px); }+.sr-kicker { display: inline-flex; align-items: center; gap: 8px; font-size: var(--text-2xs, .68rem); letter-spacing: .14em; text-transform: uppercase; color: var(--ink-dim, #888); margin: 0 0 var(--space-sm, 12px); }+.sr-title { font-family: var(--font-display, 'Space Grotesk', sans-serif); font-size: clamp(2.2rem, 6vw, 3.4rem); font-weight: 700; line-height: 1.02; margin: 0 0 var(--space-sm, 12px); color: var(--ink-dim, #999); letter-spacing: -.02em; }+.sr-title em { font-style: normal; color: var(--ink-bright, #fff); }+.sr-sub { max-width: 680px; margin: 0 auto; color: var(--ink-dim, #999); font-size: var(--text-lg, 1.02rem); line-height: 1.5; }++/* Search bar + type filters */+.sr-controls { margin: var(--space-lg, 24px) auto 0; max-width: 760px; display: flex; flex-direction: column; gap: 12px; }+.sr-search { display: flex; align-items: center; gap: 10px; background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.1)); border-radius: var(--radius-pill, 999px); padding: 12px 20px; transition: border-color .14s ease; }+.sr-search:focus-within { border-color: var(--stroke-strong, rgba(255,255,255,.24)); }+.sr-search svg { flex: 0 0 auto; color: var(--ink-faint, #666); }+.sr-search input { flex: 1; border: none; background: transparent; outline: none; font: inherit; font-size: var(--text-lg, 1rem); color: var(--ink-bright, #fff); min-width: 0; }+.sr-search input::placeholder { color: var(--ink-faint, #666); }++.sr-types { display: flex; flex-wrap: wrap; gap: 6px; justify-content: center; }+.sr-type-btn { appearance: none; font: inherit; font-size: var(--text-sm, .82rem); font-weight: 600; cursor: pointer; color: var(--ink-dim, #888); background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-pill, 999px); padding: 7px 16px; transition: color .14s ease, background .14s ease, border-color .14s ease; }+.sr-type-btn:hover { color: var(--ink, #e8e8e8); }+.sr-type-btn.active { color: var(--bg-0, #0a0a0a); background: var(--ink-bright, #fff); border-color: var(--ink-bright, #fff); }+.sr-type-btn:focus-visible { outline: 2px solid var(--accent, #fff); outline-offset: 2px; }+.sr-type-count { opacity: .65; font-weight: 500; margin-left: 4px; }++/* Feed head */+.sr-feed-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin: var(--space-xl, 40px) 0 var(--space-md, 16px); flex-wrap: wrap; }+.sr-count { font-size: var(--text-sm, .8rem); color: var(--ink-faint, #666); }++/* Card grid */+.sr-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: var(--space-md, 16px); }+.sr-card { position: relative; display: flex; flex-direction: column; background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.07)); border-radius: var(--radius-lg, 14px); overflow: hidden; transition: border-color .14s ease, transform .14s ease, background .14s ease; animation: sr-in .3s ease both; }+@keyframes sr-in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }+.sr-card:hover { border-color: var(--stroke-strong, rgba(255,255,255,.18)); background: var(--surface-2, rgba(255,255,255,.05)); transform: translateY(-2px); }++.sr-card-thumb { display: block; aspect-ratio: 1 / 1; background: var(--bg-0, #0a0a0a); position: relative; }+.sr-card-mv { width: 100%; height: 100%; display: block; --poster-color: transparent; background: radial-gradient(circle at 50% 40%, var(--surface-2, rgba(255,255,255,.05)), var(--bg-0, #0a0a0a)); }+.sr-card-img { width: 100%; height: 100%; object-fit: cover; display: block; }+.sr-card-noimg { width: 100%; height: 100%; display: grid; place-items: center; font-family: var(--font-mono, monospace); font-size: var(--text-xl, 1.2rem); font-weight: 700; color: var(--ink-faint, #555); background: var(--surface-1, rgba(255,255,255,.03)); }+.sr-card-type { position: absolute; top: 8px; left: 8px; font-size: var(--text-2xs, .6rem); font-weight: 700; letter-spacing: .04em; text-transform: uppercase; color: var(--ink-bright, #fff); background: rgba(0,0,0,.6); backdrop-filter: blur(4px); border-radius: var(--radius-sm, 6px); padding: 2px 7px; }++.sr-card-body { padding: 12px 14px 14px; display: flex; flex-direction: column; gap: 8px; min-width: 0; flex: 1; }+.sr-card-title { margin: 0; font-size: var(--text-sm, .88rem); font-weight: 600; color: var(--ink-bright, #fff); line-height: 1.35; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }+.sr-card-title a { color: inherit; text-decoration: none; }+.sr-card-title a:hover { text-decoration: underline; }+.sr-card-desc { margin: 0; font-size: var(--text-2xs, .74rem); color: var(--ink-dim, #999); line-height: 1.4; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; min-height: 2em; }+.sr-card-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }+.sr-card-creator { font-size: var(--text-2xs, .68rem); color: var(--ink-faint, #777); text-decoration: none; }+.sr-card-creator:hover { color: var(--ink-bright, #fff); text-decoration: underline; }+.sr-card-followers { font-size: var(--text-2xs, .64rem); color: var(--ink-faint, #666); }++.sr-card-actions { margin-top: auto; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }+.sr-card-btn { appearance: none; font: inherit; font-size: var(--text-2xs, .72rem); font-weight: 600; cursor: pointer; color: var(--ink, #e8e8e8); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.1)); border-radius: var(--radius-sm, 8px); padding: 6px 10px; transition: background .14s ease, border-color .14s ease; text-decoration: none; }+.sr-card-btn:hover { background: var(--surface-3, rgba(255,255,255,.08)); border-color: var(--stroke-strong, rgba(255,255,255,.18)); }+.sr-card-btn:focus-visible { outline: 2px solid var(--accent, #fff); outline-offset: 2px; }+.sr-card-btn--remix { color: var(--bg-0, #0a0a0a); background: var(--ink-bright, #fff); border-color: var(--ink-bright, #fff); }+.sr-card-btn--remix:hover { background: var(--ink, #e8e8e8); }+.sr-card-btn:disabled { opacity: .5; cursor: not-allowed; }++.sr-remix-inline { display: none; flex-direction: column; gap: 6px; padding-top: 8px; border-top: 1px dashed var(--stroke, rgba(255,255,255,.1)); margin-top: 8px; width: 100%; }+.sr-remix-inline.is-open { display: flex; }+.sr-remix-inline input { font: inherit; font-size: var(--text-sm, .8rem); color: var(--ink-bright, #fff); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.1)); border-radius: var(--radius-sm, 8px); padding: 7px 10px; }+.sr-remix-status { font-size: var(--text-2xs, .7rem); color: var(--ink-faint, #666); min-height: 1.3em; }+.sr-remix-status[data-kind="error"] { color: var(--danger, #f87171); }+.sr-remix-status[data-kind="done"] { color: var(--success, #4ade80); }+.sr-remix-status a { color: inherit; text-decoration: underline; }++/* Skeleton / empty / error */+.sr-skeleton { aspect-ratio: 3 / 4; border-radius: var(--radius-lg, 14px); background: linear-gradient(90deg, var(--surface-1, rgba(255,255,255,.03)) 25%, var(--surface-2, rgba(255,255,255,.06)) 37%, var(--surface-1, rgba(255,255,255,.03)) 63%); background-size: 400% 100%; animation: sr-shimmer 1.4s ease infinite; }+@keyframes sr-shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }+.sr-empty, .sr-error { grid-column: 1 / -1; text-align: center; padding: var(--space-xl, 40px) var(--space-md, 16px); color: var(--ink-dim, #888); border: 1px dashed var(--stroke, rgba(255,255,255,.12)); border-radius: var(--radius-lg, 14px); }+.sr-empty-title { color: var(--ink-bright, #fff); font-weight: 600; margin-bottom: 6px; font-size: var(--text-lg, 1rem); }+.sr-empty-sub { max-width: 460px; margin: 0 auto 16px; font-size: var(--text-sm, .85rem); line-height: 1.5; }+.sr-empty-ctas { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; }+.sr-error a { color: var(--ink-bright, #fff); }++/* Suggested-when-idle quick links (no query yet) */+.sr-quicklinks { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: var(--space-sm, 12px); margin-top: var(--space-lg, 24px); }+.sr-quicklink { display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.07)); border-radius: var(--radius-lg, 14px); text-decoration: none; transition: border-color .14s ease, background .14s ease, transform .14s ease; }+.sr-quicklink:hover { border-color: var(--stroke-strong, rgba(255,255,255,.18)); background: var(--surface-2, rgba(255,255,255,.05)); transform: translateY(-2px); }+.sr-quicklink-title { font-size: var(--text-sm, .85rem); font-weight: 600; color: var(--ink-bright, #fff); }+.sr-quicklink-desc { font-size: var(--text-2xs, .7rem); color: var(--ink-faint, #777); line-height: 1.4; }++@media (max-width: 520px) {+ .sr-grid { grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); }+}diff --git a/src/search-page.js b/src/search-page.jsnew file mode 100644index 000000000..f9490587f--- /dev/null+++ b/src/search-page.js@@ -0,0 +1,261 @@+// /search — cross-entity discovery over GET /api/search. Debounced text query+// + type filter chips, fanning out to the federated backend (api/search.js /+// api/_lib/cross-search.js) and rendering one ranked grid of avatar/agent/+// model/world/coin cards. Model results carry a real, wired "Remix — $0.25"+// action against the same paid rail /creations uses (POST /api/x402/remix-asset)+// — reusing that flow rather than re-deriving it.++import { ensureX402 } from './shared/x402-loader.js';++const $ = (id) => document.getElementById(id);++const TYPE_LABELS = {+ all: 'All',+ avatar: 'Avatars',+ agent: 'Agents',+ model: 'Models',+ world: 'Worlds',+ coin: 'Coins',+};++const TYPE_CREATE_CTA = {+ avatar: { label: 'Create an avatar', href: '/create-avatar' },+ agent: { label: 'Create an agent', href: '/agent/new' },+ model: { label: 'Forge a 3D model', href: '/forge' },+ world: { label: 'Build a world', href: '/diorama' },+ coin: { label: 'Launch a coin', href: '/launch' },+};++const state = { q: '', type: 'all', loading: false, controller: null };++function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}++function cssEscape(s) {+ return typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(s) : String(s).replace(/["\\]/g, '\\$&');+}++function debounce(fn, ms) {+ let t;+ return (...args) => {+ clearTimeout(t);+ t = setTimeout(() => fn(...args), ms);+ };+}++function renderTypeChips() {+ const wrap = $('sr-types');+ if (!wrap) return;+ wrap.innerHTML = Object.entries(TYPE_LABELS)+ .map(+ ([key, label]) =>+ `<button type="button" class="sr-type-btn${key === state.type ? ' active' : ''}" data-type="${key}" aria-pressed="${key === state.type}">${label}</button>`,+ )+ .join('');+}++function cardThumb(item) {+ if (item.glbUrl) {+ return `<div class="sr-card-thumb"><model-viewer class="sr-card-mv" src="${esc(item.glbUrl)}" auto-rotate camera-controls disable-zoom loading="lazy" reveal="auto" exposure="1.1"></model-viewer></div>`;+ }+ if (item.image) {+ return `<div class="sr-card-thumb"><img class="sr-card-img" src="${esc(item.image)}" alt="" loading="lazy" /></div>`;+ }+ return `<div class="sr-card-thumb"><div class="sr-card-noimg">${esc((item.title || '?')[0]?.toUpperCase() || '?')}</div></div>`;+}++function cardHtml(item) {+ const followers = item.signals?.followerCount;+ const creator = item.creator+ ? `<a class="sr-card-creator" href="${esc(item.creator.url || '#')}"${item.creator.url ? '' : ' aria-disabled="true" tabindex="-1"'}>${esc(item.creator.label)}</a>${+ typeof followers === 'number' ? `<span class="sr-card-followers">· ${followers} follower${followers === 1 ? '' : 's'}</span>` : ''+ }`+ : '';+ const remixBtn = item.remix+ ? `<button class="sr-card-btn sr-card-btn--remix" type="button" data-remix-open="${esc(item.id)}">Remix — $${item.remix.priceUsd.toFixed(2)}</button>`+ : '';+ const remixInline = item.remix+ ? `<div class="sr-remix-inline" data-remix-inline="${esc(item.id)}">+ <input type="text" class="sr-remix-input" placeholder='Describe the change, e.g. "make it metallic"' maxlength="500" />+ <button class="sr-card-btn sr-card-btn--remix" type="button" data-remix-pay="${esc(item.id)}" data-remix-glb="${esc(item.glbUrl || '')}">Pay & remix</button>+ <div class="sr-remix-status" role="status" aria-live="polite"></div>+ </div>`+ : '';+ return `+ <article class="sr-card" data-item-id="${esc(item.id)}">+ <a href="${esc(item.assetUrl || '#')}" target="${item.assetUrl?.startsWith('http') ? '_blank' : '_self'}" rel="noopener noreferrer">${cardThumb(item)}</a>+ <span class="sr-card-type">${esc(item.type)}</span>+ <div class="sr-card-body">+ <h3 class="sr-card-title"><a href="${esc(item.assetUrl || '#')}" target="${item.assetUrl?.startsWith('http') ? '_blank' : '_self'}" rel="noopener noreferrer">${esc(item.title)}</a></h3>+ ${item.description ? `<p class="sr-card-desc">${esc(item.description)}</p>` : ''}+ <div class="sr-card-meta">${creator}</div>+ <div class="sr-card-actions">+ <a class="sr-card-btn" href="${esc(item.assetUrl || '#')}" target="${item.assetUrl?.startsWith('http') ? '_blank' : '_self'}" rel="noopener noreferrer">View</a>+ ${remixBtn}+ </div>+ ${remixInline}+ </div>+ </article>`;+}++function emptyStateHtml() {+ if (!state.q) {+ return '';+ }+ const cta = state.type !== 'all' && TYPE_CREATE_CTA[state.type] ? TYPE_CREATE_CTA[state.type] : null;+ const ctas = Object.values(TYPE_CREATE_CTA);+ return `+ <div class="sr-empty">+ <div class="sr-empty-title">Nothing matched "${esc(state.q)}"</div>+ <p class="sr-empty-sub">Try a broader term, switch type filters, or be the first to make one.</p>+ <div class="sr-empty-ctas">+ ${cta ? `<a class="sr-card-btn sr-card-btn--remix" href="${cta.href}">${esc(cta.label)}</a>` : ctas.map((c) => `<a class="sr-card-btn" href="${c.href}">${esc(c.label)}</a>`).join('')}+ </div>+ </div>`;+}++function skeletonHtml(n = 8) {+ return Array.from({ length: n }, () => '<div class="sr-skeleton"></div>').join('');+}++async function runSearch() {+ const grid = $('sr-grid');+ const countEl = $('sr-count');+ if (!grid) return;+ state.controller?.abort();+ const controller = new AbortController();+ state.controller = controller;+ state.loading = true;++ if (!state.q) {+ grid.innerHTML = '';+ if (countEl) countEl.textContent = '';+ $('sr-quicklinks')?.removeAttribute('hidden');+ state.loading = false;+ return;+ }+ $('sr-quicklinks')?.setAttribute('hidden', '');+ grid.setAttribute('aria-busy', 'true');+ grid.innerHTML = skeletonHtml();++ try {+ const params = new URLSearchParams({ q: state.q, type: state.type, limit: '24' });+ const res = await fetch(`/api/search?${params}`, { signal: controller.signal, headers: { accept: 'application/json' } });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(data?.message || `search returned ${res.status}`);+ if (controller.signal.aborted) return;++ const items = Array.isArray(data.items) ? data.items : [];+ if (countEl) {+ countEl.textContent = items.length+ ? `${items.length} result${items.length === 1 ? '' : 's'} for "${state.q}"`+ : '';+ }+ grid.innerHTML = items.length ? items.map(cardHtml).join('') : emptyStateHtml();+ } catch (err) {+ if (controller.signal.aborted) return;+ grid.innerHTML = `<div class="sr-error"><div class="sr-empty-title">Search is temporarily unavailable</div><p>${esc(err?.message || 'Please try again.')} — <a href="#" data-retry>Retry</a></p></div>`;+ } finally {+ grid.removeAttribute('aria-busy');+ state.loading = false;+ }+}++const debouncedSearch = debounce(runSearch, 300);++function wireControls() {+ renderTypeChips();+ const input = $('sr-q');+ input?.addEventListener('input', (e) => {+ state.q = e.target.value.trim();+ history.replaceState(null, '', state.q ? `?q=${encodeURIComponent(state.q)}${state.type !== 'all' ? `&type=${state.type}` : ''}` : location.pathname);+ debouncedSearch();+ });+ $('sr-types')?.addEventListener('click', (e) => {+ const btn = e.target.closest('[data-type]');+ if (!btn) return;+ state.type = btn.dataset.type;+ renderTypeChips();+ if (state.q) runSearch();+ });+ $('sr-grid')?.addEventListener('click', (e) => {+ if (e.target.closest('[data-retry]')) {+ e.preventDefault();+ runSearch();+ return;+ }+ const openId = e.target.closest('[data-remix-open]')?.dataset.remixOpen;+ if (openId) {+ const inline = document.querySelector(`[data-remix-inline="${cssEscape(openId)}"]`);+ inline?.classList.toggle('is-open');+ if (inline?.classList.contains('is-open')) inline.querySelector('input')?.focus();+ return;+ }+ const payId = e.target.closest('[data-remix-pay]')?.dataset.remixPay;+ if (payId) return remixOne(payId, e.target.closest('.sr-card'));+ });+}++async function remixOne(sourceId, cardEl) {+ const inline = cardEl?.querySelector('[data-remix-inline]');+ const input = inline?.querySelector('.sr-remix-input');+ const statusEl = inline?.querySelector('.sr-remix-status');+ const payBtn = cardEl?.querySelector(`[data-remix-pay="${cssEscape(sourceId)}"]`);+ const instruction = input?.value.trim();+ if (!instruction) {+ if (statusEl) statusEl.textContent = 'Describe the change first.';+ return;+ }+ if (payBtn) payBtn.disabled = true;+ if (statusEl) {+ statusEl.textContent = 'Opening payment…';+ statusEl.dataset.kind = 'busy';+ }+ try {+ const X402 = await ensureX402();+ const out = await X402.pay({+ endpoint: '/api/x402/remix-asset',+ method: 'POST',+ body: { source_creation_id: sourceId, instruction },+ merchant: 'three.ws Remix Bazaar',+ action: 'Remix this model — $0.25 USDC (a royalty routes to its creator)',+ });+ const remix = out?.result?.remix;+ const royalty = out?.result?.royalty;+ if (statusEl) {+ statusEl.dataset.kind = 'done';+ statusEl.innerHTML = remix?.viewerUrl+ ? `Remixed! <a href="${esc(remix.viewerUrl)}" target="_blank" rel="noopener noreferrer">View your new model →</a>` ++ (royalty?.paid ? ` · $${royalty.creatorUsd} routed to the original creator.` : '')+ : 'Remix submitted.';+ }+ if (input) input.value = '';+ } catch (err) {+ if (statusEl) {+ statusEl.dataset.kind = 'error';+ statusEl.textContent = err?.message || 'Remix failed. Try again.';+ }+ } finally {+ if (payBtn) payBtn.disabled = false;+ }+}++function initFromUrl() {+ const params = new URLSearchParams(location.search);+ const q = (params.get('q') || '').trim();+ const type = params.get('type');+ if (q) {+ state.q = q;+ const input = $('sr-q');+ if (input) input.value = q;+ }+ if (type && TYPE_LABELS[type]) state.type = type;+}++document.addEventListener('DOMContentLoaded', () => {+ wireControls();+ initFromUrl();+ if (state.q) runSearch();+ else $('sr-quicklinks')?.removeAttribute('hidden');+});diff --git a/tests/api/search.test.js b/tests/api/search.test.jsnew file mode 100644index 000000000..d5ff4a8d2--- /dev/null+++ b/tests/api/search.test.js@@ -0,0 +1,173 @@+// Unit tests for GET /api/search — the cross-entity discovery endpoint+// (prompts/user-value/05-discovery-search.md). Mocks the five source+// functions in api/_lib/cross-search.js (each already unit-testable on its+// own via the stores it wraps) and asserts the endpoint's own job: fan-out+// wiring, type filtering, ranking/merge, and degrade-cleanly-without-a-db.+// All offline — no DATABASE_URL or Redis needed.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const dbState = { configured: true };+vi.mock('../../api/_lib/env.js', () => ({+ databaseConfigured: () => dbState.configured,+ env: {},+}));++const storeState = { forge: true, diorama: true };+vi.mock('../../api/_lib/forge-store.js', () => ({+ forgeStoreEnabled: () => storeState.forge,+}));+vi.mock('../../api/_lib/diorama-store.js', () => ({+ dioramaStoreEnabled: () => storeState.diorama,+}));++const rlState = { success: true };+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { publicIp: vi.fn(async () => rlState) },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++const mocks = {+ searchAvatars: vi.fn(async () => []),+ searchAgents: vi.fn(async () => []),+ searchModels: vi.fn(async () => []),+ searchWorlds: vi.fn(async () => []),+ searchCoins: vi.fn(async () => []),+ attachFollowerCounts: vi.fn(async (items) => items),+ rankItems: vi.fn((items) => items),+};+vi.mock('../../api/_lib/cross-search.js', () => mocks);++const { default: searchHandler } = await import('../../api/search.js');++function makeReq(query = {}) {+ return { method: 'GET', headers: {}, url: `/api/search?${new URLSearchParams(query)}` };+}+function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(body) { this._body = body; },+ };+}+async function call(query) {+ const req = makeReq(query);+ const res = makeRes();+ await searchHandler(req, res);+ let body = null;+ try { body = JSON.parse(res._body); } catch {}+ return { res, body };+}++function item(type, id, extra = {}) {+ return { type, id, title: `${type} ${id}`, description: '', image: null, glbUrl: null, assetUrl: `/${type}/${id}`, creator: null, remix: null, createdAt: new Date().toISOString(), signals: {}, ...extra };+}++beforeEach(() => {+ dbState.configured = true;+ storeState.forge = true;+ storeState.diorama = true;+ rlState.success = true;+ for (const key of ['searchAvatars', 'searchAgents', 'searchModels', 'searchWorlds', 'searchCoins']) {+ mocks[key].mockReset().mockResolvedValue([]);+ }+ mocks.attachFollowerCounts.mockReset().mockImplementation(async (items) => items);+ mocks.rankItems.mockReset().mockImplementation((items) => items);+});++describe('GET /api/search', () => {+ it('spans at least two creation types for a single query', async () => {+ mocks.searchAvatars.mockResolvedValue([item('avatar', 'a1')]);+ mocks.searchModels.mockResolvedValue([item('model', 'm1', { remix: { endpoint: '/api/x402/remix-asset', sourceCreationId: 'm1', priceUsd: 0.25 } })]);++ const { res, body } = await call({ q: 'dragon' });++ expect(res.statusCode).toBe(200);+ expect(body.enabled).toBe(true);+ const types = new Set(body.items.map((i) => i.type));+ expect(types.has('avatar')).toBe(true);+ expect(types.has('model')).toBe(true);+ expect(body.items).toHaveLength(2);+ });++ it('every result carries an assetUrl and a remixable model carries a working remix action', async () => {+ mocks.searchModels.mockResolvedValue([+ item('model', 'm1', {+ assetUrl: 'https://three.ws/viewer?src=x',+ creator: { label: '@maker', url: '/u/maker' },+ remix: { endpoint: '/api/x402/remix-asset', sourceCreationId: 'm1', priceUsd: 0.25, royaltyPercent: 5, royaltyPayable: true },+ }),+ ]);++ const { body } = await call({ q: 'sneaker', type: 'model' });++ expect(body.items).toHaveLength(1);+ const [m] = body.items;+ expect(m.assetUrl).toBeTruthy();+ expect(m.creator.url).toBe('/u/maker');+ expect(m.remix.endpoint).toBe('/api/x402/remix-asset');+ expect(m.remix.sourceCreationId).toBe('m1');+ });++ it('scopes to one type when type= is set and skips the others', async () => {+ mocks.searchAvatars.mockResolvedValue([item('avatar', 'a1')]);++ await call({ q: 'x', type: 'avatar' });++ expect(mocks.searchAvatars).toHaveBeenCalled();+ expect(mocks.searchAgents).not.toHaveBeenCalled();+ expect(mocks.searchModels).not.toHaveBeenCalled();+ expect(mocks.searchWorlds).not.toHaveBeenCalled();+ expect(mocks.searchCoins).not.toHaveBeenCalled();+ });++ it('never queries coins without a search term (no "browse all coins" concept here)', async () => {+ await call({ type: 'coin' });+ expect(mocks.searchCoins).not.toHaveBeenCalled();+ });++ it('skips models/worlds when their stores are unconfigured, without erroring', async () => {+ storeState.forge = false;+ storeState.diorama = false;+ mocks.searchAvatars.mockResolvedValue([item('avatar', 'a1')]);++ const { res, body } = await call({ q: 'x' });++ expect(res.statusCode).toBe(200);+ expect(mocks.searchModels).not.toHaveBeenCalled();+ expect(mocks.searchWorlds).not.toHaveBeenCalled();+ expect(body.items.some((i) => i.type === 'avatar')).toBe(true);+ });++ it('degrades to an empty, non-throwing result when no database is configured', async () => {+ dbState.configured = false;++ const { res, body } = await call({ q: 'x' });++ expect(res.statusCode).toBe(200);+ expect(body.enabled).toBe(false);+ expect(body.items).toEqual([]);+ expect(mocks.searchAvatars).not.toHaveBeenCalled();+ });++ it('an empty query returns no items without erroring (client renders the idle/browse state)', async () => {+ const { res, body } = await call({});+ expect(res.statusCode).toBe(200);+ expect(body.items).toEqual([]);+ });++ it('trims whitespace and caps q length before it reaches any query', async () => {+ await call({ q: ' dragon ' + 'x'.repeat(100) });+ const [args] = mocks.searchAvatars.mock.calls;+ expect(args[0].q.startsWith('dragon')).toBe(true);+ expect(args[0].q.length).toBeLessThanOrEqual(80);+ });++ it('rate limits like other public discovery endpoints', async () => {+ rlState.success = false;+ const { res } = await call({ q: 'x' });+ expect(res.statusCode).toBe(429);+ });+});