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(spotlight): give each entry its own readable page and rename the showcase API to match the surface
nirholas591e7b441a64
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex b4fe91cea..ddc630681 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -122,7 +122,7 @@ bottom.| Home page event strip (`/`) | Self-attaching module [src/home-event-banner.js](src/home-event-banner.js) loaded by [pages/home.html](pages/home.html); same config `public/event.json` through [src/shared/event-config.js](src/shared/event-config.js) | Live | Puts the live event in front of everyone who lands on three.ws, not just the people who already opened `/play`. A slim announcement bar between the nav and the hero: event name, start time in the visitor's own timezone, a countdown ticking to the second, and one CTA into the $THREE world (suppressed when the visitor is already there). Same three states as the `/play` surfaces and the same auto-unmount at `endsAt`, flipping upcoming to live without a reload. Dismissal shares the `/play` pill's `cc-event-dismissed:<startsAt>` key, so waving the reminder away on the home page also clears it in-world; the `/play` lobby banner stays, because it is lobby content rather than an overlay. Styled from the home page's own tokens (mono kicker, hairline pill CTA) and light-theme aware. Verified with `npm run verify:event`. || `/play` friends, presence & verified profiles (drawer, cross-world DMs, in-world profile cards) | Client: [src/game/friends-panel.js](src/game/friends-panel.js) (shared with `/walk`), mounted in [src/game/coincommunities.js](src/game/coincommunities.js) `_openFriends()`/`_closeFriends()`, HUD button + unread badge in [src/game/coincommunities-ui.js](src/game/coincommunities-ui.js), account-level state/polling in [src/friends.js](src/friends.js), profile card in the shared inspector [src/shared/avatar-inspector.js](src/shared/avatar-inspector.js) (`renderProfile`). Server: signed ticket verify + `socialHub` registration + verified `username` on the Player schema in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) + [multiplayer/src/schemas.js](multiplayer/src/schemas.js), ticket signer [api/_lib/presence-store.js](api/_lib/presence-store.js) / verifier [multiplayer/src/presence-token.js](multiplayer/src/presence-token.js), hub in [multiplayer/src/social-hub.js](multiplayer/src/social-hub.js) | In-repo | W09+W10 of the World Online program (program brief retired to git history). Press `J` or the HUD `Friends` button to open a right-docked drawer showing your account's friend graph; live online/offline presence per coin world, requests, and DM threads; the same graph and threads `/walk` and the standalone `/friends` page already share. `community-net.js` carries a signed presence ticket into every `walk_world` join and forwards the server's `social` push onto its own event bus, which is what makes a `/play` player visible to friends and able to receive a live DM. W10 makes the platform identity first-class in-world: the ticket also carries the account's username + display name (signed, so nobody can wear a handle they don't own), WalkRoom publishes the verified `username` on the Player schema, nameplates show the @handle, the signed-in lobby defaults to the account's display name with an @handle chip, and clicking any verified player (or `I`) opens their real three.ws profile card in the shared avatar inspector: bio, follower counts, follow/unfollow (`/api/users/:username/follow`), the right friends verb (Message → the in-world DM drawer when already friends, Add friend / Accept otherwise), their latest creations, and a link to `/u/<username>`. Works identically in `/walk` (same room, same inspector). Tests: [tests/play-friends-presence.test.js](tests/play-friends-presence.test.js), [tests/play-profile-identity.test.js](tests/play-profile-identity.test.js). || Crew HQ (crews, tags, 3D presence room) | Page [pages/crews.html](pages/crews.html) + [src/crews-page.js](src/crews-page.js) + [src/crews.css](src/crews.css) `→ /crews` and `/crews/<TAG>`, data layer [api/_lib/crews-store.js](api/_lib/crews-store.js), endpoints [api/crews/](api/crews) (`index.js`, `[tag].js`, `search.js`, `directory.js`), presence [api/_lib/presence-store.js](api/_lib/presence-store.js), schema `api/_lib/migrations/2026-06-05-crews.sql` | Live | The group half of the social system: a crew is a set of accounts flying one 2-6 character tag, with one owner, one crew per account, and a public headquarters. The HQ renders the roster as a room rather than a list, each member standing as their own agent's 3D avatar (resolved by `standeesFor()`, private models never emitted) and lit by the same Redis presence the friends drawer reads. Crew colour is an FNV-1a hash of the tag, so a crew looks like itself everywhere without stored art. Live `<agent-3d>` figures are capped and lazily mounted so a large crew cannot exhaust the browser's WebGL contexts. The backend shipped with W09 and had no UI at all until this page; the in-world friends drawer now links to it. Docs: [docs/crews.md](docs/crews.md). Tests: [tests/crews-shared.test.js](tests/crews-shared.test.js), [tests/crews-wiring.test.js](tests/crews-wiring.test.js) |-| Agent Spotlight (community showcase) | Page [pages/spotlight.html](pages/spotlight.html) + [src/spotlight.js](src/spotlight.js) + [src/spotlight.css](src/spotlight.css) `→ /spotlight`, HTTP boundary [api/showcase/[action].js](api/showcase), queries + ranking [api/_lib/showcase-store.js](api/_lib/showcase-store.js), schema `api/_lib/migrations/20260901160000_agent_showcase.sql`, curated seed [scripts/seed-showcase.mjs](scripts/seed-showcase.mjs) | Live | The curated half of `/agents`: the index lists every agent ever registered, this lists the ones a person wrote up and the community voted on. An entry stores the pitch only (headline, one-liner, write-up, category, tags, demo link); the agent's name, avatar, skills, on-chain identity, conversation count and builder are read live off `agent_identities` on every request, so a card can never drift from the agent it points at. Ranked by `(votes + 1) / (age_days + 1) ^ 1.2`, computed identically in JS and in the SQL `ORDER BY`; the `+ 1` keeps a brand-new entry on the first page, and the day scale (rather than the hour scale every feed copies from Hacker News) is what stops a low-volume board's `trending` from collapsing into `newest`. One entry per agent (re-submitting edits it), one vote per account, votes counted on read rather than denormalised. Entries badged `Curated` were written by three.ws about someone else's public agent and are replaced the moment that builder submits their own. Docs: [docs/spotlight.md](docs/spotlight.md). Tests: [tests/showcase-ranking.test.js](tests/showcase-ranking.test.js) |+| Agent Spotlight (community showcase) | Index [pages/spotlight.html](pages/spotlight.html) + [src/spotlight.js](src/spotlight.js) `→ /spotlight`, entry page [pages/spotlight-entry.html](pages/spotlight-entry.html) + [src/spotlight-entry.js](src/spotlight-entry.js) `→ /spotlight/:id`, shared render + form modules [src/spotlight-shared.js](src/spotlight-shared.js) / [src/spotlight-form.js](src/spotlight-form.js), styles [src/spotlight.css](src/spotlight.css), crawler share cards [api/spotlight-og.js](api/spotlight-og.js), HTTP boundary [api/spotlight/[action].js](api/spotlight), queries + ranking [api/_lib/spotlight-store.js](api/_lib/spotlight-store.js), schema `api/_lib/migrations/20260901160000_agent_showcase.sql`, curated seed [scripts/seed-spotlight.mjs](scripts/seed-spotlight.mjs) | Live | The curated half of `/agents`: the index lists every agent ever registered, this lists the ones a person wrote up and the community voted on. An entry stores the pitch only (headline, one-liner, write-up, category, tags, demo link); the agent's name, avatar, skills, on-chain identity, conversation count and builder are read live off `agent_identities` on every request, so a card can never drift from the agent it points at. Ranked by `(votes + 1) / (age_days + 1) ^ 1.2`, computed identically in JS and in the SQL `ORDER BY`; the `+ 1` keeps a brand-new entry on the first page, and the day scale (rather than the hour scale every feed copies from Hacker News) is what stops a low-volume board's `trending` from collapsing into `newest`. One entry per agent (re-submitting edits it), one vote per account, votes counted on read rather than denormalised. Entries badged `Curated` were written by three.ws about someone else's public agent, say so in words on the entry page, and are replaced the moment that builder submits their own. The API lives at `/api/spotlight/*` because `/api/showcase` is the unrelated ERC-8004 directory ([api/showcase.js](api/showcase.js)); the tables keep the `agent_showcase` name they were applied under. Docs: [docs/spotlight.md](docs/spotlight.md). Tests: [tests/spotlight-ranking.test.js](tests/spotlight-ranking.test.js) || `/play` Robinhood Chain worlds (NOXA + The Odyssey coins, live-trade animation) | Firehose worker [workers/robinhood-feed/](workers/robinhood-feed) (watches NOXA + Odyssey launchpads + their Uniswap v3 pools, normalizes to the pump-compatible event shape, serves SSE/WS/REST). API bridge: [api/robinhood/coin-trades.js](api/robinhood/coin-trades.js) (the in-world chart-screen's trade feed), [api/robinhood/play-worlds.js](api/robinhood/play-worlds.js) (the `/worlds` lobby's Robinhood Chain tab). Client: chain-flavored biome `hoodchain` in [src/game/world-env.js](src/game/world-env.js) (auto-pinned in [src/game/coincommunities.js](src/game/coincommunities.js) `isRobinhoodCoin()`), trade-feed endpoint routing in [src/game/chart-screen.js](src/game/chart-screen.js), lobby tab + EVM-address support in [src/worlds-lobby.js](src/worlds-lobby.js) (routes Robinhood coins to `/play`, unchanged pump.fun coins stay on `/temporary`) | In-repo | Every Robinhood Chain memecoin (chain 4663) gets the same treatment pump.fun coins already have: a deterministic 3D world seeded by its contract address, in a distinct dark ticker-tape palette, with real launchpad/Uniswap-v3 trades rippling the space live via `MarketReactor`. Multiplayer (`walk_world`, filtered by `coin`+`tier`) needed zero code changes — it already keys rooms by an opaque coin id string. `isValidToken()` in [api/_lib/coin-communities.js](api/_lib/coin-communities.js) was widened to accept EVM addresses (it previously 400'd every EVM-chain world's Town chat, even though the CHAINS list already declared ethereum/base/bsc support). Tests: [workers/robinhood-feed/tests/normalize.test.js](workers/robinhood-feed/tests/normalize.test.js) (against real captured on-chain logs). || Sealed wallet gift drops (send/claim) | Client: [src/pages/sealed-drops.js](src/pages/sealed-drops.js) — create + "My drops" sections mounted into [public/vanity-wallet.html](public/vanity-wallet.html) (`#drop-create`/`#drop-mine`, below the vanity grinder — vanity pattern fields are shared), claim flow on its own page [pages/drop.html](pages/drop.html) `→ /drop/:id` (24-hex-char id, routed in [vite.config.js](vite.config.js) dev middleware + [vercel.json](vercel.json)). Crypto: [src/solana/vanity/sealed-envelope.js](src/solana/vanity/sealed-envelope.js) (ECIES seal/open, X25519 keygen — all client-side, three.ws never sees a plaintext key), [src/solana/vanity/drop-protocol.js](src/solana/vanity/drop-protocol.js) (claim-token derivation). Server: [api/vanity/drops.js](api/vanity/drops.js) (create/claim/reveal/reclaim, on-chain funding), OG card [api/og/sealed-drop.js](api/og/sealed-drop.js) | In-repo | Fund a fresh wallet — optionally vanity-ground with the same prefix/suffix grinder above — wrap it in a sealed link, and send it. Two seal modes: a **bearer link** (the claim key rides in the URL fragment, anyone with the full link claims once) or **sealed to a recipient's X25519 key** (only they can ever open it, even with the link). The create fee settles via x402; the gift amount funds on-chain into a fresh wallet server-side. Claiming decrypts entirely in the browser and offers the recovered seed phrase/secret key for import — the server only ever sees the sealed ciphertext. "My drops" (browser-local, by a random sender tag) lists what you've sent so expired-unclaimed gifts can be reclaimed. || Premium vanity inventory (sell pre-ground addresses) | [public/vanity/premium/](public/vanity/premium/index.html) `→ /vanity/premium`, batch grinder [workers/vanity-grinder/](workers/vanity-grinder), store [api/_lib/vanity-inventory-store.js](api/_lib/vanity-inventory-store.js), sell [api/x402/vanity-premium.js](api/x402/vanity-premium.js), replenish [api/cron/vanity-inventory-replenish.js](api/cron/vanity-inventory-replenish.js) | In-repo · GCP spot CPU | Long (4–5+ char) brandable Solana addresses ground ahead of time on cheap spot CPU, sealed at rest (AES-256-GCM or GCP-KMS envelope, [api/_lib/vanity-vault.js](api/_lib/vanity-vault.js)), and sold from stock via x402 — priced by rarity ($1–$50) on `vanity-premium`, or by fixed 4–5 char tiers ($2.50/$10) directly through [`/api/x402/vanity`](docs/vanity.md#tier-1--live-grinder) (instant delivery, `source:"inventory"`) and the [pump-launch vanity upsell](docs/pump-launcher.md) — delivered exactly once, ciphertext destroyed on delivery. An hourly cron watches stock and fires a fresh grind batch (Cloud Run Job) when low. Free `vanity_premium` MCP browse tool. Runbook: [docs/ops/gcp-credits.md](docs/ops/gcp-credits.md) |diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex b213a8a3e..6d3484b0b 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -1228,7 +1228,7 @@ export const limits = {getLimiter('bounty:create', { limit: 15, window: '1 h' }).limit(userId),bountySubmit: (userId) =>getLimiter('bounty:submit', { limit: 40, window: '1 h' }).limit(userId),- // Agent Spotlight (api/showcase/[action].js). Writing a showcase entry is a+ // Agent Spotlight (api/spotlight/[action].js). Writing a showcase entry is a// considered act (a builder does it once per agent and edits it a few times),// so the create bucket is deliberately tight. Voting is a browse-time// gesture down a long page, so it gets a much wider one; both are keyed ondiff --git a/api/_lib/showcase-store.js b/api/_lib/spotlight-store.jssimilarity index 95%rename from api/_lib/showcase-store.jsrename to api/_lib/spotlight-store.jsindex 006429dec..409460ca0 100644--- a/api/_lib/showcase-store.js+++ b/api/_lib/spotlight-store.js@@ -6,6 +6,12 @@// agent_identities/avatars/users on each query, so an entry can never show a// stale name or a deleted avatar. See the migration// 20260901160000_agent_showcase.sql for the same reasoning at the schema level.+//+// Naming: the HTTP surface and this module are "spotlight" because /api/showcase+// was already taken by an unrelated public endpoint (the ERC-8004 directory in+// api/showcase.js, documented in docs/showcase.md). The TABLES stay+// `agent_showcase` / `agent_showcase_votes`: they are applied in production, and+// renaming a live table to match a module name is not a trade worth making.import { sql } from './db.js';import { env } from './env.js';@@ -209,7 +215,15 @@ export async function listEntries({then (coalesce(v.n, 0) + 1)::numeric/ power(extract(epoch from (now() - s.created_at))::numeric / 86400.0 + 1, ${GRAVITY}::numeric)end desc nulls last,- s.created_at desc+ s.created_at desc,+ -- A board seeded in one batch, or two entries published the same+ -- minute, ties on every clause above and would then order by whatever+ -- the planner happened to return: the same query gives a different+ -- page each time, which reads as a bug. Break the tie on the agent's+ -- own activity (it is the most useful thing to lead with among equals)+ -- and finally on id, so the order is total and stable.+ (coalesce(ch.n, 0) + coalesce(ac.n, 0)) desc,+ s.idlimit ${limit} offset ${offset}`;const now = Date.now();diff --git a/api/spotlight-og.js b/api/spotlight-og.jsnew file mode 100644index 000000000..51c3b72ca--- /dev/null+++ b/api/spotlight-og.js@@ -0,0 +1,151 @@+/**+ * SSR OG page for an Agent Spotlight entry (/spotlight/:id)+ * ---------------------------------------------------------+ * GET /api/spotlight-og?id=<entryId>+ *+ * Wired via vercel.json: when a social crawler hits /spotlight/<uuid>, a+ * User-Agent "has" condition rewrites here. The entry page itself is client+ * rendered, so without this every shared write-up would unfurl as the generic+ * showcase page: same title, same image, for all of them. A showcase whose links+ * do not unfurl is a showcase nobody shares.+ *+ * Real browsers never reach this route. Mirrors api/agent-detail-og.js.+ *+ * The card image is the agent's own trading card (api/og/agent.js), because the+ * subject of the share is that agent; the headline and one-liner supply the+ * text. That pairing is why this does not need an image renderer of its own.+ */++import { sql } from './_lib/db.js';+import { cors, method, wrap } from './_lib/http.js';+import { env } from './_lib/env.js';+import { isUuid } from './_lib/validate.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const url = new URL(req.url, 'http://x');+ const id = url.searchParams.get('id');+ const origin = env.APP_ORIGIN || 'https://three.ws';++ if (!id || !isUuid(id)) return passthrough(res, origin);++ let entry;+ try {+ [entry] = await sql`+ select s.id, s.title, s.tagline, s.source, s.category,+ i.id as agent_id, i.name as agent_name,+ u.display_name as builder_display_name, u.username as builder_username+ from agent_showcase s+ join agent_identities i on i.id = s.agent_id and i.deleted_at is null and i.is_public = true+ left join users u on u.id = i.user_id and u.deleted_at is null+ where s.id = ${id} and s.deleted_at is null and s.status = 'published'+ limit 1+ `;+ } catch {+ return passthrough(res, origin);+ }+ if (!entry) return passthrough(res, origin);++ const builder = entry.builder_display_name || entry.builder_username || null;+ const credit =+ entry.source === 'curated'+ ? `${entry.agent_name} on three.ws${builder ? `, built by ${builder}` : ''}.`+ : `${entry.agent_name} on three.ws${builder ? `, by ${builder}` : ''}.`;++ const pageUrl = `${origin}/spotlight/${entry.id}`;+ const ogImage = `${origin}/api/og/agent?id=${encodeURIComponent(entry.agent_id)}`;++ res.statusCode = 200;+ res.setHeader('content-type', 'text/html; charset=utf-8');+ res.setHeader('cache-control', 'public, max-age=60, s-maxage=600, stale-while-revalidate=3600');+ res.end(+ renderHtml({+ entryId: entry.id,+ title: entry.title,+ desc: `${entry.tagline} ${credit}`,+ agentName: entry.agent_name,+ pageUrl,+ ogImage,+ origin,+ }),+ );+});++function passthrough(res, origin) {+ res.statusCode = 302;+ res.setHeader('location', `${origin}/spotlight`);+ res.setHeader('cache-control', 'no-cache');+ res.end();+}++function renderHtml({ entryId, title, desc, agentName, pageUrl, ogImage, origin }) {+ const t = esc(title);+ const d = esc(desc);+ const entryUrl = `/spotlight/${entryId}`;+ return `<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <title>${t} — Agent Spotlight — three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">+ <meta name="description" content="${d}">+ <meta name="theme-color" content="#06070a">++ <meta property="og:type" content="article">+ <meta property="og:site_name" content="three.ws">+ <meta property="og:title" content="${t}">+ <meta property="og:description" content="${d}">+ <meta property="og:url" content="${esc(pageUrl)}">+ <meta property="og:image" content="${esc(ogImage)}">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta property="og:image:alt" content="${esc(agentName)} on three.ws">++ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:site" content="@trythreews">+ <meta name="twitter:title" content="${t}">+ <meta name="twitter:description" content="${d}">+ <meta name="twitter:image" content="${esc(ogImage)}">++ <meta property="fc:frame" content="vNext">+ <meta property="fc:frame:image" content="${esc(ogImage)}">+ <meta property="fc:frame:image:aspect_ratio" content="1.91:1">+ <meta property="fc:frame:button:1" content="Meet ${esc(agentName)}">+ <meta property="fc:frame:button:1:action" content="link">+ <meta property="fc:frame:button:1:target" content="${esc(pageUrl)}">++ <link rel="canonical" href="${esc(pageUrl)}">+ <link rel="shortcut icon" href="/favicon.ico">++ <style>+ html,body{margin:0;padding:0;background:#06070a;color:#e0e0e0;font-family:Inter,system-ui,sans-serif;height:100%}+ .shell{display:grid;place-items:center;min-height:100vh;text-align:center;padding:2rem;gap:1rem}+ .shell a{color:#e0e0e0;text-decoration:underline;text-underline-offset:3px}+ p{margin:0;color:rgba(255,255,255,0.5);font-size:14px}+ </style>+</head>+<body>+ <noscript>+ <div class="shell">+ <h1>${t}</h1>+ <p>${d}</p>+ <p><a href="${esc(pageUrl)}">Read the write-up</a> · <a href="${esc(origin)}/spotlight">Agent Spotlight</a></p>+ </div>+ </noscript>+ <div class="shell" aria-live="polite">+ <p>Loading ${t}…</p>+ </div>+ <script>(function(){window.location.replace(${JSON.stringify(entryUrl)});})()</script>+</body>+</html>`;+}++function esc(value) {+ return String(value ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}diff --git a/api/showcase/[action].js b/api/spotlight/[action].jssimilarity index 93%rename from api/showcase/[action].jsrename to api/spotlight/[action].jsindex cdabfed95..fa3ed72d9 100644--- a/api/showcase/[action].js+++ b/api/spotlight/[action].js@@ -1,15 +1,15 @@-// api/showcase/[action]: Agent Spotlight, the community showcase.+// api/spotlight/[action]: Agent Spotlight, the community showcase.//-// GET /api/showcase/list?sort=trending|new|top&category=&tag=&q=&limit=&offset=&featured=1-// GET /api/showcase/get?id=<uuid>-// GET /api/showcase/categories (per-category counts + headline totals)-// GET /api/showcase/eligible (auth: the caller's showcasable agents)-// POST /api/showcase/submit { agentId, title, tagline, story?, demoUrl?, category, tags[] }-// POST /api/showcase/vote { id } (toggle)-// POST /api/showcase/remove { id } (submitter or agent owner)+// GET /api/spotlight/list?sort=trending|new|top&category=&tag=&q=&limit=&offset=&featured=1+// GET /api/spotlight/get?id=<uuid>+// GET /api/spotlight/categories (per-category counts + headline totals)+// GET /api/spotlight/eligible (auth: the caller's showcasable agents)+// POST /api/spotlight/submit { agentId, title, tagline, story?, demoUrl?, category, tags[] }+// POST /api/spotlight/vote { id } (toggle)+// POST /api/spotlight/remove { id } (submitter or agent owner)//// Reads are public and CDN-cached; writes need a session plus CSRF. The ranking-// and every query live in api/_lib/showcase-store.js; this file is the HTTP+// and every query live in api/_lib/spotlight-store.js; this file is the HTTP// boundary and nothing else.import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';@@ -35,7 +35,7 @@ import {softDeleteEntry,toggleVote,upsertEntry,-} from '../_lib/showcase-store.js';+} from '../_lib/spotlight-store.js';const MAX_LIMIT = 48;@@ -63,7 +63,7 @@ export default wrap(async (req, res) => {case 'remove':return await handleRemove(req, res);default:- return error(res, 404, 'not_found', `unknown showcase action "${actionOf(req)}"`);+ return error(res, 404, 'not_found', `unknown spotlight action "${actionOf(req)}"`);}});diff --git a/docs/spotlight.md b/docs/spotlight.mdindex ecd3bde89..b6dd4aadf 100644--- a/docs/spotlight.md+++ b/docs/spotlight.md@@ -28,8 +28,28 @@ copy to go wrong.4. Optional: a write-up of up to 4,000 characters, a demo link, and tags.**One entry per agent.** Submitting again for the same agent edits the entry you-already have; it never creates a second card. You can remove your own entry at-any time, and so can the agent's owner if someone else wrote it up.+already have; it never creates a second card.++## The entry page++Every entry has its own page at `/spotlight/<entry id>`. That is where the+write-up is actually readable (the index can only show three clamped lines of+it), and it is the one place an entry is edited after it is created:++- the agent standing in 3D, live from its own GLB, with its still image held+ underneath until the viewer has painted so a model that fails to load degrades+ to the avatar rather than an empty stage,+- the full write-up as real paragraphs,+- a facts panel read live off the agent on every request: skills, conversations,+ on-chain actions, network, upvotes, views,+- share controls, and links into the agent in 3D, its profile, and AR,+- for the entry's owner (the submitter, or the agent's owner): **Edit entry** and+ **Remove**, the latter behind a two-step confirmation.++Owners reach the editor from a card's `Edit` link on the index, which deep-links+to `/spotlight/<id>?edit=1` and opens the form scrolled and focused. Both forms+are built by the same module, [`src/spotlight-form.js`](../src/spotlight-form.js),+so the create and edit paths cannot drift apart.## Ranking@@ -65,7 +85,7 @@ the front page. That is the behaviour a showcase wants: durable good work nearthe top, always room for the newest.The formula lives in one place,-[`trendingScore()` in `api/_lib/showcase-store.js`](../api/_lib/showcase-store.js),+[`trendingScore()` in `api/_lib/spotlight-store.js`](../api/_lib/spotlight-store.js),and the SQL `ORDER BY` computes the identical expression so the server neverdisagrees with its own documentation.@@ -82,13 +102,13 @@ agent record, and the moment they submit their own write-up for that agent itreplaces the curated one and the badge goes away.Curated entries are seeded by-[`scripts/seed-showcase.mjs`](../scripts/seed-showcase.mjs), which refuses to+[`scripts/seed-spotlight.mjs`](../scripts/seed-spotlight.mjs), which refuses toattach a write-up to an agent that has since been renamed, made private, ordeleted:```bash-node scripts/seed-showcase.mjs # dry run, reports what would land-node scripts/seed-showcase.mjs --apply # write the entries+node scripts/seed-spotlight.mjs # dry run, reports what would land+node scripts/seed-spotlight.mjs --apply # write the entries```## Categories@@ -103,7 +123,14 @@ aspirational taxonomy.Public reads, no key. Writes need a session cookie and a CSRF token, exactly likeevery other authenticated three.ws endpoint.-### `GET /api/showcase/list`+> The endpoints are `/api/spotlight/*`, not `/api/showcase/*`. `/api/showcase` was+> already taken by an unrelated public endpoint, the ERC-8004 agent directory+> behind [`/showcase`](showcase.md). The database tables are still named+> `agent_showcase` and `agent_showcase_votes`, which is deliberate: they are+> applied in production, and renaming a live table to match a module name is not+> a trade worth making.++### `GET /api/spotlight/list`| Param | Default | Notes || --- | --- | --- |@@ -116,7 +143,7 @@ every other authenticated three.ws endpoint.| `featured` | off | `1` returns only the editor's picks |```bash-curl -s 'https://three.ws/api/showcase/list?sort=top&limit=3' | jq '.entries[].title'+curl -s 'https://three.ws/api/spotlight/list?sort=top&limit=3' | jq '.entries[].title'``````json@@ -153,21 +180,23 @@ A signed-in read is personalised (`voted_by_me`) and returns`Cache-Control: private, no-store`; an anonymous read is identical for everyoneand is CDN-cached for 30 seconds.-### `GET /api/showcase/get?id=<uuid>`+### `GET /api/spotlight/get?id=<uuid>`-One entry, in the same shape, plus a view count bump.+One entry, in the same shape, plus a view count bump. This is what+`/spotlight/<id>` renders. `404` once the entry is removed or its agent stops+being public.-### `GET /api/showcase/categories`+### `GET /api/spotlight/categories`Per-category counts plus the headline totals the hero renders(`{ entries, builders, votes }`).-### `GET /api/showcase/eligible`+### `GET /api/spotlight/eligible`Session required. The caller's public agents that are not already showcased,plus the category list, which is what the submission form is built from.-### `POST /api/showcase/submit`+### `POST /api/spotlight/submit`Session + CSRF. Body:@@ -186,7 +215,7 @@ Session + CSRF. Body:Returns the created or updated entry. `403` if the agent is not yours, `409` ifit is not public.-### `POST /api/showcase/vote`+### `POST /api/spotlight/vote`Session + CSRF. Body `{ "id": "<entry uuid>" }`. Toggles, and returns theserver-confirmed state so the button never settles on an optimistic guess:@@ -195,22 +224,35 @@ server-confirmed state so the button never settles on an optimistic guess:{ "voted": true, "vote_count": 12 }```-### `POST /api/showcase/remove`+### `POST /api/spotlight/remove`Session + CSRF. Body `{ "id": "<entry uuid>" }`. Soft-deletes the entry. Allowed-for the submitter and for the agent's owner.+for the submitter and for the agent's owner. The agent is immediately eligible to+be showcased again.++## Sharing++A crawler that requests `/spotlight/<id>` is rewritten to+[`api/spotlight-og.js`](../api/spotlight-og.js), which renders the entry's+headline, one-liner and builder credit as OG, Twitter Card and Farcaster Frame+meta, with the agent's own live trading card (`/api/og/agent`) as the image. Real+browsers never touch that route. An unknown or removed entry redirects a crawler+to `/spotlight` rather than unfurling a 404.## Where the code lives| Piece | File || --- | --- |-| Page shell | [`pages/spotlight.html`](../pages/spotlight.html) |-| Controller | [`src/spotlight.js`](../src/spotlight.js) |+| Index page | [`pages/spotlight.html`](../pages/spotlight.html) + [`src/spotlight.js`](../src/spotlight.js) |+| Entry page | [`pages/spotlight-entry.html`](../pages/spotlight-entry.html) + [`src/spotlight-entry.js`](../src/spotlight-entry.js) |+| Shared card, stage and vote button | [`src/spotlight-shared.js`](../src/spotlight-shared.js) |+| Shared entry form | [`src/spotlight-form.js`](../src/spotlight-form.js) |+| Share cards for crawlers | [`api/spotlight-og.js`](../api/spotlight-og.js) || Styles | [`src/spotlight.css`](../src/spotlight.css) |-| HTTP boundary | [`api/showcase/[action].js`](../api/showcase/[action].js) |-| Queries + ranking | [`api/_lib/showcase-store.js`](../api/_lib/showcase-store.js) |+| HTTP boundary | [`api/spotlight/[action].js`](../api/spotlight/[action].js) |+| Queries + ranking | [`api/_lib/spotlight-store.js`](../api/_lib/spotlight-store.js) || Schema | `api/_lib/migrations/20260901160000_agent_showcase.sql` |-| Curated seed | [`scripts/seed-showcase.mjs`](../scripts/seed-showcase.mjs) |+| Curated seed | [`scripts/seed-spotlight.mjs`](../scripts/seed-spotlight.mjs) |## Relateddiff --git a/pages/spotlight-entry.html b/pages/spotlight-entry.htmlnew file mode 100644index 000000000..f930f57f6--- /dev/null+++ b/pages/spotlight-entry.html@@ -0,0 +1,55 @@+<!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>Agent Spotlight · three.ws</title>+ <meta+ name="description"+ content="A community write-up of an agent built on three.ws: what it does, how it was built, and the live agent behind it."+ />+ <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="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/spotlight.css" />+ <link rel="stylesheet" href="/footer.css" />+ <script defer src="/footer-newsletter.js"></script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="sp-shell sp-detail" id="sp-entry" aria-busy="true">+ <!-- Rendered by /src/spotlight-entry.js from /api/spotlight/get. The+ skeleton below is real markup rather than a spinner so the page has+ its final shape before the data lands. -->+ <div class="sp-detail-skeleton" id="sp-entry-skeleton">+ <div class="sp-skeleton sp-skeleton-stage"></div>+ <div class="sp-skeleton sp-skeleton-copy"></div>+ </div>+ <noscript>+ <section class="sp-empty">+ <h3>Agent Spotlight</h3>+ <p>+ This page renders a community write-up of an agent built on three.ws. Enable+ JavaScript to read it, or browse the whole showcase.+ </p>+ <a class="sp-btn sp-btn-primary" href="/spotlight">Open the showcase</a>+ </section>+ </noscript>+ </main>++ <div id="sp-live" class="sr-only" role="status" aria-live="polite"></div>++ <script type="module" src="/src/spotlight-entry.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/pages/spotlight.html b/pages/spotlight.htmlindex 5f370b25d..ecf72599e 100644--- a/pages/spotlight.html+++ b/pages/spotlight.html@@ -70,7 +70,7 @@<dl class="sp-stats" id="sp-stats" aria-live="polite"></dl></section>- <!-- Submission. Server-validated on POST /api/showcase/submit; the client+ <!-- Submission. Server-validated on POST /api/spotlight/submit; the clientmirrors the same bounds so a builder learns about a too-long taglinewhile typing it rather than after a round trip. --><form class="sp-panel" id="sp-submit-panel" hidden>@@ -85,86 +85,9 @@<div id="sp-submit-auth" class="sp-inline-state" hidden></div>- <div class="sp-field">- <label for="sp-agent">Agent</label>- <select class="sp-input" id="sp-agent" name="agentId" required></select>- <span class="sp-hint" id="sp-agent-hint"></span>- </div>-- <div class="sp-row">- <div class="sp-field">- <label for="sp-title">Headline</label>- <input- class="sp-input"- id="sp-title"- name="title"- required- minlength="3"- maxlength="90"- placeholder="The rug detector that reads the chain before you ape"- autocomplete="off"- />- <span class="sp-hint"><span data-count-for="sp-title">0</span>/90</span>- </div>- <div class="sp-field">- <label for="sp-category">Category</label>- <select class="sp-input" id="sp-category" name="category" required></select>- </div>- </div>-- <div class="sp-field">- <label for="sp-tagline">One-liner</label>- <input- class="sp-input"- id="sp-tagline"- name="tagline"- required- minlength="10"- maxlength="160"- placeholder="What it does, in the words you would use out loud."- autocomplete="off"- />- <span class="sp-hint"><span data-count-for="sp-tagline">0</span>/160</span>- </div>-- <div class="sp-field">- <label for="sp-story">The write-up <span class="sp-hint">(optional)</span></label>- <textarea- class="sp-textarea"- id="sp-story"- name="story"- maxlength="4000"- placeholder="How you built it, what it is for, what surprised you. This is the part people read."- ></textarea>- <span class="sp-hint"><span data-count-for="sp-story">0</span>/4000</span>- </div>-- <div class="sp-row">- <div class="sp-field">- <label for="sp-demo">Demo link <span class="sp-hint">(optional)</span></label>- <input- class="sp-input"- id="sp-demo"- name="demoUrl"- type="url"- maxlength="500"- placeholder="https://your-site.com/where-it-lives"- autocomplete="off"- />- </div>- <div class="sp-field">- <label for="sp-tags">Tags <span class="sp-hint">(optional, up to 6)</span></label>- <input- class="sp-input"- id="sp-tags"- name="tags"- maxlength="160"- placeholder="solana, on-chain, research"- autocomplete="off"- />- <span class="sp-hint">Comma separated. Lowercase letters, digits and hyphens.</span>- </div>- </div>+ <!-- Fields are built by src/spotlight-form.js, the same module the edit+ form on /spotlight/:id uses, so the two can never drift apart. -->+ <div id="sp-fields"></div><div class="sp-ctas"><button type="submit" class="sp-btn sp-btn-primary" id="sp-submit">Publish to the showcase</button>diff --git a/scripts/seed-showcase.mjs b/scripts/seed-spotlight.mjssimilarity index 98%rename from scripts/seed-showcase.mjsrename to scripts/seed-spotlight.mjsindex 43e878404..4cf7d6bd4 100644--- a/scripts/seed-showcase.mjs+++ b/scripts/seed-spotlight.mjs@@ -20,9 +20,9 @@* reported and skipped, never overwritten with stale editorial.** Usage:- * node scripts/seed-showcase.mjs # dry run: report what would land- * node scripts/seed-showcase.mjs --apply # write the entries- * node scripts/seed-showcase.mjs --apply --force # also refresh existing curated rows+ * node scripts/seed-spotlight.mjs # dry run: report what would land+ * node scripts/seed-spotlight.mjs --apply # write the entries+ * node scripts/seed-spotlight.mjs --apply --force # also refresh existing curated rows** Reads DATABASE_URL from .env.local then .env (same order as the migrations* runner). A community-submitted entry for the same agent is never touched.diff --git a/src/spotlight-entry.js b/src/spotlight-entry.jsnew file mode 100644index 000000000..ee8924ddb--- /dev/null+++ b/src/spotlight-entry.js@@ -0,0 +1,500 @@+/**+ * /spotlight/:id — one Agent Spotlight entry.+ *+ * The reason this page exists: an entry's write-up runs to 4,000 characters and+ * the index could only ever show three clamped lines of it. A showcase whose+ * write-ups cannot be read is a directory with extra steps.+ *+ * It is also the only place an entry is WRITTEN after it is created. The index+ * creates; this page edits and removes, using the same field module+ * (src/spotlight-form.js), so there is exactly one implementation of the form+ * and one place a builder has to find to fix a typo.+ *+ * The page title, meta description and canonical are set from the entry once it+ * loads. Social crawlers never execute this: vercel.json rewrites them to+ * api/spotlight-og.js, which renders the same facts server-side.+ */++import { apiFetch } from './api.js';+import {+ buildFields,+ fillCategories,+ fillEntry,+ readValues,+ removeEntry,+ saveEntry,+ validate,+} from './spotlight-form.js';+import { el, entryPath, errorMessage, monogram, relativeTime, stageFor, voteButton } from './spotlight-shared.js';++const root = document.getElementById('sp-entry');+const live = document.getElementById('sp-live');++let entry = null;+let categories = [];++function announce(message) {+ if (live) live.textContent = message;+}++function plural(n, one, many) {+ return `${n.toLocaleString()} ${n === 1 ? one : many}`;+}++function entryIdFromPath() {+ const m = location.pathname.match(/^\/spotlight\/([0-9a-f-]{36})\/?$/i);+ return m ? m[1] : null;+}++function categoryLabel(slug) {+ return categories.find((c) => c.slug === slug)?.label || slug;+}++/* ── head ─────────────────────────────────────────────────────────────── */++// A client-rendered page still owes a correct title and canonical: the browser+// tab, a bookmark, and the history entry all read them, and so does any crawler+// that does execute JS.+function applyHead(e) {+ const title = `${e.title} · Agent Spotlight · three.ws`;+ document.title = title;+ setMeta('name', 'description', e.tagline);+ setLink('canonical', `https://three.ws/spotlight/${e.id}`);+}++function setMeta(attr, key, value) {+ let node = document.head.querySelector(`meta[${attr}="${key}"]`);+ if (!node) {+ node = document.createElement('meta');+ node.setAttribute(attr, key);+ document.head.appendChild(node);+ }+ node.setAttribute('content', value);+}++function setLink(rel, href) {+ let node = document.head.querySelector(`link[rel="${rel}"]`);+ if (!node) {+ node = document.createElement('link');+ node.rel = rel;+ document.head.appendChild(node);+ }+ node.href = href;+}++/* ── render ───────────────────────────────────────────────────────────── */++function breadcrumb(e) {+ return el('nav', { class: 'sp-crumbs', 'aria-label': 'Breadcrumb' }, [+ el('a', { href: '/spotlight', text: 'Agent Spotlight' }),+ el('span', { 'aria-hidden': 'true', text: '/' }),+ el('a', {+ href: `/spotlight?category=${encodeURIComponent(e.category)}`,+ text: categoryLabel(e.category),+ }),+ ]);+}++function badges(e) {+ return el('div', { class: 'sp-detail-badges' }, [+ el('span', { class: 'sp-badge', text: categoryLabel(e.category) }),+ e.agent.is_registered ? el('span', { class: 'sp-badge sp-badge-onchain', text: 'On-chain' }) : null,+ e.featured ? el('span', { class: 'sp-badge', text: "Editor's pick" }) : null,+ e.source === 'curated' ? el('span', { class: 'sp-badge sp-badge-curated', text: 'Curated' }) : null,+ ]);+}++// A curated entry says so in words, not just a badge. The badge tells you the+// category of thing you are reading; this tells you who wrote it, which is the+// part that would otherwise put words in a builder's mouth.+function provenance(e) {+ if (e.source !== 'curated') return null;+ return el('p', { class: 'sp-provenance' }, [+ el('strong', { text: 'Written by three.ws. ' }),+ document.createTextNode(+ `${e.agent.name} is ${e.builder?.name ? `${e.builder.name}'s` : 'a community'} agent; this write-up is ours, not theirs. `,+ ),+ e.editable_by_me+ ? el('span', { text: 'It is your agent, so you can replace this with your own words below.' })+ : document.createTextNode('Its builder can replace it with their own write-up at any time.'),+ ]);+}++function storyBlock(e) {+ if (!e.story) return null;+ // Stored as plain text with blank-line paragraph breaks. Rendered as real+ // paragraphs via textContent, never innerHTML: this is user-submitted copy on+ // a public page.+ const paragraphs = e.story+ .split(/\n{2,}/)+ .map((p) => p.trim())+ .filter(Boolean);+ return el(+ 'div',+ { class: 'sp-story' },+ paragraphs.map((p) => el('p', { text: p })),+ );+}++function skillChips(e) {+ const skills = e.agent.skills || [];+ if (!skills.length) return null;+ return el('div', { class: 'sp-facts-block' }, [+ el('h3', { class: 'sp-facts-head', text: 'Skills' }),+ el(+ 'div',+ { class: 'sp-tags' },+ skills.slice(0, 14).map((s) => el('span', { class: 'sp-tag sp-tag-static', text: s })),+ ),+ ]);+}++// Everything in this panel is read live off the agent on each request, which is+// exactly why it belongs beside the write-up: the prose is a claim from a+// moment in time, these are facts as of now.+function factsPanel(e) {+ const rows = [+ ['Agent', e.agent.name],+ ['Builder', e.builder?.name || 'Not public'],+ ['Published', relativeTime(e.created_at)],+ ['Upvotes', String(e.vote_count)],+ ];+ if (e.agent.chat_count > 0) rows.push(['Conversations', e.agent.chat_count.toLocaleString()]);+ if (e.agent.action_count > 0) rows.push(['On-chain actions', e.agent.action_count.toLocaleString()]);+ if (e.view_count > 0) rows.push(['Views', e.view_count.toLocaleString()]);+ if (e.agent.onchain?.network) rows.push(['Network', e.agent.onchain.network]);++ return el('aside', { class: 'sp-facts', 'aria-label': 'Agent facts' }, [+ el(+ 'dl',+ { class: 'sp-facts-list' },+ rows.flatMap(([k, v]) => [el('dt', { text: k }), el('dd', { text: v })]),+ ),+ skillChips(e),+ el('div', { class: 'sp-facts-block' }, [+ el('h3', { class: 'sp-facts-head', text: 'Go to the agent' }),+ el('div', { class: 'sp-facts-links' }, [+ el('a', { class: 'sp-btn sp-btn-sm', href: `/agents/${e.agent.id}`, text: 'Open in 3D' }),+ el('a', { class: 'sp-btn sp-btn-sm', href: `/agents/${e.agent.id}/profile`, text: 'Full profile' }),+ el('a', { class: 'sp-btn sp-btn-sm', href: `/agents/${e.agent.id}/ar`, text: 'View in AR' }),+ ]),+ ]),+ ]);+}++function shareRow(e) {+ const url = `https://three.ws/spotlight/${e.id}`;+ const shareText = `${e.title} — ${e.agent.name} on three.ws`;++ const copy = el('button', { type: 'button', class: 'sp-btn sp-btn-sm', text: 'Copy link' });+ copy.addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(url);+ copy.textContent = 'Copied';+ announce('Link copied.');+ setTimeout(() => {+ copy.textContent = 'Copy link';+ }, 1600);+ } catch {+ // Clipboard is permission-gated and can simply refuse. Select the URL+ // so the visitor can copy it themselves rather than getting nothing.+ const field = el('input', { class: 'sp-input', value: url, readonly: true });+ copy.replaceWith(field);+ field.select();+ }+ });++ return el('div', { class: 'sp-share' }, [+ copy,+ el('a', {+ class: 'sp-btn sp-btn-sm',+ href: `https://x.com/intent/post?text=${encodeURIComponent(shareText)}&url=${encodeURIComponent(url)}`,+ target: '_blank',+ rel: 'noopener',+ text: 'Share on X',+ }),+ e.demo_url+ ? el('a', {+ class: 'sp-btn sp-btn-sm',+ href: e.demo_url,+ target: '_blank',+ rel: 'noopener nofollow ugc',+ text: 'See it live',+ })+ : null,+ ]);+}++function ownerControls(e) {+ if (!e.editable_by_me) return null;+ const edit = el('button', { type: 'button', class: 'sp-btn sp-btn-sm', text: 'Edit entry' });+ const remove = el('button', { type: 'button', class: 'sp-btn sp-btn-sm sp-btn-danger', text: 'Remove' });+ edit.addEventListener('click', () => openEditor(true));+ remove.addEventListener('click', () => confirmRemove(remove));+ return el('div', { class: 'sp-owner-bar' }, [+ el('span', { class: 'sp-owner-label', text: 'You can edit this entry' }),+ edit,+ remove,+ ]);+}++// Two-step, in place: a destructive action gets a real confirmation, and the+// second click is a different button than the first so a double click cannot+// delete an entry by accident.+function confirmRemove(button) {+ const bar = button.parentElement;+ const cancel = el('button', { type: 'button', class: 'sp-btn sp-btn-sm', text: 'Keep it' });+ const confirm = el('button', {+ type: 'button',+ class: 'sp-btn sp-btn-sm sp-btn-danger',+ text: 'Yes, remove it',+ });+ const prompt = el('span', { class: 'sp-owner-label', text: 'Remove this entry from the showcase?' });+ const original = Array.from(bar.childNodes);+ bar.replaceChildren(prompt, confirm, cancel);+ cancel.addEventListener('click', () => bar.replaceChildren(...original));+ confirm.addEventListener('click', async () => {+ confirm.disabled = true;+ confirm.textContent = 'Removing…';+ try {+ await removeEntry(entry.id);+ announce('Entry removed.');+ location.href = '/spotlight';+ } catch (err) {+ bar.replaceChildren(...original);+ renderNote(err?.message || 'the entry could not be removed', 'error');+ }+ });+}++function renderNote(message, tone) {+ const note = document.getElementById('sp-detail-note');+ if (!note) return;+ note.textContent = message;+ if (tone) note.dataset.tone = tone;+ else delete note.dataset.tone;+}++/* ── edit ─────────────────────────────────────────────────────────────── */++let editRefs = null;++function editorPanel() {+ const fields = el('div', { id: 'sp-edit-fields' });+ const note = el('p', { class: 'sp-form-note', id: 'sp-edit-note', role: 'status', 'aria-live': 'polite' });+ const save = el('button', { type: 'submit', class: 'sp-btn sp-btn-primary', text: 'Save changes' });+ const cancel = el('button', { type: 'button', class: 'sp-btn', text: 'Cancel' });+ cancel.addEventListener('click', () => openEditor(false));++ const form = el('form', { class: 'sp-panel', id: 'sp-edit-panel', hidden: true }, [+ el('div', { class: 'sp-panel-head' }, [+ el('h2', { class: 'sp-h2', text: 'Edit this entry' }),+ el('p', {+ class: 'sp-panel-note',+ text: `You are editing the write-up, not ${entry.agent.name} itself. The agent's name, avatar, skills and identity always come from the agent record.`,+ }),+ ]),+ fields,+ el('div', { class: 'sp-ctas' }, [save, cancel]),+ note,+ ]);++ form.addEventListener('submit', async (event) => {+ event.preventDefault();+ const payload = readValues(editRefs, entry.agent.id);+ const problem = validate(payload);+ if (problem) {+ note.textContent = problem;+ note.dataset.tone = 'error';+ return;+ }+ save.disabled = true;+ note.textContent = 'Saving…';+ delete note.dataset.tone;+ try {+ entry = await saveEntry(payload);+ announce('Entry updated.');+ render();+ } catch (err) {+ note.textContent = err.unauthorized+ ? 'your session expired; sign in and try again'+ : err?.message || 'the change did not save';+ note.dataset.tone = 'error';+ } finally {+ save.disabled = false;+ }+ });++ return form;+}++function openEditor(open) {+ const panel = document.getElementById('sp-edit-panel');+ if (!panel) return;+ panel.hidden = !open;+ if (!open) return;+ if (!editRefs) {+ editRefs = buildFields(document.getElementById('sp-edit-fields'), {+ prefix: 'spe',+ withAgentPicker: false,+ });+ }+ fillCategories(editRefs, categories, entry.category);+ fillEntry(editRefs, entry);+ panel.scrollIntoView({ behavior: 'smooth', block: 'start' });+ editRefs.title.focus();+}++/* ── related ──────────────────────────────────────────────────────────── */++async function loadRelated(e) {+ const rail = document.getElementById('sp-related');+ if (!rail) return;+ try {+ const res = await apiFetch(+ `/api/spotlight/list?category=${encodeURIComponent(e.category)}&limit=4&sort=trending`,+ { allowAnonymous: true },+ );+ if (!res.ok) return;+ const data = await res.json().catch(() => null);+ const others = (data?.entries || []).filter((x) => x.id !== e.id).slice(0, 3);+ if (!others.length) return;++ rail.replaceChildren(+ el('h2', { class: 'sp-h2', text: `More in ${categoryLabel(e.category)}` }),+ el(+ 'div',+ { class: 'sp-related-grid' },+ others.map((o) =>+ el('a', { class: 'sp-related-card', href: entryPath(o) }, [+ o.agent.thumbnail+ ? el('img', { src: o.agent.thumbnail, alt: '', loading: 'lazy', decoding: 'async' })+ : monogram(o.agent),+ el('div', { class: 'sp-related-copy' }, [+ el('strong', { text: o.title }),+ el('span', { text: o.agent.name }),+ ]),+ ]),+ ),+ ),+ );+ rail.hidden = false;+ } catch {+ // A missing related rail is not worth an error state on a page whose+ // content has already rendered.+ }+}++/* ── page ─────────────────────────────────────────────────────────────── */++function render() {+ applyHead(entry);++ const header = el('div', { class: 'sp-detail-copy' }, [+ breadcrumb(entry),+ badges(entry),+ el('h1', { class: 'sp-detail-title', text: entry.title }),+ el('p', { class: 'sp-detail-tagline', text: entry.tagline }),+ el('div', { class: 'sp-card-meta' }, [+ el('span', {}, [el('strong', { text: entry.agent.name })]),+ entry.builder?.name+ ? el('span', { 'aria-hidden': 'true', text: '·' })+ : null,+ entry.builder?.name+ ? entry.builder.profile_url+ ? el('a', { href: entry.builder.profile_url, text: `built by ${entry.builder.name}` })+ : el('span', { text: `built by ${entry.builder.name}` })+ : null,+ el('span', { 'aria-hidden': 'true', text: '·' }),+ el('span', { text: relativeTime(entry.created_at) }),+ ]),+ el('div', { class: 'sp-detail-actions' }, [+ voteButton(entry, { announce, large: true }),+ el('a', {+ class: 'sp-btn sp-btn-primary',+ href: `/agents/${entry.agent.id}`,+ text: `Talk to ${entry.agent.name}`,+ }),+ ]),+ shareRow(entry),+ ]);++ const main = el('div', { class: 'sp-detail-main' }, [+ provenance(entry),+ storyBlock(entry) ||+ el('p', { class: 'sp-detail-nostory', text: 'No write-up yet, just the one-liner above.' }),+ ]);++ root.replaceChildren(+ el('div', { class: 'sp-detail-hero' }, [stageFor(entry, { eager: true }), header]),+ ownerControls(entry),+ editorPanel(),+ el('p', { class: 'sp-form-note', id: 'sp-detail-note', role: 'status', 'aria-live': 'polite' }),+ el('div', { class: 'sp-detail-body' }, [main, factsPanel(entry)]),+ el('section', { class: 'sp-related', id: 'sp-related', hidden: true }),+ el('div', { class: 'sp-detail-foot' }, [+ el('a', { class: 'sp-btn', href: '/spotlight', text: 'Back to the showcase' }),+ el('a', { class: 'sp-btn', href: '/spotlight?submit=1', text: 'Showcase your own agent' }),+ ]),+ );+ root.setAttribute('aria-busy', 'false');+ editRefs = null;+}++function renderMissing(message, { notFound = false } = {}) {+ root.setAttribute('aria-busy', 'false');+ root.replaceChildren(+ el('div', { class: notFound ? 'sp-empty' : 'sp-error' }, [+ el('h3', { text: notFound ? 'That entry is not here' : 'This entry did not load' }),+ el('p', { text: message }),+ el('a', { class: 'sp-btn sp-btn-primary', href: '/spotlight', text: 'Open the showcase' }),+ ]),+ );+ document.title = notFound ? 'Entry not found · Agent Spotlight · three.ws' : document.title;+}++async function loadCategories() {+ try {+ const res = await apiFetch('/api/spotlight/categories', { allowAnonymous: true });+ if (!res.ok) return;+ const data = await res.json().catch(() => null);+ categories = Array.isArray(data?.categories) ? data.categories : [];+ } catch {+ categories = [];+ }+}++async function boot() {+ const id = entryIdFromPath();+ if (!id) {+ renderMissing('That link does not point at a showcase entry.', { notFound: true });+ return;+ }++ // Categories only supply human labels, so the entry never waits on them.+ loadCategories();++ try {+ const res = await apiFetch(`/api/spotlight/get?id=${encodeURIComponent(id)}`, { allowAnonymous: true });+ const data = await res.json().catch(() => null);+ if (res.status === 404) {+ renderMissing(+ 'This entry was removed, or the agent behind it is no longer public. The rest of the showcase is still here.',+ { notFound: true },+ );+ return;+ }+ if (!res.ok) throw new Error(errorMessage(data, `the entry returned ${res.status}`));+ entry = data.entry;+ render();+ loadRelated(entry);+ announce(`${entry.title}. ${plural(entry.vote_count, 'upvote', 'upvotes')}.`);+ if (new URLSearchParams(location.search).get('edit') === '1' && entry.editable_by_me) {+ openEditor(true);+ }+ } catch (err) {+ renderMissing(err?.message || 'could not reach the showcase');+ }+}++boot();diff --git a/src/spotlight-form.js b/src/spotlight-form.jsnew file mode 100644index 000000000..e5362af85--- /dev/null+++ b/src/spotlight-form.js@@ -0,0 +1,278 @@+/**+ * The Agent Spotlight entry form, shared by /spotlight (create) and+ * /spotlight/:id (edit).+ *+ * Both surfaces write the same six fields through the same endpoint, so the+ * field spec, the client-side bounds, the tag parsing and the save call live+ * here once. The bounds mirror the server's (api/spotlight/[action].js) on+ * purpose: the server is the authority, and this copy exists only so a builder+ * learns about a too-long tagline while typing it rather than after a round+ * trip. When one moves, move both, and the bounds are named constants here so+ * the two can be diffed at a glance.+ */++import { apiFetch } from './api.js';++export const BOUNDS = {+ title: { min: 3, max: 90 },+ tagline: { min: 10, max: 160 },+ story: { max: 4000 },+ demoUrl: { max: 500 },+ tags: { max: 6, maxLength: 24 },+};++function el(tag, props = {}, children = []) {+ const node = document.createElement(tag);+ for (const [k, v] of Object.entries(props)) {+ if (v == null || v === false) continue;+ if (k === 'class') node.className = v;+ else if (k === 'text') node.textContent = v;+ else node.setAttribute(k, v === true ? '' : String(v));+ }+ for (const child of [].concat(children)) {+ if (child != null) node.append(child);+ }+ return node;+}++// A labelled field with a live character counter. The counter is the reason+// these are built rather than written as markup twice: it has to be wired to+// its own input, and a second hand-written copy is how the two forms drift.+function field({ id, label, optional, hint, control, counterFor }) {+ const labelNode = el('label', { for: id }, [+ document.createTextNode(label),+ optional ? el('span', { class: 'sp-hint', text: ` ${optional}` }) : null,+ ]);+ const hintNode = counterFor+ ? el('span', { class: 'sp-hint' }, [+ el('span', { 'data-count': id, text: '0' }),+ document.createTextNode(`/${counterFor}`),+ ])+ : hint+ ? el('span', { class: 'sp-hint', text: hint })+ : null;+ return el('div', { class: 'sp-field' }, [labelNode, control, hintNode]);+}++/**+ * Build the form body into `container`. `prefix` namespaces the element ids so+ * the create form and an edit form can coexist on one page without colliding.+ * Returns the refs the rest of the module reads.+ */+export function buildFields(container, { prefix = 'sp', withAgentPicker = true } = {}) {+ const id = (name) => `${prefix}-${name}`;++ const agentSelect = el('select', { class: 'sp-input', id: id('agent'), required: true });+ const agentHint = el('span', { class: 'sp-hint', id: id('agent-hint') });+ const titleInput = el('input', {+ class: 'sp-input',+ id: id('title'),+ required: true,+ minlength: BOUNDS.title.min,+ maxlength: BOUNDS.title.max,+ placeholder: 'The rug detector that reads the chain before you ape',+ autocomplete: 'off',+ });+ const categorySelect = el('select', { class: 'sp-input', id: id('category'), required: true });+ const taglineInput = el('input', {+ class: 'sp-input',+ id: id('tagline'),+ required: true,+ minlength: BOUNDS.tagline.min,+ maxlength: BOUNDS.tagline.max,+ placeholder: 'What it does, in the words you would use out loud.',+ autocomplete: 'off',+ });+ const storyArea = el('textarea', {+ class: 'sp-textarea',+ id: id('story'),+ maxlength: BOUNDS.story.max,+ placeholder:+ 'How you built it, what it is for, what surprised you. This is the part people read.',+ });+ const demoInput = el('input', {+ class: 'sp-input',+ id: id('demo'),+ type: 'url',+ maxlength: BOUNDS.demoUrl.max,+ placeholder: 'https://your-site.com/where-it-lives',+ autocomplete: 'off',+ });+ const tagsInput = el('input', {+ class: 'sp-input',+ id: id('tags'),+ maxlength: 160,+ placeholder: 'solana, on-chain, research',+ autocomplete: 'off',+ });++ const nodes = [];+ if (withAgentPicker) {+ nodes.push(+ el('div', { class: 'sp-field' }, [+ el('label', { for: id('agent'), text: 'Agent' }),+ agentSelect,+ agentHint,+ ]),+ );+ }+ nodes.push(+ el('div', { class: 'sp-row' }, [+ field({ id: id('title'), label: 'Headline', control: titleInput, counterFor: BOUNDS.title.max }),+ field({ id: id('category'), label: 'Category', control: categorySelect }),+ ]),+ field({ id: id('tagline'), label: 'One-liner', control: taglineInput, counterFor: BOUNDS.tagline.max }),+ field({+ id: id('story'),+ label: 'The write-up',+ optional: '(optional)',+ control: storyArea,+ counterFor: BOUNDS.story.max,+ }),+ el('div', { class: 'sp-row' }, [+ field({+ id: id('demo'),+ label: 'Demo link',+ optional: '(optional)',+ control: demoInput,+ hint: 'Where it can be seen working. Rendered as a link, never fetched.',+ }),+ field({+ id: id('tags'),+ label: 'Tags',+ optional: `(optional, up to ${BOUNDS.tags.max})`,+ control: tagsInput,+ hint: 'Comma separated. Lowercase letters, digits and hyphens.',+ }),+ ]),+ );+ container.replaceChildren(...nodes);++ const refs = {+ agentSelect,+ agentHint,+ title: titleInput,+ category: categorySelect,+ tagline: taglineInput,+ story: storyArea,+ demo: demoInput,+ tags: tagsInput,+ };+ wireCounters(container);+ return refs;+}++function wireCounters(container) {+ for (const counter of container.querySelectorAll('[data-count]')) {+ const input = container.querySelector(`#${CSS.escape(counter.dataset.count)}`);+ if (!input) continue;+ const update = () => {+ counter.textContent = String(input.value.length);+ };+ input.addEventListener('input', update);+ update();+ }+}++export function fillCategories(refs, categories, selected) {+ if (!categories?.length) return;+ refs.category.replaceChildren(+ ...categories.map((c) => {+ const opt = el('option', { value: c.slug, text: c.label });+ if (c.slug === selected) opt.selected = true;+ return opt;+ }),+ );+}++export function fillEntry(refs, entry) {+ refs.title.value = entry.title || '';+ refs.tagline.value = entry.tagline || '';+ refs.story.value = entry.story || '';+ refs.demo.value = entry.demo_url || '';+ refs.tags.value = (entry.tags || []).join(', ');+ for (const input of [refs.title, refs.tagline, refs.story]) {+ input.dispatchEvent(new Event('input'));+ }+}++export function parseTags(raw) {+ const out = [];+ for (const piece of String(raw || '').split(',')) {+ const tag = piece.trim().toLowerCase().replace(/\s+/g, '-');+ if (tag && !out.includes(tag)) out.push(tag);+ }+ return out.slice(0, BOUNDS.tags.max);+}++export function readValues(refs, agentId) {+ return {+ agentId: agentId || refs.agentSelect?.value || '',+ title: refs.title.value.trim(),+ tagline: refs.tagline.value.trim(),+ story: refs.story.value.trim() || null,+ demoUrl: refs.demo.value.trim() || null,+ category: refs.category.value,+ tags: parseTags(refs.tags.value),+ };+}++// Returns an error message, or null when the payload is worth sending. Every+// rule here has a server-side twin; this only saves the round trip.+export function validate(payload) {+ if (!payload.agentId) return 'pick which agent you are showcasing';+ if (payload.title.length < BOUNDS.title.min) {+ return `the headline needs at least ${BOUNDS.title.min} characters`;+ }+ if (payload.tagline.length < BOUNDS.tagline.min) {+ return `the one-liner needs at least ${BOUNDS.tagline.min} characters`;+ }+ for (const tag of payload.tags) {+ if (tag.length > BOUNDS.tags.maxLength || !/^[a-z0-9][a-z0-9-]*$/.test(tag)) {+ return `"${tag}" is not a usable tag: lowercase letters, digits and hyphens only`;+ }+ }+ if (payload.demoUrl && !/^https?:\/\//i.test(payload.demoUrl)) {+ return 'the demo link has to start with http:// or https://';+ }+ return null;+}++/**+ * Save (create or edit, the server decides which) and return the entry.+ * Throws an Error carrying the server's message, or `{ unauthorized: true }`+ * on a 401 so the caller can show a sign-in prompt rather than a red error.+ */+export async function saveEntry(payload) {+ const res = await apiFetch('/api/spotlight/submit', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(payload),+ allowAnonymous: true,+ });+ if (res.status === 401) {+ const err = new Error('sign in to publish');+ err.unauthorized = true;+ throw err;+ }+ const data = await res.json().catch(() => null);+ if (!res.ok) throw new Error(data?.error_description || data?.error?.message || `the submission returned ${res.status}`);+ return data.entry;+}++export async function removeEntry(id) {+ const res = await apiFetch('/api/spotlight/remove', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ id }),+ allowAnonymous: true,+ });+ if (res.status === 401) {+ const err = new Error('sign in to remove this entry');+ err.unauthorized = true;+ throw err;+ }+ const data = await res.json().catch(() => null);+ if (!res.ok) throw new Error(data?.error_description || data?.error?.message || `the removal returned ${res.status}`);+ return true;+}diff --git a/src/spotlight-shared.js b/src/spotlight-shared.jsnew file mode 100644index 000000000..3f9fe8de1--- /dev/null+++ b/src/spotlight-shared.js@@ -0,0 +1,224 @@+/**+ * Rendering pieces shared by /spotlight and /spotlight/:id.+ *+ * Both surfaces draw the same entry: the same 3D stage, the same upvote button+ * with the same optimistic-free settle, the same monogram fallback for an agent+ * with no public avatar. Keeping them here means a card and a detail page can+ * never disagree about what an entry looks like or what a vote does.+ */++import { apiFetch } from './api.js';++const AGENT_3D_LOADER = 'https://three.ws/agent-3d/latest/agent-3d.js';++export function el(tag, props = {}, children = []) {+ const node = document.createElement(tag);+ for (const [k, v] of Object.entries(props)) {+ if (v == null || v === false) continue;+ if (k === 'class') node.className = v;+ else if (k === 'text') node.textContent = v;+ else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v);+ else node.setAttribute(k, v === true ? '' : String(v));+ }+ for (const child of [].concat(children)) {+ if (child != null) node.append(child);+ }+ return node;+}++// The API answers errors as { error, error_description } (api/_lib/http.js).+// Reading `error.message` instead, which is the shape most JSON APIs use, threw+// away every server-side validation message and replaced it with a bare status+// code, so a builder was told "the submission returned 400" instead of "the+// headline needs at least 3 characters". One reader, used everywhere.+export function errorMessage(payload, fallback) {+ return payload?.error_description || payload?.error?.message || fallback;+}++export function entryPath(entry) {+ return `/spotlight/${entry.id}`;+}++export function relativeTime(iso) {+ const then = new Date(iso).getTime();+ if (!Number.isFinite(then)) return '';+ const mins = Math.round((Date.now() - then) / 60000);+ if (mins < 1) return 'just now';+ if (mins < 60) return `${mins}m ago`;+ const hours = Math.round(mins / 60);+ if (hours < 24) return `${hours}h ago`;+ const days = Math.round(hours / 24);+ if (days < 30) return `${days}d ago`;+ return new Date(then).toLocaleDateString(undefined, { month: 'short', year: 'numeric' });+}++// Deterministic hue from the agent id: the same agent keeps the same monogram+// colour on every card, in every session, without storing anything.+function hueOf(id) {+ let h = 0;+ for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) % 360;+ return h;+}++export function monogram(agent) {+ const hue = hueOf(agent.id || agent.name || 'agent');+ const initials = (agent.name || '?')+ .split(/\s+/)+ .slice(0, 2)+ .map((w) => w[0])+ .join('')+ .toUpperCase();+ const node = el('div', { class: 'sp-mono', 'aria-hidden': 'true', text: initials });+ node.style.background = `linear-gradient(140deg, hsl(${hue} 62% 26%), hsl(${(hue + 48) % 360} 55% 14%))`;+ return node;+}++let agent3dRequested = false;+function loadAgent3d() {+ if (agent3dRequested) return;+ agent3dRequested = true;+ const s = document.createElement('script');+ s.type = 'module';+ s.src = AGENT_3D_LOADER;+ document.head.appendChild(s);+}++// Hide the still only once <agent-3d> has painted a canvas of its own. There is+// no documented ready event on the component, and a canvas in the DOM is the one+// signal that means the model is genuinely on screen. Give up after a bounded+// wait and leave the still in place, which is the correct outcome when the GLB+// never arrives.+function revealWhenPainted(viewer, still) {+ let settled = false;+ const painted = () =>+ Boolean(viewer.querySelector('canvas') || viewer.shadowRoot?.querySelector('canvas'));+ const done = () => {+ if (settled) return;+ settled = true;+ observer.disconnect();+ clearTimeout(timer);+ still.classList.add('is-hidden');+ };+ const observer = new MutationObserver(() => {+ if (painted()) done();+ });+ observer.observe(viewer, { childList: true, subtree: true });+ const timer = setTimeout(() => observer.disconnect(), 15000);+ if (painted()) done();+}++/**+ * The 3D stage. `eager: true` mounts the viewer immediately (the detail page,+ * where the stage IS the page); the default waits for the stage to scroll into+ * view, because below-the-fold WebGL on a browse page costs a visitor real+ * frames for something they may never reach.+ */+export function stageFor(entry, { badge = null, eager = false } = {}) {+ const stage = el('div', { class: 'sp-stage' });+ if (badge) stage.append(el('span', { class: 'sp-stage-badge', text: badge }));++ // The still goes in first and stays until the 3D viewer has actually painted.+ // A GLB can fail for reasons this page does not control (a cold CDN, a blocked+ // origin, no WebGL on the device), and a silently empty hero is the worst+ // version of that failure.+ const still = entry.agent.thumbnail+ ? el('img', {+ class: 'sp-stage-still',+ src: entry.agent.thumbnail,+ alt: `${entry.agent.name} avatar`,+ loading: eager ? 'eager' : 'lazy',+ decoding: 'async',+ })+ : monogram(entry.agent);+ stage.append(still);++ if (!entry.agent.glb_url) return stage;++ const mount = () => {+ loadAgent3d();+ const viewer = el('agent-3d', {+ body: entry.agent.glb_url,+ autorotate: 'true',+ 'camera-controls': 'true',+ 'aria-label': `${entry.agent.name} in 3D`,+ });+ stage.append(viewer);+ revealWhenPainted(viewer, still);+ };++ if (eager || !('IntersectionObserver' in window)) {+ mount();+ } else {+ const io = new IntersectionObserver(+ (entries, obs) => {+ if (entries.some((e) => e.isIntersecting)) {+ obs.disconnect();+ mount();+ }+ },+ { rootMargin: '200px' },+ );+ io.observe(stage);+ }+ return stage;+}++/**+ * The upvote toggle. Never optimistic: the count and pressed state settle on+ * what the server returns, so two tabs, a double click and a lost request all+ * converge on the same truth instead of drifting apart.+ *+ * `onVoted` is called with the mutated entry after a successful toggle, which is+ * how the page's headline totals stay in step without a refetch.+ */+export function voteButton(entry, { announce = () => {}, onVoted = () => {}, large = false } = {}) {+ const count = el('span', { class: 'sp-vote-count', text: String(entry.vote_count) });+ const btn = el(+ 'button',+ {+ type: 'button',+ class: large ? 'sp-vote sp-vote-lg' : 'sp-vote',+ 'aria-pressed': String(Boolean(entry.voted_by_me)),+ 'aria-label': `Upvote ${entry.title}`,+ title: 'Upvote',+ },+ [el('span', { class: 'sp-vote-caret', 'aria-hidden': 'true', text: '▲' }), count],+ );++ btn.addEventListener('click', async (event) => {+ event.preventDefault();+ event.stopPropagation();+ btn.classList.add('is-busy');+ try {+ const res = await apiFetch('/api/spotlight/vote', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ id: entry.id }),+ allowAnonymous: true,+ });+ if (res.status === 401) {+ location.href = `/login?next=${encodeURIComponent(location.pathname + location.search)}`;+ return;+ }+ const data = await res.json().catch(() => null);+ if (!res.ok) {+ announce(errorMessage(data, 'the vote did not go through'));+ return;+ }+ entry.vote_count = data.vote_count;+ entry.voted_by_me = data.voted;+ count.textContent = String(data.vote_count);+ btn.setAttribute('aria-pressed', String(data.voted));+ announce(+ `${data.voted ? 'Upvoted' : 'Removed your upvote from'} ${entry.title}. ${data.vote_count} total.`,+ );+ onVoted(entry);+ } catch {+ announce('the vote did not go through; check your connection');+ } finally {+ btn.classList.remove('is-busy');+ }+ });++ return btn;+}diff --git a/src/spotlight.css b/src/spotlight.cssindex 460ef14aa..45d9511ab 100644--- a/src/spotlight.css+++ b/src/spotlight.css@@ -880,3 +880,368 @@max-width: none;}}++/* ── entry detail: /spotlight/:id ─────────────────────────────────────── */++.sp-detail {+ display: grid;+ gap: var(--space-xl, 32px);+ align-content: start;+}++.sp-detail-skeleton {+ display: grid;+ gap: var(--space-md, 16px);+ grid-template-columns: minmax(0, 5fr) minmax(0, 7fr);+ padding-top: var(--space-lg, 24px);+}++.sp-skeleton-stage {+ height: 420px;+}++.sp-skeleton-copy {+ height: 420px;+}++@media (max-width: 860px) {+ .sp-detail-skeleton {+ grid-template-columns: minmax(0, 1fr);+ }+}++.sp-detail-hero {+ display: grid;+ gap: var(--space-lg, 24px);+ grid-template-columns: minmax(0, 5fr) minmax(0, 7fr);+ align-items: stretch;+ padding-top: var(--space-lg, 24px);+}++@media (max-width: 860px) {+ .sp-detail-hero {+ grid-template-columns: minmax(0, 1fr);+ }+}++.sp-detail-hero .sp-stage {+ min-height: 420px;+}++.sp-detail-hero .sp-stage agent-3d,+.sp-detail-hero .sp-stage-still {+ min-height: 420px;+}++.sp-detail-copy {+ display: grid;+ align-content: center;+ gap: var(--space-sm, 12px);+}++.sp-crumbs {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: var(--space-2, 8px);+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--ink-faint, rgba(255, 255, 255, 0.45));+}++.sp-crumbs a {+ color: inherit;+ text-decoration: none;+ border-bottom: 1px solid transparent;+}++.sp-crumbs a:hover {+ color: var(--ink-bright, #fff);+ border-bottom-color: var(--stroke-strong, rgba(255, 255, 255, 0.3));+}++.sp-detail-badges {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+}++/* The detail badges sit on a page surface, not on media, so they take page ink+ rather than the on-scrim ink the card overlay badges use. */+.sp-detail-badges .sp-badge {+ background: var(--surface-2, rgba(255, 255, 255, 0.06));+ border-color: var(--stroke, rgba(255, 255, 255, 0.12));+ color: var(--ink-dim, rgba(255, 255, 255, 0.62));+ backdrop-filter: none;+}++.sp-detail-title {+ margin: 0;+ font-family: var(--font-display);+ font-size: var(--text-2xl, 38px);+ line-height: var(--leading-tight, 1.12);+ letter-spacing: -0.02em;+ font-weight: var(--weight-bold, 700);+ color: var(--ink-bright, #fff);+}++.sp-detail-tagline {+ margin: 0;+ max-width: 60ch;+ font-size: var(--text-lg, 18px);+ line-height: var(--leading-normal, 1.6);+ color: var(--ink-dim, rgba(255, 255, 255, 0.68));+}++.sp-detail-actions {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: var(--space-sm, 12px);+ margin-top: var(--space-2, 8px);+}++.sp-vote-lg {+ flex-direction: row;+ gap: var(--space-2, 8px);+ padding: 10px var(--space-md, 16px);+ font-size: var(--text-ui, 14px);+}++.sp-share {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-2, 8px);+ margin-top: var(--space-2, 8px);+}++.sp-owner-bar {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: var(--space-sm, 12px);+ padding: var(--space-sm, 12px) var(--space-md, 16px);+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.12));+ border-radius: var(--radius-md, 10px);+ background: var(--surface-1, rgba(255, 255, 255, 0.04));+}++.sp-owner-label {+ flex: 1 1 auto;+ font-size: var(--text-md, 13px);+ color: var(--ink-dim, rgba(255, 255, 255, 0.62));+}++.sp-btn-danger {+ border-color: color-mix(in srgb, var(--danger, #f87171) 42%, transparent);+ color: var(--danger, #f87171);+}++.sp-btn-danger:hover {+ background: color-mix(in srgb, var(--danger, #f87171) 14%, transparent);+ border-color: color-mix(in srgb, var(--danger, #f87171) 62%, transparent);+}++.sp-detail-body {+ display: grid;+ gap: var(--space-xl, 32px);+ grid-template-columns: minmax(0, 1fr) minmax(240px, 300px);+ align-items: start;+}++@media (max-width: 860px) {+ .sp-detail-body {+ grid-template-columns: minmax(0, 1fr);+ }+}++.sp-provenance {+ margin: 0 0 var(--space-md, 16px);+ padding: var(--space-sm, 12px) var(--space-md, 16px);+ border-left: 2px solid color-mix(in srgb, var(--warn, #fbbf24) 55%, transparent);+ border-radius: 0 var(--radius-md, 10px) var(--radius-md, 10px) 0;+ background: color-mix(in srgb, var(--warn, #fbbf24) 8%, transparent);+ font-size: var(--text-md, 13px);+ line-height: var(--leading-normal, 1.6);+ color: var(--ink-dim, rgba(255, 255, 255, 0.7));+}++.sp-provenance strong {+ color: var(--ink-bright, #fff);+}++/* Long-form prose gets a real measure. Anything wider than ~68 characters is+ measurably harder to read, and the write-up is the reason this page exists. */+.sp-story {+ display: grid;+ gap: var(--space-md, 16px);+ max-width: 68ch;+}++.sp-story p {+ margin: 0;+ font-size: var(--text-base, 16px);+ line-height: 1.7;+ color: var(--ink, rgba(255, 255, 255, 0.8));+}++.sp-detail-nostory {+ margin: 0;+ font-size: var(--text-ui, 14px);+ color: var(--ink-faint, rgba(255, 255, 255, 0.45));+ font-style: italic;+}++.sp-facts {+ display: grid;+ gap: var(--space-md, 16px);+ padding: var(--space-md, 16px);+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.1));+ border-radius: var(--radius-lg, 14px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ position: sticky;+ top: calc(var(--header-h, 3.5rem) + var(--space-md, 16px));+}++@media (max-width: 860px) {+ .sp-facts {+ position: static;+ }+}++.sp-facts-list {+ display: grid;+ grid-template-columns: auto 1fr;+ gap: 6px var(--space-sm, 12px);+ margin: 0;+ font-size: var(--text-md, 13px);+}++.sp-facts-list dt {+ color: var(--ink-faint, rgba(255, 255, 255, 0.45));+}++.sp-facts-list dd {+ margin: 0;+ color: var(--ink, rgba(255, 255, 255, 0.84));+ text-align: right;+ font-variant-numeric: tabular-nums;+}++.sp-facts-block {+ display: grid;+ gap: var(--space-2, 8px);+ padding-top: var(--space-md, 16px);+ border-top: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+}++.sp-facts-head {+ margin: 0;+ font-family: var(--font-mono);+ font-size: var(--text-2xs, 11px);+ letter-spacing: 0.1em;+ text-transform: uppercase;+ font-weight: var(--weight-regular, 400);+ color: var(--ink-faint, rgba(255, 255, 255, 0.45));+}++.sp-facts-links {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+}++.sp-tag-static {+ cursor: default;+}++.sp-tag-static:hover {+ color: var(--ink-faint, rgba(255, 255, 255, 0.5));+ border-color: var(--stroke, rgba(255, 255, 255, 0.08));+}++.sp-related {+ display: grid;+ gap: var(--space-md, 16px);+}++.sp-related-grid {+ display: grid;+ gap: var(--space-sm, 12px);+ grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));+}++.sp-related-card {+ display: grid;+ grid-template-columns: 64px minmax(0, 1fr);+ gap: var(--space-sm, 12px);+ align-items: center;+ padding: var(--space-2, 8px);+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.1));+ border-radius: var(--radius-md, 10px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ text-decoration: none;+ transition:+ border-color var(--duration-fast, 140ms) var(--ease-standard),+ transform var(--duration-fast, 140ms) var(--ease-standard);+}++.sp-related-card:hover {+ border-color: var(--stroke-strong, rgba(255, 255, 255, 0.24));+ transform: translateY(-1px);+}++.sp-related-card img,+.sp-related-card .sp-mono {+ width: 64px;+ height: 64px;+ border-radius: var(--radius-sm, 6px);+ object-fit: cover;+ font-size: var(--text-lg, 20px);+ position: static;+}++.sp-related-copy {+ display: grid;+ gap: 2px;+ min-width: 0;+}++.sp-related-copy strong {+ font-size: var(--text-ui, 14px);+ font-weight: var(--weight-medium, 500);+ color: var(--ink-bright, #fff);+ line-height: var(--leading-tight, 1.3);+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}++.sp-related-copy span {+ font-size: var(--text-2xs, 11px);+ font-family: var(--font-mono);+ color: var(--ink-faint, rgba(255, 255, 255, 0.45));+}++.sp-detail-foot {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-sm, 12px);+ padding-top: var(--space-lg, 24px);+ border-top: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+}++@media (max-width: 560px) {+ .sp-detail-title {+ font-size: var(--text-xl, 26px);+ }++ .sp-detail-hero .sp-stage,+ .sp-detail-hero .sp-stage agent-3d,+ .sp-detail-hero .sp-stage-still {+ min-height: 300px;+ }+}diff --git a/src/spotlight.js b/src/spotlight.jsindex 1d370c407..d00a9bd09 100644--- a/src/spotlight.js+++ b/src/spotlight.js@@ -1,5 +1,5 @@/**- * /spotlight: Agent Spotlight, the three.ws community showcase.+ * /spotlight — Agent Spotlight, the three.ws community showcase.** One controller, three jobs: browse (sort + category + search + paging), vote,* and submit. State is a single `view` object that the URL mirrors, so every@@ -7,15 +7,28 @@* re-fetched from that object rather than mutated in place, which keeps the* "what am I looking at" question answerable from one value.*+ * A card's headline links to the ENTRY (/spotlight/:id), not the agent. The+ * write-up is the thing a showcase exists to publish, and burying it behind a+ * clamped three-line preview with no way to open it was the difference between a+ * showcase and a directory. Every card still carries direct links to the agent+ * itself in its footer.+ ** The 3D stage on the featured entry is deliberately lazy: <agent-3d> is a- * WebGL component and the showcase is a browse surface, so the loader script is- * only injected once a featured entry with a public GLB actually scrolls into- * view. Everything below the fold renders from thumbnails.+ * WebGL component and this is a browse surface, so the loader script is only+ * injected once a featured entry with a public GLB actually scrolls into view.+ * Everything below the fold renders from thumbnails.*/import { apiFetch } from './api.js';+import {+ buildFields,+ fillCategories,+ readValues,+ saveEntry,+ validate,+} from './spotlight-form.js';+import { entryPath, errorMessage, monogram, relativeTime, stageFor, voteButton } from './spotlight-shared.js';-const AGENT_3D_LOADER = 'https://three.ws/agent-3d/latest/agent-3d.js';const PAGE_SIZE = 24;const els = {@@ -31,27 +44,20 @@ const els = {panel: document.getElementById('sp-submit-panel'),panelToggle: document.getElementById('sp-submit-toggle'),panelAuth: document.getElementById('sp-submit-auth'),- agentSelect: document.getElementById('sp-agent'),- agentHint: document.getElementById('sp-agent-hint'),- categorySelect: document.getElementById('sp-category'),+ fields: document.getElementById('sp-fields'),cancel: document.getElementById('sp-cancel'),submit: document.getElementById('sp-submit'),formNote: document.getElementById('sp-form-note'),live: document.getElementById('sp-live'),};-const view = {- sort: 'trending',- category: null,- tag: null,- q: '',- offset: 0,-};+const view = { sort: 'trending', category: null, tag: null, q: '', offset: 0 };let total = 0;let categories = [];let totals = { entries: 0, builders: 0, votes: 0 };let loadToken = 0;+let formRefs = null;/* ── url state ────────────────────────────────────────────────────────── */@@ -87,8 +93,7 @@ function el(tag, props = {}, children = []) {else node.setAttribute(k, v === true ? '' : String(v));}for (const child of [].concat(children)) {- if (child == null) continue;- node.append(child);+ if (child != null) node.append(child);}return node;}@@ -101,135 +106,16 @@ function plural(n, one, many) {return `${n.toLocaleString()} ${n === 1 ? one : many}`;}-function relativeTime(iso) {- const then = new Date(iso).getTime();- if (!Number.isFinite(then)) return '';- const mins = Math.round((Date.now() - then) / 60000);- if (mins < 1) return 'just now';- if (mins < 60) return `${mins}m ago`;- const hours = Math.round(mins / 60);- if (hours < 24) return `${hours}h ago`;- const days = Math.round(hours / 24);- if (days < 30) return `${days}d ago`;- return new Date(then).toLocaleDateString(undefined, { month: 'short', year: 'numeric' });-}--// Deterministic hue from the agent id: the same agent keeps the same monogram-// colour on every card, in every session, without storing anything.-function hueOf(id) {- let h = 0;- for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) % 360;- return h;-}--function monogram(agent) {- const hue = hueOf(agent.id || agent.name || 'agent');- const initials = (agent.name || '?')- .split(/\s+/)- .slice(0, 2)- .map((w) => w[0])- .join('')- .toUpperCase();- const node = el('div', { class: 'sp-mono', 'aria-hidden': 'true', text: initials });- node.style.background = `linear-gradient(140deg, hsl(${hue} 62% 26%), hsl(${(hue + 48) % 360} 55% 14%))`;- return node;-}-function categoryLabel(slug) {return categories.find((c) => c.slug === slug)?.label || slug;}-/* ── the featured stage ───────────────────────────────────────────────── */--let agent3dRequested = false;-function loadAgent3d() {- if (agent3dRequested) return;- agent3dRequested = true;- const s = document.createElement('script');- s.type = 'module';- s.src = AGENT_3D_LOADER;- document.head.appendChild(s);+function onVoted(entry) {+ totals.votes += entry.voted_by_me ? 1 : -1;+ renderStats();}-// Hide the still only once <agent-3d> has painted a canvas of its own. There is-// no documented ready event on the component, and a canvas in the DOM is the-// one signal that means the model is genuinely on screen. Give up after a-// bounded wait and leave the still in place, which is the correct outcome when-// the GLB never arrives.-function revealWhenPainted(viewer, still) {- let settled = false;- const done = () => {- if (settled) return;- settled = true;- observer.disconnect();- clearTimeout(timer);- still.classList.add('is-hidden');- };- const painted = () =>- Boolean(viewer.querySelector('canvas') || viewer.shadowRoot?.querySelector('canvas'));-- const observer = new MutationObserver(() => {- if (painted()) done();- });- observer.observe(viewer, { childList: true, subtree: true });- const timer = setTimeout(() => {- observer.disconnect();- }, 15000);- if (painted()) done();-}--function stageFor(entry) {- const stage = el('div', { class: 'sp-stage' });- stage.append(el('span', { class: 'sp-stage-badge', text: "Editor's pick" }));-- // The still image goes in first and stays until the 3D viewer has actually- // painted a canvas. A GLB can fail to load for reasons this page does not- // control (a cold CDN, a blocked origin, no WebGL on the device), and a- // silently empty hero is the worst version of that failure.- const still = entry.agent.thumbnail- ? el('img', {- class: 'sp-stage-still',- src: entry.agent.thumbnail,- alt: `${entry.agent.name} avatar`,- loading: 'lazy',- decoding: 'async',- })- : monogram(entry.agent);- stage.append(still);-- if (!entry.agent.glb_url) return stage;-- // Mounted only when the stage is actually on screen. Below-the-fold WebGL on- // a browse page costs a visitor real frames for something they may never- // scroll to.- const mount = () => {- loadAgent3d();- const viewer = el('agent-3d', {- body: entry.agent.glb_url,- autorotate: 'true',- 'camera-controls': 'true',- 'aria-label': `${entry.agent.name} in 3D`,- });- stage.append(viewer);- revealWhenPainted(viewer, still);- };-- if ('IntersectionObserver' in window) {- const io = new IntersectionObserver(- (entries, obs) => {- if (entries.some((e) => e.isIntersecting)) {- obs.disconnect();- mount();- }- },- { rootMargin: '200px' },- );- io.observe(stage);- } else {- mount();- }- return stage;-}+/* ── featured ─────────────────────────────────────────────────────────── */function renderFeatured(entries) {if (!entries.length) {@@ -239,27 +125,18 @@ function renderFeatured(entries) {}const entry = entries[0];const copy = el('div', { class: 'sp-featured-copy' }, [- el('h3', {}, [el('a', { href: `/agents/${entry.agent.id}`, text: entry.title })]),+ el('h3', {}, [el('a', { href: entryPath(entry), text: entry.title })]),el('p', { text: entry.tagline }),entry.story ? el('p', { class: 'sp-featured-story', text: entry.story }) : null,el('div', { class: 'sp-card-meta' }, metaBits(entry)),el('div', { class: 'sp-ctas' }, [- el('a', { class: 'sp-btn sp-btn-primary', href: `/agents/${entry.agent.id}`, text: `Open ${entry.agent.name}` }),- el('a', { class: 'sp-btn', href: `/agents/${entry.agent.id}/profile`, text: 'Read the profile' }),- entry.demo_url- ? el('a', {- class: 'sp-btn',- href: entry.demo_url,- target: '_blank',- rel: 'noopener nofollow ugc',- text: 'See it live',- })- : null,- voteButton(entry),+ el('a', { class: 'sp-btn sp-btn-primary', href: entryPath(entry), text: 'Read the write-up' }),+ el('a', { class: 'sp-btn', href: `/agents/${entry.agent.id}`, text: `Open ${entry.agent.name}` }),+ voteButton(entry, { announce, onVoted }),]),]);- els.featuredBody.replaceChildren(stageFor(entry), copy);+ els.featuredBody.replaceChildren(stageFor(entry, { badge: "Editor's pick" }), copy);els.featured.hidden = false;}@@ -269,10 +146,11 @@ function metaBits(entry) {const bits = [el('span', {}, [el('strong', { text: entry.agent.name })])];if (entry.builder?.name) {bits.push(el('span', { 'aria-hidden': 'true', text: '·' }));- const by = entry.builder.profile_url- ? el('a', { href: entry.builder.profile_url, text: `by ${entry.builder.name}` })- : el('span', { text: `by ${entry.builder.name}` });- bits.push(by);+ bits.push(+ entry.builder.profile_url+ ? el('a', { href: entry.builder.profile_url, text: `by ${entry.builder.name}` })+ : el('span', { text: `by ${entry.builder.name}` }),+ );}if (entry.agent.chat_count > 0) {bits.push(el('span', { 'aria-hidden': 'true', text: '·' }));@@ -286,76 +164,25 @@ function metaBits(entry) {return bits;}-function voteButton(entry) {- const count = el('span', { class: 'sp-vote-count', text: String(entry.vote_count) });- const btn = el(- 'button',- {- type: 'button',- class: 'sp-vote',- 'aria-pressed': String(Boolean(entry.voted_by_me)),- 'aria-label': `Upvote ${entry.title}`,- title: 'Upvote',- },- [el('span', { class: 'sp-vote-caret', 'aria-hidden': 'true', text: '▲' }), count],- );-- btn.addEventListener('click', async (event) => {- event.preventDefault();- event.stopPropagation();- btn.classList.add('is-busy');- try {- const res = await apiFetch('/api/showcase/vote', {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({ id: entry.id }),- allowAnonymous: true,- });- if (res.status === 401) {- location.href = `/login?next=${encodeURIComponent(location.pathname + location.search)}`;- return;- }- const data = await res.json().catch(() => null);- if (!res.ok) {- announce(data?.error?.message || 'the vote did not go through');- return;- }- entry.vote_count = data.vote_count;- entry.voted_by_me = data.voted;- count.textContent = String(data.vote_count);- btn.setAttribute('aria-pressed', String(data.voted));- announce(`${data.voted ? 'Upvoted' : 'Removed your upvote from'} ${entry.title}. ${data.vote_count} total.`);- } catch {- announce('the vote did not go through; check your connection');- } finally {- btn.classList.remove('is-busy');- }- });-- return btn;-}-function cardFor(entry) {const art = el('div', { class: 'sp-card-art' });- if (entry.agent.thumbnail) {- art.append(- el('img', {- src: entry.agent.thumbnail,- alt: `${entry.agent.name} avatar`,- loading: 'lazy',- decoding: 'async',- }),- );- } else {- art.append(monogram(entry.agent));- }-- const badges = el('div', { class: 'sp-card-badges' }, [- el('span', { class: 'sp-badge', text: categoryLabel(entry.category) }),- entry.agent.is_registered ? el('span', { class: 'sp-badge sp-badge-onchain', text: 'On-chain' }) : null,- entry.source === 'curated' ? el('span', { class: 'sp-badge sp-badge-curated', text: 'Curated' }) : null,- ]);- art.append(badges);+ art.append(+ entry.agent.thumbnail+ ? el('img', {+ src: entry.agent.thumbnail,+ alt: `${entry.agent.name} avatar`,+ loading: 'lazy',+ decoding: 'async',+ })+ : monogram(entry.agent),+ );+ art.append(+ el('div', { class: 'sp-card-badges' }, [+ el('span', { class: 'sp-badge', text: categoryLabel(entry.category) }),+ entry.agent.is_registered ? el('span', { class: 'sp-badge sp-badge-onchain', text: 'On-chain' }) : null,+ entry.source === 'curated' ? el('span', { class: 'sp-badge sp-badge-curated', text: 'Curated' }) : null,+ ]),+ );const tags = entry.tags.length? el(@@ -380,23 +207,27 @@ function cardFor(entry) {: null;const body = el('div', { class: 'sp-card-body' }, [- el('h3', { class: 'sp-card-title' }, [el('a', { href: `/agents/${entry.agent.id}`, text: entry.title })]),+ el('h3', { class: 'sp-card-title' }, [el('a', { href: entryPath(entry), text: entry.title })]),el('p', { class: 'sp-card-tagline', text: entry.tagline }),el('div', { class: 'sp-card-meta' }, metaBits(entry)),tags,]);const links = el('div', { class: 'sp-card-links' }, [- el('a', { href: `/agents/${entry.agent.id}`, text: 'Open' }),- el('a', { href: `/agents/${entry.agent.id}/profile`, text: 'Profile' }),+ el('a', { href: `/agents/${entry.agent.id}`, text: 'Open agent' }),entry.demo_url? el('a', { href: entry.demo_url, target: '_blank', rel: 'noopener nofollow ugc', text: 'Demo' }): null,+ // Only an owner sees this, and it goes to the entry page where the edit+ // form lives, so there is exactly one place an entry is written.+ entry.editable_by_me ? el('a', { href: `${entryPath(entry)}?edit=1`, text: 'Edit' }) : null,]);- const foot = el('div', { class: 'sp-card-foot' }, [links, voteButton(entry)]);-- return el('article', { class: 'sp-card' }, [art, body, foot]);+ return el('article', { class: 'sp-card' }, [+ art,+ body,+ el('div', { class: 'sp-card-foot' }, [links, voteButton(entry, { announce, onVoted })]),+ ]);}/* ── loading ──────────────────────────────────────────────────────────── */@@ -412,7 +243,7 @@ function renderEmpty() {el('p', {text: filtered? 'No showcased agent matches this filter. Clear it to see everything the community has published.'- : 'No one has claimed the first slot. Build an agent, make it public, and write up what it does; the first entry gets the featured stage.',+ : 'No one has claimed the first slot. Build an agent, make it public, and write up what it does: the first entry gets the featured stage.',}),]);box.append(@@ -428,6 +259,7 @@ function renderEmpty() {view.offset = 0;if (els.search) els.search.value = '';writeUrl();+ renderCategories();load();},})@@ -447,12 +279,7 @@ function renderError(message) {el('div', { class: 'sp-error' }, [el('h3', { text: 'The showcase did not load' }),el('p', { text: message }),- el('button', {- type: 'button',- class: 'sp-btn sp-btn-primary',- text: 'Try again',- onclick: () => load(),- }),+ el('button', { type: 'button', class: 'sp-btn sp-btn-primary', text: 'Try again', onclick: () => load() }),]),);}@@ -475,15 +302,15 @@ async function load({ append = false } = {}) {if (view.q) p.set('q', view.q);try {- const res = await apiFetch(`/api/showcase/list?${p}`, { allowAnonymous: true });+ const res = await apiFetch(`/api/spotlight/list?${p}`, { allowAnonymous: true });if (token !== loadToken) return;if (res.status === 503) {- renderEmpty();els.grid.replaceChildren();+ renderEmpty();return;}const data = await res.json().catch(() => null);- if (!res.ok) throw new Error(data?.error?.message || `the showcase returned ${res.status}`);+ if (!res.ok) throw new Error(errorMessage(data, `the showcase returned ${res.status}`));const entries = Array.isArray(data.entries) ? data.entries : [];total = Number(data.total) || 0;@@ -515,19 +342,11 @@ function renderStats() {els.stats.replaceChildren();return;}+ const stat = (value, label) => el('div', {}, [el('dd', { text: value.toLocaleString() }), el('dt', { text: label })]);els.stats.replaceChildren(- el('div', {}, [- el('dd', { text: totals.entries.toLocaleString() }),- el('dt', { text: totals.entries === 1 ? 'agent showcased' : 'agents showcased' }),- ]),- el('div', {}, [- el('dd', { text: totals.builders.toLocaleString() }),- el('dt', { text: totals.builders === 1 ? 'builder' : 'builders' }),- ]),- el('div', {}, [- el('dd', { text: totals.votes.toLocaleString() }),- el('dt', { text: totals.votes === 1 ? 'upvote' : 'upvotes' }),- ]),+ stat(totals.entries, totals.entries === 1 ? 'agent showcased' : 'agents showcased'),+ stat(totals.builders, totals.builders === 1 ? 'builder' : 'builders'),+ stat(totals.votes, totals.votes === 1 ? 'upvote' : 'upvotes'),);}@@ -535,7 +354,7 @@ function renderStats() {async function loadFeatured() {try {- const res = await apiFetch('/api/showcase/list?featured=1&limit=1&sort=trending', { allowAnonymous: true });+ const res = await apiFetch('/api/spotlight/list?featured=1&limit=1&sort=trending', { allowAnonymous: true });if (!res.ok) return;const data = await res.json().catch(() => null);renderFeatured(Array.isArray(data?.entries) ? data.entries : []);@@ -557,10 +376,16 @@ function renderCategories() {...categories.filter((c) => c.count > 0 || c.slug === view.category).map((c) =>- el('button', { type: 'button', class: 'sp-cat', 'aria-pressed': String(view.category === c.slug), onclick: () => selectCategory(c.slug) }, [- el('span', { text: c.label }),- el('span', { class: 'sp-cat-count', text: String(c.count) }),- ]),+ el(+ 'button',+ {+ type: 'button',+ class: 'sp-cat',+ 'aria-pressed': String(view.category === c.slug),+ onclick: () => selectCategory(c.slug),+ },+ [el('span', { text: c.label }), el('span', { class: 'sp-cat-count', text: String(c.count) })],+ ),),);}@@ -575,26 +400,19 @@ function selectCategory(slug) {async function loadCategories() {try {- const res = await apiFetch('/api/showcase/categories', { allowAnonymous: true });+ const res = await apiFetch('/api/spotlight/categories', { allowAnonymous: true });if (!res.ok) return;const data = await res.json().catch(() => null);categories = Array.isArray(data?.categories) ? data.categories : [];if (data?.totals) totals = data.totals;renderCategories();renderStats();- fillCategorySelect();+ if (formRefs) fillCategories(formRefs, categories);} catch {categories = [];}}-function fillCategorySelect() {- if (!els.categorySelect || !categories.length) return;- els.categorySelect.replaceChildren(- ...categories.map((c) => el('option', { value: c.slug, text: c.label })),- );-}-/* ── submission ───────────────────────────────────────────────────────── */let eligibleLoaded = false;@@ -609,56 +427,58 @@ function openPanel(open) {async function loadEligible() {eligibleLoaded = true;- els.agentSelect.replaceChildren(el('option', { value: '', text: 'Loading your agents…' }));+ formRefs.agentSelect.replaceChildren(new Option('Loading your agents…', ''));try {- const res = await apiFetch('/api/showcase/eligible', { allowAnonymous: true });+ const res = await apiFetch('/api/spotlight/eligible', { allowAnonymous: true });if (res.status === 401) {eligibleLoaded = false;showPanelAuth();return;}const data = await res.json().catch(() => null);- if (!res.ok) throw new Error(data?.error?.message || 'could not load your agents');+ if (!res.ok) throw new Error(errorMessage(data, 'could not load your agents'));if (Array.isArray(data.categories) && data.categories.length && !categories.length) {categories = data.categories.map((c) => ({ ...c, count: 0 }));- fillCategorySelect();+ renderCategories();}+ fillCategories(formRefs, categories);const agents = Array.isArray(data.agents) ? data.agents : [];if (!agents.length) {- els.agentSelect.replaceChildren(el('option', { value: '', text: 'No eligible agents' }));- els.agentSelect.disabled = true;+ formRefs.agentSelect.replaceChildren(new Option('No eligible agents', ''));+ formRefs.agentSelect.disabled = true;els.submit.disabled = true;- els.agentHint.replaceChildren(- document.createTextNode('Every public agent you own is already showcased, or you have not made one yet. '),+ formRefs.agentHint.replaceChildren(+ document.createTextNode(+ 'Every public agent you own is already showcased, or you have not made one yet. ',+ ),el('a', { href: '/create-agent', text: 'Create an agent' }),document.createTextNode('.'),);return;}- els.agentSelect.disabled = false;+ formRefs.agentSelect.disabled = false;els.submit.disabled = false;- els.agentSelect.replaceChildren(- el('option', { value: '', text: 'Choose an agent…' }),- ...agents.map((a) => el('option', { value: a.id, text: a.name })),+ formRefs.agentSelect.replaceChildren(+ new Option('Choose an agent…', ''),+ ...agents.map((a) => new Option(a.name, a.id)),);- els.agentHint.textContent = `${plural(agents.length, 'agent', 'agents')} you can showcase. Only public agents are listed.`;+ formRefs.agentHint.textContent = `${plural(agents.length, 'agent', 'agents')} you can showcase. Only public agents are listed.`;// Pre-fill the one-liner from the agent's own description: the builder// already wrote it once, and an empty field is the main reason a// submission gets abandoned halfway.- els.agentSelect.addEventListener('change', () => {- const chosen = agents.find((a) => a.id === els.agentSelect.value);- const tagline = document.getElementById('sp-tagline');- if (chosen?.description && tagline && !tagline.value.trim()) {- tagline.value = chosen.description.replace(/\s+/g, ' ').trim().slice(0, 160);- tagline.dispatchEvent(new Event('input'));+ formRefs.agentSelect.addEventListener('change', () => {+ const chosen = agents.find((a) => a.id === formRefs.agentSelect.value);+ if (chosen?.description && !formRefs.tagline.value.trim()) {+ formRefs.tagline.value = chosen.description.replace(/\s+/g, ' ').trim().slice(0, 160);+ formRefs.tagline.dispatchEvent(new Event('input'));}});} catch (err) {eligibleLoaded = false;- els.agentSelect.replaceChildren(el('option', { value: '', text: 'Could not load your agents' }));+ formRefs.agentSelect.replaceChildren(new Option('Could not load your agents', ''));setNote(err?.message || 'could not load your agents', 'error');}}@@ -674,8 +494,8 @@ function showPanelAuth() {}),el('a', { class: 'sp-btn sp-btn-sm', href: '/register', text: 'Create an account' }),);- els.agentSelect.replaceChildren(el('option', { value: '', text: 'Sign in first' }));- els.agentSelect.disabled = true;+ formRefs.agentSelect.replaceChildren(new Option('Sign in first', ''));+ formRefs.agentSelect.disabled = true;els.submit.disabled = true;}@@ -685,60 +505,25 @@ function setNote(message, tone) {else delete els.formNote.dataset.tone;}-function parseTags(raw) {- return raw- .split(',')- .map((t) => t.trim().toLowerCase().replace(/\s+/g, '-'))- .filter(Boolean)- .slice(0, 6);-}-async function onSubmit(event) {event.preventDefault();- const agentId = els.agentSelect.value;- if (!agentId) return setNote('pick which agent you are showcasing', 'error');-- const payload = {- agentId,- title: document.getElementById('sp-title').value.trim(),- tagline: document.getElementById('sp-tagline').value.trim(),- story: document.getElementById('sp-story').value.trim() || null,- demoUrl: document.getElementById('sp-demo').value.trim() || null,- category: els.categorySelect.value,- tags: parseTags(document.getElementById('sp-tags').value),- };-- if (payload.title.length < 3) return setNote('the headline needs at least 3 characters', 'error');- if (payload.tagline.length < 10) return setNote('the one-liner needs at least 10 characters', 'error');+ const payload = readValues(formRefs);+ const problem = validate(payload);+ if (problem) return setNote(problem, 'error');els.submit.disabled = true;setNote('Publishing…');try {- const res = await apiFetch('/api/showcase/submit', {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify(payload),- allowAnonymous: true,- });- if (res.status === 401) {+ const entry = await saveEntry(payload);+ setNote('Published. Taking you to your entry…', 'success');+ announce(`${payload.title} is now in the showcase.`);+ location.href = entryPath(entry);+ } catch (err) {+ if (err.unauthorized) {showPanelAuth();setNote('sign in to publish', 'error');return;}- const data = await res.json().catch(() => null);- if (!res.ok) throw new Error(data?.error?.message || `the submission returned ${res.status}`);-- setNote('Published. Your agent is in the showcase.', 'success');- els.panel.reset();- eligibleLoaded = false;- view.offset = 0;- view.sort = 'new';- syncSortButtons();- writeUrl();- await Promise.all([load(), loadCategories()]);- announce(`${payload.title} is now in the showcase.`);- setTimeout(() => openPanel(false), 1200);- } catch (err) {setNote(err?.message || 'the submission did not go through', 'error');} finally {els.submit.disabled = false;@@ -755,19 +540,9 @@ function syncSortButtons() {}}-function wireCharCounters() {- for (const counter of document.querySelectorAll('[data-count-for]')) {- const field = document.getElementById(counter.dataset.countFor);- if (!field) continue;- const update = () => {- counter.textContent = String(field.value.length);- };- field.addEventListener('input', update);- update();- }-}-function wire() {+ formRefs = buildFields(els.fields, { prefix: 'sp', withAgentPicker: true });+for (const btn of els.sorts) {btn.addEventListener('click', () => {if (view.sort === btn.dataset.sort) return;@@ -818,7 +593,8 @@ function wire() {load();});- wireCharCounters();+ // Deep link from a card's "Edit" affordance or an empty state.+ if (new URLSearchParams(location.search).get('submit') === '1') openPanel(true);}readUrl();diff --git a/tests/showcase-ranking.test.js b/tests/spotlight-ranking.test.jssimilarity index 89%rename from tests/showcase-ranking.test.jsrename to tests/spotlight-ranking.test.jsindex 68cf57967..9dc376b95 100644--- a/tests/showcase-ranking.test.js+++ b/tests/spotlight-ranking.test.js@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest';import { readFileSync } from 'node:fs';-import { CATEGORIES, GRAVITY, SORTS, isCategory, mapEntry, trendingScore } from '../api/_lib/showcase-store.js';+import { CATEGORIES, GRAVITY, SORTS, isCategory, mapEntry, trendingScore } from '../api/_lib/spotlight-store.js';const DAY = 86_400_000;const NOW = Date.UTC(2026, 8, 1, 12, 0, 0);@@ -54,13 +54,21 @@ describe('spotlight trending score', () => {describe('spotlight SQL and JS agree', () => {it('computes the same expression in the ORDER BY as trendingScore does', () => {- const source = readFileSync(new URL('../api/_lib/showcase-store.js', import.meta.url), 'utf8');+ const source = readFileSync(new URL('../api/_lib/spotlight-store.js', import.meta.url), 'utf8');// The ranking exists twice by necessity (Postgres orders the page, JS// reports the score on each row). Pin the SQL shape so a change to one// without the other fails here instead of silently reordering the page.expect(source).toMatch(/\(coalesce\(v\.n, 0\) \+ 1\)::numeric/);expect(source).toMatch(/power\(extract\(epoch from \(now\(\) - s\.created_at\)\)::numeric \/ 86400\.0 \+ 1, \$\{GRAVITY\}::numeric\)/);});++ it('orders totally, so the same query cannot return a different page', () => {+ const source = readFileSync(new URL('../api/_lib/spotlight-store.js', import.meta.url), 'utf8');+ // Entries seeded in one batch tie on score AND created_at. Without a+ // terminal tie-break the planner picks, and the page reshuffles between+ // identical requests.+ expect(source).toMatch(/\(coalesce\(ch\.n, 0\) \+ coalesce\(ac\.n, 0\)\) desc,\n\t\t\ts\.id/);+ });});describe('spotlight categories', () => {diff --git a/vercel.json b/vercel.jsonindex 90f81765c..b555663df 100644--- a/vercel.json+++ b/vercel.json@@ -941,6 +941,21 @@"src": "/spotlight/?$","dest": "/spotlight.html"},+ {+ "src": "/spotlight/([0-9a-fA-F-]{36})/?$",+ "has": [+ {+ "type": "header",+ "key": "user-agent",+ "value": "(?i).*(Twitterbot|facebookexternalhit|Slackbot|LinkedInBot|Discordbot|TelegramBot|WhatsApp|Googlebot|bingbot|Applebot|Pinterestbot|redditbot|Embedly|Quora|outbrain|vkShare|Iframely).*"+ }+ ],+ "dest": "/api/spotlight-og?id=$1"+ },+ {+ "src": "/spotlight/([0-9a-fA-F-]{36})/?$",+ "dest": "/spotlight-entry.html"+ },{"src": "/drops/([a-z0-9][a-z0-9-]*)/?$","dest": "/drop-collection.html"diff --git a/vite.config.js b/vite.config.jsindex bb20b3a98..90d5b6f8a 100644--- a/vite.config.js+++ b/vite.config.js@@ -542,6 +542,7 @@ const appConfig = {drops: resolve(__dirname, 'pages/drops.html'),'drop-collection': resolve(__dirname, 'pages/drop-collection.html'),spotlight: resolve(__dirname, 'pages/spotlight.html'),+ 'spotlight-entry': resolve(__dirname, 'pages/spotlight-entry.html'),app: resolve(__dirname, 'pages/app.html'),proof: resolve(__dirname, 'pages/proof.html'),stream: resolve(__dirname, 'pages/stream.html'),@@ -2149,6 +2150,9 @@ const appConfig = {/^\/markets\/robinhood\/coin\/0x[0-9a-fA-F]{40}\/?$/.test(path))filePath = resolve(root, 'pages/robinhood-coin.html');+ // /spotlight/:id → one Agent Spotlight entry (uuid).+ else if (!filePath && /^\/spotlight\/[0-9a-fA-F-]{36}\/?$/.test(path))+ filePath = resolve(root, 'pages/spotlight-entry.html');// /drops/:slug → one generative 3D collection. Declared ahead of the// /drop/:id rule below so the singular sealed-gift route and this// plural collection route can never shadow each other.