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(crews): crew directory, search API, and crews page
nirholas988c312edabc
diff --git a/api/_lib/crews-store.js b/api/_lib/crews-store.jsindex 3b37c9549..37b9e08f5 100644--- a/api/_lib/crews-store.js+++ b/api/_lib/crews-store.js@@ -9,6 +9,7 @@// single-purpose queries the api/crews/* endpoints wrap thinly.import { sql } from './db.js';+import { publicUrl, thumbnailUrl } from './r2.js';// Columns safe to expose for any account — never leak email, wallet, plan, or// admin flags through a crew roster. Built lazily so importing this module never@@ -34,6 +35,18 @@ export function normalizeTag(raw) {return t.length >= 2 && t.length <= 6 ? t : '';}+// Tags that would collide with a route segment. `/api/crews/:tag` and+// `/crews/:tag` both resolve an exact file or page before the dynamic segment+// (server/index.mjs precedence: exact file > [param].js), so a crew tagged+// SEARCH would be permanently unreachable at its own public URL. Refusing the+// tag at founding time is the only place this can be fixed without breaking an+// existing crew's link later.+const RESERVED_TAGS = new Set(['SEARCH', 'INDEX', 'API', 'ADMIN', 'NEW', 'ME', 'ALL', 'NULL']);++export function isReservedTag(tag) {+ return RESERVED_TAGS.has(String(tag || '').toUpperCase());+}+function normalizeName(raw) {return String(raw || '').replace(/[\x00-\x1f\x7f]+/g, ' ')@@ -98,7 +111,9 @@ export async function crewTagsFor(accountIds) {}// The full roster for a crew, owner first then by join time. Each entry carries-// the public profile + role; presence is merged at the endpoint layer (Redis).+// the public profile + role + the member's standee (their agent's 3D avatar, so+// the Crew HQ room can render the roster in 3D). Presence is merged at the+// endpoint layer (Redis).export async function listMembers(crewId) {const rows = await sql`select ${publicUserCols()}, m.role, m.joined_at@@ -107,7 +122,144 @@ export async function listMembers(crewId) {where m.crew_id = ${crewId} and u.deleted_at is nullorder by (m.role = 'owner') desc, m.joined_at asc`;- return rows.map((r) => ({ ...toProfile(r), role: r.role, joinedAt: r.joined_at }));+ const standees = await standeesFor(rows.map((r) => r.id));+ return rows.map((r) => ({+ ...toProfile(r),+ role: r.role,+ joinedAt: r.joined_at,+ standee: standees[r.id] || null,+ }));+}++// The 3D figure that represents each account in the Crew HQ room: their agent+// and, when that agent owns a publicly readable avatar, the GLB the viewer+// loads. One row per account, preferring an agent that actually has a model+// over an older one that does not, so a member with several agents stands as+// the one that can be rendered.+//+// Visibility is enforced here exactly as api/agents.js decorate() enforces it:+// only 'public' / 'unlisted' avatars ever emit a URL, so a private model can+// never leak through a crew roster. An account with no agent, or no renderable+// avatar, resolves to a null modelUrl — the page falls back to the default rig+// and offers to claim one, which is the whole point of showing the gap.+export async function standeesFor(accountIds) {+ const ids = [...new Set((accountIds || []).filter(Boolean))];+ if (!ids.length) return {};+ let rows;+ try {+ rows = await sql`+ select distinct on (i.user_id)+ i.user_id, i.id as agent_id, i.name as agent_name,+ a.storage_key, a.thumbnail_key, a.visibility+ from agent_identities i+ left join avatars a on a.id = i.avatar_id and a.deleted_at is null+ where i.user_id = any(${ids}) and i.deleted_at is null+ order by i.user_id,+ (a.storage_key is not null and a.visibility in ('public', 'unlisted')) desc,+ i.created_at asc+ `;+ } catch (err) {+ // A roster that renders without standees beats a 500. Any schema drift in+ // the agent tables degrades the room to the default rig, never the page.+ if (isMissingRelation(err)) return {};+ throw err;+ }+ const out = {};+ for (const r of rows) {+ const readable = r.visibility === 'public' || r.visibility === 'unlisted';+ out[r.user_id] = {+ agentId: r.agent_id,+ agentName: r.agent_name || null,+ modelUrl: readable && r.storage_key ? publicUrl(r.storage_key) : null,+ thumbUrl: readable && r.thumbnail_key ? thumbnailUrl(r.thumbnail_key) : null,+ };+ }+ return out;+}++// True when an error is Postgres telling us a table/column isn't there — the+// signal every crews endpoint uses to degrade instead of 500 while a migration+// is still rolling out.+export function isMissingRelation(err) {+ const m = err?.message || '';+ return m.includes('relation') || m.includes('does not exist') || err?.code === '42P01';+}++// Public crew directory: every crew with at least one member, biggest first, so+// a visitor with no crew has somewhere to look before founding their own. Only+// public roster facts (tag, name, size, founding date, a few member faces).+export async function listCrewDirectory(limit = 24) {+ const cap = Math.min(Math.max(Number(limit) || 24, 1), 60);+ const rows = await sql`+ select c.id, c.tag, c.name, c.created_at,+ count(m.account_id)::int as member_count+ from crews c+ join crew_members m on m.crew_id = c.id+ group by c.id, c.tag, c.name, c.created_at+ order by count(m.account_id) desc, c.created_at asc+ limit ${cap}+ `;+ if (!rows.length) return [];++ const faces = await sql`+ select m.crew_id, u.id, u.display_name, u.username, u.avatar_url+ from crew_members m+ join users u on u.id = m.account_id+ where m.crew_id = any(${rows.map((r) => r.id)}) and u.deleted_at is null+ order by (m.role = 'owner') desc, m.joined_at asc+ `;+ const byCrew = new Map();+ for (const f of faces) {+ const list = byCrew.get(f.crew_id) || [];+ if (list.length < 5) list.push(toProfile(f));+ byCrew.set(f.crew_id, list);+ }+ return rows.map((r) => ({+ tag: r.tag,+ name: r.name,+ createdAt: r.created_at,+ memberCount: r.member_count,+ faces: byCrew.get(r.id) || [],+ }));+}++// Search accounts to invite. Mirrors friends-store.searchUsers but annotates+// what a crew owner actually needs to know before clicking: whether the person+// is already in a crew (and which), and whether this crew already invited them.+// Both make the invite button render its true state instead of failing on click.+export async function searchInvitees(meId, q, limit = 12) {+ const term = String(q || '').trim();+ if (term.length < 2) return [];+ const like = `%${term.replace(/[%_]/g, (m) => `\\${m}`)}%`;+ const rows = await sql`+ select ${publicUserCols()}+ from users u+ where u.deleted_at is null+ and u.id <> ${meId}+ and (u.display_name ilike ${like} or u.username ilike ${like})+ order by+ (lower(u.username) = lower(${term}) or lower(u.display_name) = lower(${term})) desc,+ length(coalesce(u.username, u.display_name)) asc+ limit ${Math.min(Math.max(Number(limit) || 12, 1), 25)}+ `;+ if (!rows.length) return [];++ const ids = rows.map((r) => r.id);+ const tags = await crewTagsFor(ids);+ const myCrew = await getMyCrew(meId);+ const invited = myCrew+ ? new Set(+ (+ await sql`select invitee_id from crew_invites where crew_id = ${myCrew.id} and invitee_id = any(${ids})`+ ).map((r) => r.invitee_id),+ )+ : new Set();++ return rows.map((r) => ({+ ...toProfile(r),+ crew: tags[r.id] || null,+ invited: invited.has(r.id),+ }));}// Public view of a crew by tag: identity + roster. Returns null if no such tag.@@ -152,7 +304,8 @@ export async function listInvites(accountId) {// duplicate tag and an account that's already in a crew (one-crew-per-account).export async function createCrew(accountId, rawTag, rawName) {const tag = normalizeTag(rawTag);- if (!tag) throw err('Tag must be 2–6 letters or digits.', 400, 'bad_tag');+ if (!tag) throw err('Tag must be 2-6 letters or digits.', 400, 'bad_tag');+ if (isReservedTag(tag)) throw err('That tag is reserved.', 409, 'tag_reserved');const name = normalizeName(rawName) || tag;if (name.length < 2) throw err('Crew name is too short.', 400, 'bad_name');diff --git a/api/crews/[tag].js b/api/crews/[tag].jsindex be0e01e30..ba147d680 100644--- a/api/crews/[tag].js+++ b/api/crews/[tag].js@@ -7,7 +7,7 @@import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { readPresence } from '../_lib/presence-store.js';-import { getCrewByTag, normalizeTag } from '../_lib/crews-store.js';+import { getCrewByTag, normalizeTag, isMissingRelation } from '../_lib/crews-store.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;@@ -25,9 +25,7 @@ export default wrap(async (req, res) => {try {crew = await getCrewByTag(tag);} catch (err) {- if (err?.message?.includes('relation') || err?.message?.includes('does not exist')) {- return error(res, 404, 'not_found', 'no such crew');- }+ if (isMissingRelation(err)) return error(res, 404, 'not_found', 'no such crew');throw err;}if (!crew) return error(res, 404, 'not_found', 'no such crew');diff --git a/api/crews/directory.js b/api/crews/directory.jsnew file mode 100644index 000000000..2a68e32d7--- /dev/null+++ b/api/crews/directory.js@@ -0,0 +1,35 @@+// GET /api/crews/directory?limit=24+// The public crew directory: every crew that has members, biggest first. This+// is what a visitor with no crew sees — somewhere to look before deciding to+// found one, and the only way a crew is discoverable without knowing its tag.+//+// Public and cacheable: a roster is public exactly like the agent gallery, and+// nothing here is caller-specific, so it answers for anonymous visitors too.++import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { listCrewDirectory, isMissingRelation } from '../_lib/crews-store.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://x');+ const limit = Number(url.searchParams.get('limit')) || 24;++ let crews;+ try {+ crews = await listCrewDirectory(limit);+ } catch (err) {+ // Before the crews migration lands there are no crews, which is an empty+ // directory rather than an outage.+ if (isMissingRelation(err)) crews = [];+ else throw err;+ }++ res.setHeader('Cache-Control', 'public, max-age=30, s-maxage=60, stale-while-revalidate=300');+ return json(res, 200, { data: { crews } });+});diff --git a/api/crews/index.js b/api/crews/index.jsindex 1540e5857..caa2f4ee9 100644--- a/api/crews/index.js+++ b/api/crews/index.js@@ -27,6 +27,7 @@ import {declineInvite,leaveCrew,kickMember,+ isMissingRelation,} from '../_lib/crews-store.js';function isUuid(v) {@@ -99,10 +100,8 @@ async function crewWithPresence(me) {crew = await getMyCrew(me);invites = await listInvites(me);} catch (err) {- // Crew tables may not be migrated yet — return an empty view rather than 500.- if (err?.message?.includes('relation') || err?.message?.includes('does not exist')) {- return EMPTY;- }+ // Crew tables may not be migrated yet: return an empty view rather than 500.+ if (isMissingRelation(err)) return EMPTY;throw err;}if (!crew) return { crew: null, members: [], invites: invites || [] };diff --git a/api/crews/search.js b/api/crews/search.jsnew file mode 100644index 000000000..ce1721235--- /dev/null+++ b/api/crews/search.js@@ -0,0 +1,38 @@+// GET /api/crews/search?q=<term>+// Find accounts to invite to my crew. Each hit is annotated with what the+// inviter needs to decide before clicking: the crew they already belong to (a+// person can only be in one, so inviting them would fail) and whether my crew+// already has an invite out to them. The Crew HQ renders those as a disabled+// row with the real reason instead of letting the click 409.+//+// Auth required, and the caller must be in a crew — searching people to invite+// when you have no crew to invite them to is a dead path, so it is closed here+// rather than rendered and then rejected on submit.++import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { resolveAccount } from '../_lib/account-auth.js';+import { getMyCrew, searchInvitees, isMissingRelation } from '../_lib/crews-store.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const auth = await resolveAccount(req, res);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');++ const url = new URL(req.url, 'http://x');+ const q = url.searchParams.get('q') || '';++ try {+ const crew = await getMyCrew(auth.userId);+ if (!crew) return error(res, 400, 'no_crew', 'found or join a crew before inviting');+ return json(res, 200, { data: { results: await searchInvitees(auth.userId, q) } });+ } catch (err) {+ if (isMissingRelation(err)) return json(res, 200, { data: { results: [] } });+ throw err;+ }+});diff --git a/pages/crews.html b/pages/crews.htmlnew file mode 100644index 000000000..65118899c--- /dev/null+++ b/pages/crews.html@@ -0,0 +1,144 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <script>/* three.ws theme boot: no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+ <title>Crew HQ · three.ws</title>+ <meta name="description" content="Found a crew, invite your people, and watch the whole roster stand in one 3D headquarters. Every member appears as their own agent, lit when they are live in the world." />+ <link rel="canonical" href="https://three.ws/crews" />+ <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="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <link rel="stylesheet" href="/src/crews.css" />+ <meta property="og:type" content="website" />+ <meta property="og:title" content="Crew HQ · three.ws" />+ <meta property="og:description" content="A crew is a group of people whose agents share one tag and one headquarters. Found one, invite your people, and see who is live in the world right now." />+ <meta property="og:url" content="https://three.ws/crews" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&t=Crew+HQ&d=Found+a+crew%2C+invite+your+people%2C+and+watch+the+whole+roster+stand+in+one+3D+headquarters.&p=%2Fcrews" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" content="Crew HQ · three.ws" />+ <meta name="twitter:description" content="Found a crew, invite your people, and watch the roster stand in one 3D headquarters." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&t=Crew+HQ&d=Found+a+crew%2C+invite+your+people%2C+and+watch+the+whole+roster+stand+in+one+3D+headquarters.&p=%2Fcrews" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="Crew HQ / three.ws" />+ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>+</head>+<body>+ <header class="site-header"><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="cw-wrap">+ <section class="cw-hero">+ <h1>Crew HQ</h1>+ <p>+ A crew is a group of accounts whose agents fly one tag. Every member stands in this+ headquarters as their own agent, lit when they are live in+ <a href="/play">the world</a> and unlit when they are not. Found one, invite your+ people, and share the link.+ </p>+ <p id="cw-public-note" class="cw-hint" hidden style="margin-top:10px"></p>+ </section>++ <div class="cw-error" id="cw-error" role="alert" hidden></div>++ <!-- The room. Hidden until there is a crew to put in it. -->+ <section class="cw-room" id="cw-room" aria-labelledby="cw-room-heading" hidden>+ <h2 id="cw-room-heading" class="cw-sr">The crew headquarters</h2>+ <div class="cw-room-head" id="cw-room-head"></div>+ <div class="cw-stage" id="cw-stage" role="list" aria-label="Crew members in the headquarters"></div>+ </section>++ <!-- Signed out. -->+ <section class="cw-panel" id="cw-signedout" hidden style="margin-top:22px">+ <h3>Sign in to found or join a crew</h3>+ <p class="cw-hint">+ A crew is tied to your account, not to a browser, so the roster and the tag follow you+ everywhere you sign in. Browsing the directory below needs no account at all.+ </p>+ <a class="cw-btn primary" href="/login?next=%2Fcrews">Sign in</a>+ </section>++ <!-- Invites addressed to me. Shown above everything else: an invite is the+ one thing on this page that expires socially. -->+ <section class="cw-panel" id="cw-invites-panel" hidden style="margin-top:22px">+ <h3>You have been invited</h3>+ <p class="cw-hint">Accepting one clears the rest. You can be in one crew at a time.</p>+ <div id="cw-invites"></div>+ </section>++ <div class="cw-cols">+ <!-- Roster -->+ <section class="cw-panel" id="cw-roster-panel" hidden>+ <h3>Roster</h3>+ <p class="cw-hint">+ Owner first, then by the day they joined. Presence is the same signal the in-world+ friends list reads, so “in world” means the same thing in both places.+ </p>+ <ul class="cw-roster" id="cw-roster"></ul>+ </section>++ <!-- Manage: invite people (any member may invite) -->+ <section class="cw-panel" id="cw-manage" hidden>+ <h3>Invite people</h3>+ <p class="cw-hint" id="cw-manage-hint"></p>+ <div class="cw-field">+ <label for="cw-invite-q">Search accounts</label>+ <input id="cw-invite-q" type="search" autocomplete="off" placeholder="Name or username" />+ <span class="cw-note">Someone already in a crew shows their tag instead of a button.</span>+ </div>+ <ul class="cw-results" id="cw-results">+ <li class="cw-empty">Type at least 2 characters of a name or username.</li>+ </ul>+ </section>++ <!-- Found a crew -->+ <section class="cw-panel" id="cw-found-panel" hidden>+ <h3>Found a crew</h3>+ <p class="cw-hint">+ Two steps. The tag is a short badge worn over your avatar in world; the name is what+ people read. Both are public and the tag is unique across the whole site.+ </p>+ <form id="cw-found" novalidate>+ <div class="cw-field">+ <label for="cw-found-tag">Tag</label>+ <input id="cw-found-tag" name="tag" maxlength="6" autocomplete="off" spellcheck="false"+ placeholder="NOVA" aria-describedby="cw-found-tag-note" />+ <span class="cw-note" id="cw-found-tag-note"></span>+ </div>+ <div class="cw-field">+ <label for="cw-found-name">Crew name</label>+ <input id="cw-found-name" name="name" maxlength="32" autocomplete="off"+ placeholder="Nova Collective" />+ <span class="cw-note">Up to 32 characters.</span>+ </div>+ <button type="submit" class="cw-btn primary" id="cw-found-submit" disabled>Found the crew</button>+ </form>+ </section>+ </div>++ <!-- Directory -->+ <section class="cw-panel" id="cw-dir-panel" hidden style="margin-top:16px">+ <h3>Every crew</h3>+ <p class="cw-hint">+ Biggest first. Open one to see its headquarters and who is standing in it right now.+ </p>+ <div class="cw-dir" id="cw-dir">+ <p class="cw-empty" style="grid-column:1/-1">Loading crews…</p>+ </div>+ </section>+ </main>++ <div class="cw-toast" id="cw-toast" role="status" aria-live="polite" data-show="false"></div>++ <script src="/brand.js" defer></script>+ <script type="module" src="/src/crews-page.js"></script>+ <script type="module" src="/i18n.js"></script>+</body>+</html>diff --git a/src/crews-page.js b/src/crews-page.jsnew file mode 100644index 000000000..28c14c651--- /dev/null+++ b/src/crews-page.js@@ -0,0 +1,720 @@+// Crew HQ (/crews and /crews/<TAG>) — the browser half of the crews system.+//+// The crews backend (api/crews/*, api/_lib/crews-store.js, the 2026-06-05+// migration) has been complete and reachable since the /play world shipped, but+// nothing in the product ever rendered it: the only reference anywhere in the+// frontend was a `if (a.openCrew)` branch in the game HUD that nothing supplied,+// so the button never drew. This page is the surface that closes that gap, and+// src/game/hud/index.js now supplies openCrew so the in-world button opens it.+//+// What makes it a room rather than a list: every member stands in the HQ as+// their own agent's avatar (crews-store.standeesFor resolves each account's+// renderable agent), lit when they are online in a realm and unlit when they are+// not. Presence is read from the same Redis the friends list reads, so "online"+// here means the same thing it means in-world.+//+// Three views share one page, chosen by URL and session:+// /crews signed out → the directory (public, no auth call needed)+// /crews signed in → my HQ, or the found-a-crew flow plus invites+// /crews/<TAG> anyone → that crew's public HQ, read-only+//+// WebGL contexts are the one hard budget here: browsers cap them (~16) and a+// 12-person crew asking for 12 canvases would evict the site's other viewers.+// LIVE_FIGURE_BUDGET caps how many members render as a live <agent-3d>; the rest+// render as their avatar still, which is the same figure, just not animated.++import { apiFetch } from './api.js';++const LIVE_FIGURE_BUDGET = 6;+const DEFAULT_RIG = '/avatars/default.glb';+const PRESENCE_POLL_MS = 20_000;+const SEARCH_DEBOUNCE_MS = 250;+const TAG_RE = /^[A-Z0-9]{2,6}$/;+// Kept in sync with RESERVED_TAGS in api/_lib/crews-store.js. Duplicated rather+// than fetched so the founding form can say "reserved" as you type instead of+// after a round trip; the server remains the authority and rejects it anyway.+const RESERVED_TAGS = new Set(['SEARCH', 'INDEX', 'API', 'ADMIN', 'NEW', 'ME', 'ALL', 'NULL']);++const $ = (id) => document.getElementById(id);++const esc = (s) =>+ String(s ?? '').replace(/[&<>"']/g, (c) =>+ ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );++// ── crest ────────────────────────────────────────────────────────────────────+// A crew's colour is derived from its tag, so it is stable everywhere the crew+// appears (room, directory, share card) without anyone picking or storing one.+function crestHues(tag) {+ let h = 2166136261;+ for (const ch of String(tag || '')) {+ h ^= ch.charCodeAt(0);+ h = Math.imul(h, 16777619) >>> 0;+ }+ const hue = h % 360;+ return { hue, hue2: (hue + 58) % 360 };+}++function applyCrewHues(el, tag) {+ const { hue, hue2 } = crestHues(tag);+ el.style.setProperty('--crew-hue', String(hue));+ el.style.setProperty('--crew-hue-2', String(hue2));+}++function crestHtml(tag, small = false) {+ const { hue, hue2 } = crestHues(tag);+ return (+ `<div class="cw-crest${small ? ' sm' : ''}" aria-hidden="true" ` ++ `style="--crew-hue:${hue};--crew-hue-2:${hue2}">${esc(tag)}</div>`+ );+}++// ── presence wording ─────────────────────────────────────────────────────────+// Matches src/game/friends-panel.js so the same person reads the same in both.+function realmLabel(realm, server) {+ if (!realm) return '';+ const r = String(realm)+ .replace(/[_-]+/g, ' ')+ .replace(/\b\w/g, (c) => c.toUpperCase());+ return server ? `${r} · Server ${server}` : r;+}++function presenceLine(m) {+ if (!m.online) return 'Offline';+ const where = realmLabel(m.realm, m.server);+ return where ? `In ${where}` : 'Online';+}++function joinedLabel(iso) {+ if (!iso) return '';+ const d = new Date(iso);+ if (Number.isNaN(d.getTime())) return '';+ return d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });+}++// ── errors ───────────────────────────────────────────────────────────────────+// Every mutation surfaces the server's own reason. The store throws typed codes+// and http.error() emits them as { error, error_description }; anything without+// one still gets a sentence rather than "undefined".+async function readError(res) {+ const body = await res.json().catch(() => null);+ return (+ body?.error_description ||+ body?.error ||+ (res.status === 429 ? 'Too many requests. Wait a moment and try again.' : `Request failed (${res.status}).`)+ );+}++// ── state ────────────────────────────────────────────────────────────────────+const state = {+ /** @type {'mine'|'public'} */ mode: 'mine',+ publicTag: '',+ me: null, // { crew, members, invites } for the signed-in account+ viewing: null, // { crew, members } currently rendered in the room+ authed: false,+ loaded: false,+ pollTimer: null,+ searchTimer: null,+ liveFigures: 0,+};++// ── toast ────────────────────────────────────────────────────────────────────+let toastTimer = null;+function toast(message, tone = 'good') {+ const el = $('cw-toast');+ if (!el) return;+ el.textContent = message;+ el.dataset.tone = tone;+ el.dataset.show = 'true';+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => {+ el.dataset.show = 'false';+ }, 4200);+}++// ── the room ─────────────────────────────────────────────────────────────────+function renderRoom(crew, members, { canManage }) {+ const room = $('cw-room');+ const stage = $('cw-stage');+ const head = $('cw-room-head');+ room.hidden = false;+ applyCrewHues(room, crew.tag);++ const online = members.filter((m) => m.online).length;+ const memberWord = members.length === 1 ? 'member' : 'members';+ head.innerHTML =+ crestHtml(crew.tag) ++ '<div class="cw-room-title">' ++ `<h2>${esc(crew.name)} <span class="cw-tag-badge">${esc(crew.tag)}</span></h2>` ++ `<p>${members.length} ${memberWord} · ${+ online ? `<span class="cw-live">${online} in world now</span>` : 'nobody in world right now'+ }</p>` ++ '</div>' ++ '<div class="cw-room-actions">' ++ `<button type="button" class="cw-btn sm" id="cw-share" title="Copy this crew's public link">Copy link</button>` ++ '<a class="cw-btn sm" href="/play" title="Open the 3D world where crews meet">Enter the world</a>' ++ (canManage ? '<button type="button" class="cw-btn sm danger" id="cw-leave">Leave crew</button>' : '') ++ '</div>';++ state.liveFigures = 0;+ stage.innerHTML = members.map(standeeHtml).join('');+ mountFigures(stage);++ $('cw-share').addEventListener('click', () => shareCrew(crew.tag));+ $('cw-leave')?.addEventListener('click', leaveCrew);+}++function standeeHtml(m) {+ const live = state.liveFigures < LIVE_FIGURE_BUDGET;+ if (live) state.liveFigures++;+ const model = m.standee?.modelUrl || DEFAULT_RIG;+ const label = m.standee?.agentName ? `${m.name} as ${m.standee.agentName}` : m.name;+ // Only link where there is somewhere real to go: the member's agent, else+ // their profile, else nothing. A standee with no destination stays a figure+ // rather than becoming an anchor to /u/ with no username behind it.+ const href = m.standee?.agentId+ ? `/a/${encodeURIComponent(m.standee.agentId)}`+ : m.username+ ? `/u/${encodeURIComponent(m.username)}`+ : '';+ const figure = live+ ? `<div class="cw-figure" data-model="${esc(model)}" data-label="${esc(label)}"></div>`+ : `<div class="cw-figure"><img class="cw-figure-img" src="${esc(+ m.standee?.thumbUrl || m.avatarUrl || '/favicon.svg',+ )}" alt="" loading="lazy" decoding="async" /></div>`;++ const tag = href ? 'a' : 'div';+ return (+ `<${tag} class="cw-standee" data-online="${m.online ? 'true' : 'false'}"` ++ (href ? ` href="${esc(href)}"` : '') ++ ` title="${esc(label)} · ${esc(presenceLine(m))}">` ++ figure ++ '<span class="cw-plinth"></span>' ++ '<span class="cw-nameplate">' ++ `<b>${esc(m.name)}</b>` ++ `<span class="${m.online ? 'cw-live' : ''}">${esc(presenceLine(m))}</span>` ++ '</span>' ++ `</${tag}>`+ );+}++// The live figures are mounted only when they scroll into the stage, so a crew+// wider than the viewport never pays for the members you cannot see.+function mountFigures(stage) {+ const pending = stage.querySelectorAll('.cw-figure[data-model]');+ if (!pending.length) return;+ if (!('IntersectionObserver' in window)) {+ pending.forEach(mountFigure);+ return;+ }+ const io = new IntersectionObserver(+ (entries) => {+ for (const e of entries) {+ if (!e.isIntersecting) continue;+ io.unobserve(e.target);+ mountFigure(e.target);+ }+ },+ { root: stage, rootMargin: '160px' },+ );+ pending.forEach((el) => io.observe(el));+}++function mountFigure(el) {+ const model = el.dataset.model;+ if (!model) return;+ delete el.dataset.model;+ const tag = document.createElement('agent-3d');+ tag.setAttribute('src', model);+ tag.setAttribute('animation', 'idle');+ tag.setAttribute('hide-chrome', '');+ tag.setAttribute('aria-label', el.dataset.label || 'Crew member');+ el.appendChild(tag);+}++// ── roster ───────────────────────────────────────────────────────────────────+function renderRoster(members, { canKick }) {+ const list = $('cw-roster');+ list.innerHTML = members+ .map((m) => {+ const joined = joinedLabel(m.joinedAt);+ const meta = [presenceLine(m), joined ? `joined ${joined}` : ''].filter(Boolean).join(' · ');+ return (+ '<li class="cw-row">' ++ `<img class="cw-avatar" src="${esc(m.avatarUrl || m.standee?.thumbUrl || '/favicon.svg')}" alt="" loading="lazy" decoding="async" />` ++ '<span class="cw-row-main">' ++ `<b>${esc(m.name)}</b><span>${esc(meta)}</span>` ++ '</span>' ++ (m.role === 'owner' ? '<span class="cw-tag-badge owner">Owner</span>' : '') ++ (canKick && m.role !== 'owner'+ ? `<button type="button" class="cw-btn sm danger" data-kick="${esc(m.id)}" data-name="${esc(m.name)}">Remove</button>`+ : '') ++ '</li>'+ );+ })+ .join('');++ list.querySelectorAll('[data-kick]').forEach((btn) => {+ btn.addEventListener('click', () => kickMember(btn.dataset.kick, btn.dataset.name));+ });+}++// ── invites addressed to me ──────────────────────────────────────────────────+function renderInvites(invites) {+ const panel = $('cw-invites-panel');+ const list = $('cw-invites');+ panel.hidden = !invites.length;+ if (!invites.length) return;+ list.innerHTML = invites+ .map(+ (i) =>+ '<div class="cw-invite">' ++ crestHtml(i.tag, true) ++ '<span class="cw-row-main">' ++ `<b>${esc(i.name)} <span class="cw-tag-badge">${esc(i.tag)}</span></b>` ++ `<span>Invited by ${esc(i.inviter?.name || 'a member')}</span>` ++ '</span>' ++ '<span class="cw-invite-actions">' ++ `<button type="button" class="cw-btn sm primary" data-accept="${esc(i.crewId)}">Accept</button>` ++ `<button type="button" class="cw-btn sm" data-decline="${esc(i.crewId)}">Decline</button>` ++ '</span>' ++ '</div>',+ )+ .join('');++ list.querySelectorAll('[data-accept]').forEach((b) =>+ b.addEventListener('click', () => respondToInvite('accept', b.dataset.accept, b)),+ );+ list.querySelectorAll('[data-decline]').forEach((b) =>+ b.addEventListener('click', () => respondToInvite('decline', b.dataset.decline, b)),+ );+}++// ── directory ────────────────────────────────────────────────────────────────+async function loadDirectory() {+ const wrap = $('cw-dir');+ try {+ const res = await apiFetch('/api/crews/directory?limit=24', { allowAnonymous: true });+ if (!res.ok) throw new Error(await readError(res));+ const { data } = await res.json();+ const crews = (data?.crews || []).filter((c) => c.tag !== state.me?.crew?.tag);+ if (!crews.length) {+ wrap.innerHTML =+ '<p class="cw-empty" style="grid-column:1/-1"><strong>No crews yet</strong>' ++ 'Found the first one. Its tag is yours for good.</p>';+ return;+ }+ wrap.innerHTML = crews+ .map(+ (c) =>+ `<a class="cw-dir-card" href="/crews/${encodeURIComponent(c.tag)}" title="Open ${esc(c.name)}">` ++ crestHtml(c.tag, true) ++ '<span class="cw-row-main">' ++ `<b>${esc(c.name)}</b>` ++ `<span>${c.memberCount} member${c.memberCount === 1 ? '' : 's'}</span>` ++ '<span class="cw-faces">' ++ c.faces+ .map((f) =>+ f.avatarUrl+ ? `<img src="${esc(f.avatarUrl)}" alt="" loading="lazy" decoding="async" />`+ : '<span class="cw-face-blank"></span>',+ )+ .join('') ++ '</span>' ++ '</span>' ++ '</a>',+ )+ .join('');+ } catch (err) {+ wrap.innerHTML =+ '<p class="cw-empty" style="grid-column:1/-1"><strong>The directory did not load</strong>' ++ esc(err.message || 'Try again in a moment.') ++ '</p>';+ }+}++// ── founding a crew ──────────────────────────────────────────────────────────+function wireFoundForm() {+ const form = $('cw-found');+ const tagInput = $('cw-found-tag');+ const nameInput = $('cw-found-name');+ const note = $('cw-found-tag-note');+ const submit = $('cw-found-submit');++ const validate = () => {+ const tag = tagInput.value.trim().toUpperCase().replace(/[^A-Z0-9]/g, '');+ if (tagInput.value !== tag) tagInput.value = tag;+ let msg = '';+ let tone = '';+ let ok = false;+ if (!tag) {+ msg = '2 to 6 letters or digits. This is the badge worn over your avatar in world.';+ } else if (!TAG_RE.test(tag)) {+ msg = tag.length < 2 ? 'A tag needs at least 2 characters.' : 'A tag is at most 6 characters.';+ tone = 'bad';+ } else if (RESERVED_TAGS.has(tag)) {+ msg = `${tag} is reserved by the site.`;+ tone = 'bad';+ } else {+ msg = `${tag} looks good.`;+ tone = 'good';+ ok = true;+ }+ note.textContent = msg;+ note.dataset.tone = tone;+ tagInput.setAttribute('aria-invalid', tone === 'bad' ? 'true' : 'false');+ submit.disabled = !ok || nameInput.value.trim().length < 2;+ return ok;+ };++ tagInput.addEventListener('input', validate);+ nameInput.addEventListener('input', validate);+ validate();++ form.addEventListener('submit', async (e) => {+ e.preventDefault();+ if (!validate()) return;+ submit.disabled = true;+ submit.textContent = 'Founding…';+ try {+ const res = await apiFetch('/api/crews', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ action: 'create',+ tag: tagInput.value.trim(),+ name: nameInput.value.trim(),+ }),+ });+ if (!res.ok) throw new Error(await readError(res));+ toast(`${tagInput.value.trim()} is yours. Invite your first member.`);+ await refresh();+ } catch (err) {+ toast(err.message || 'Could not found the crew.', 'bad');+ submit.disabled = false;+ } finally {+ submit.textContent = 'Found the crew';+ }+ });+}++// ── inviting ─────────────────────────────────────────────────────────────────+function wireInviteSearch() {+ const input = $('cw-invite-q');+ const results = $('cw-results');++ const run = async () => {+ const q = input.value.trim();+ if (q.length < 2) {+ results.innerHTML =+ '<li class="cw-empty">Type at least 2 characters of a name or username.</li>';+ return;+ }+ results.innerHTML = '<li class="cw-empty">Searching…</li>';+ try {+ const res = await apiFetch(`/api/crews/search?q=${encodeURIComponent(q)}`);+ if (!res.ok) throw new Error(await readError(res));+ const { data } = await res.json();+ const hits = data?.results || [];+ if (!hits.length) {+ results.innerHTML = `<li class="cw-empty">Nobody matches “${esc(q)}”.</li>`;+ return;+ }+ results.innerHTML = hits.map(inviteRowHtml).join('');+ results.querySelectorAll('[data-invite]').forEach((b) =>+ b.addEventListener('click', () => sendInvite(b.dataset.invite, b.dataset.name, b)),+ );+ } catch (err) {+ results.innerHTML = `<li class="cw-empty">${esc(err.message || 'Search failed.')}</li>`;+ }+ };++ input.addEventListener('input', () => {+ clearTimeout(state.searchTimer);+ state.searchTimer = setTimeout(run, SEARCH_DEBOUNCE_MS);+ });+}++// A hit renders its true state: already in a crew, already invited, or invitable.+// The reason is on the row, so nobody clicks a button that was always going to+// be refused.+function inviteRowHtml(u) {+ let action;+ if (u.crew) {+ action = `<span class="cw-tag-badge" title="Already flies ${esc(u.crew.name)}">${esc(u.crew.tag)}</span>`;+ } else if (u.invited) {+ action = '<span class="cw-tag-badge">Invited</span>';+ } else {+ action = `<button type="button" class="cw-btn sm primary" data-invite="${esc(u.id)}" data-name="${esc(u.name)}">Invite</button>`;+ }+ return (+ '<li class="cw-row">' ++ `<img class="cw-avatar" src="${esc(u.avatarUrl || '/favicon.svg')}" alt="" loading="lazy" decoding="async" />` ++ '<span class="cw-row-main">' ++ `<b>${esc(u.name)}</b><span>${u.username ? '@' + esc(u.username) : 'No username'}</span>` ++ '</span>' ++ action ++ '</li>'+ );+}++async function sendInvite(userId, name, btn) {+ btn.disabled = true;+ btn.textContent = 'Inviting…';+ try {+ const res = await apiFetch('/api/crews', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ action: 'invite', userId }),+ });+ if (!res.ok) throw new Error(await readError(res));+ btn.replaceWith(Object.assign(document.createElement('span'), {+ className: 'cw-tag-badge',+ textContent: 'Invited',+ }));+ toast(`Invite sent to ${name}.`);+ } catch (err) {+ btn.disabled = false;+ btn.textContent = 'Invite';+ toast(err.message || 'Could not send that invite.', 'bad');+ }+}++async function respondToInvite(action, crewId, btn) {+ const buttons = btn.closest('.cw-invite').querySelectorAll('button');+ buttons.forEach((b) => (b.disabled = true));+ try {+ const res = await apiFetch('/api/crews', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ action, crewId }),+ });+ if (!res.ok) throw new Error(await readError(res));+ toast(action === 'accept' ? 'You are in. Welcome to the crew.' : 'Invite declined.');+ await refresh();+ } catch (err) {+ buttons.forEach((b) => (b.disabled = false));+ toast(err.message || 'That did not go through.', 'bad');+ }+}++// ── destructive actions ──────────────────────────────────────────────────────+async function leaveCrew() {+ const crew = state.me?.crew;+ if (!crew) return;+ const lastOne = (state.me.members || []).length <= 1;+ const warning = lastOne+ ? `You are the only member of ${crew.name}. Leaving disbands the crew and frees the tag ${crew.tag}. Continue?`+ : crew.isOwner+ ? `Leave ${crew.name}? Ownership passes to the longest-standing member.`+ : `Leave ${crew.name}?`;+ if (!confirm(warning)) return;+ try {+ const res = await apiFetch('/api/crews', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ action: 'leave' }),+ });+ if (!res.ok) throw new Error(await readError(res));+ const { data } = await res.json();+ toast(data?.disbanded ? `${crew.name} has been disbanded.` : `You left ${crew.name}.`);+ await refresh();+ } catch (err) {+ toast(err.message || 'Could not leave the crew.', 'bad');+ }+}++async function kickMember(userId, name) {+ if (!confirm(`Remove ${name} from the crew?`)) return;+ try {+ const res = await apiFetch('/api/crews', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ action: 'kick', userId }),+ });+ if (!res.ok) throw new Error(await readError(res));+ toast(`${name} was removed.`);+ await refresh();+ } catch (err) {+ toast(err.message || 'Could not remove that member.', 'bad');+ }+}++async function shareCrew(tag) {+ const url = `${location.origin}/crews/${encodeURIComponent(tag)}`;+ try {+ await navigator.clipboard.writeText(url);+ toast('Public crew link copied.');+ } catch {+ // Clipboard is blocked in some embedded contexts; show the URL so the+ // action still succeeds by hand rather than failing silently.+ toast(url, 'good');+ }+}++// ── loading ──────────────────────────────────────────────────────────────────+function showSkeleton() {+ $('cw-room').hidden = false;+ $('cw-stage').innerHTML =+ '<div class="cw-skeleton">' ++ Array.from({ length: 4 }, () => '<div class="cw-shimmer"></div>').join('') ++ '</div>';+ $('cw-room-head').innerHTML = '<div class="cw-room-title"><h2>Loading the HQ…</h2></div>';+}++function showError(message, retry) {+ const box = $('cw-error');+ box.hidden = false;+ box.innerHTML = `<p>${esc(message)}</p><button type="button" class="cw-btn" id="cw-retry">Try again</button>`;+ $('cw-retry').addEventListener('click', () => {+ box.hidden = true;+ retry();+ });+}++async function loadPublicCrew(tag) {+ showSkeleton();+ try {+ const res = await apiFetch(`/api/crews/${encodeURIComponent(tag)}`, { allowAnonymous: true });+ if (res.status === 404) {+ $('cw-room').hidden = true;+ $('cw-manage').hidden = true;+ showError(`No crew flies the tag ${tag}. It is still available.`, () => loadPublicCrew(tag));+ $('cw-found-panel').hidden = false;+ $('cw-found-tag').value = tag;+ $('cw-found-tag').dispatchEvent(new Event('input'));+ return;+ }+ if (!res.ok) throw new Error(await readError(res));+ const { data } = await res.json();+ const crew = data.crew;+ state.viewing = { crew, members: crew.members };+ document.title = `${crew.name} (${crew.tag}) · Crew HQ · three.ws`;+ renderRoom(crew, crew.members, { canManage: false });+ renderRoster(crew.members, { canKick: false });+ $('cw-roster-panel').hidden = false;+ $('cw-public-note').hidden = false;+ $('cw-public-note').innerHTML =+ `Viewing <b>${esc(crew.name)}</b> as a visitor. <a href="/crews">Your own Crew HQ</a> is one click away.`;+ } catch (err) {+ $('cw-room').hidden = true;+ showError(err.message || 'That crew could not be loaded.', () => loadPublicCrew(tag));+ }+}++async function loadMine() {+ try {+ const res = await apiFetch('/api/crews', { allowAnonymous: true });+ if (res.status === 401) {+ state.authed = false;+ state.me = null;+ return;+ }+ if (!res.ok) throw new Error(await readError(res));+ const { data } = await res.json();+ state.authed = true;+ state.me = data;+ } catch (err) {+ state.authed = false;+ state.me = null;+ throw err;+ }+}++// Re-read everything and re-render. Used after every mutation and by the+// presence poll, so the room is never a stale snapshot of who is in world.+async function refresh() {+ if (state.mode === 'public') return loadPublicCrew(state.publicTag);+ try {+ await loadMine();+ } catch (err) {+ showError(err.message || 'Your crew could not be loaded.', refresh);+ return;+ }+ renderMine();+}++function renderMine() {+ const signedOut = !state.authed;+ const crew = state.me?.crew || null;+ const members = state.me?.members || [];++ $('cw-signedout').hidden = !signedOut;+ $('cw-found-panel').hidden = signedOut || !!crew;+ $('cw-manage').hidden = !crew;+ $('cw-roster-panel').hidden = !crew;+ $('cw-room').hidden = !crew;+ $('cw-dir-panel').hidden = false;++ renderInvites(signedOut ? [] : state.me?.invites || []);++ if (crew) {+ renderRoom(crew, members, { canManage: true });+ renderRoster(members, { canKick: crew.isOwner });+ document.title = `${crew.name} (${crew.tag}) · Crew HQ · three.ws`;+ $('cw-manage-hint').textContent = crew.isOwner+ ? 'You own this crew. Invite anyone with an account; they join the moment they accept.'+ : 'Invite anyone with an account to fly your tag. Only the owner can remove members.';+ }+ state.loaded = true;+}++// ── presence polling ─────────────────────────────────────────────────────────+// Only while the tab is visible: an idle background tab does not need to know+// who walked into a realm, and a poll it cannot show is wasted DB and Redis.+function startPolling() {+ const tick = async () => {+ if (document.visibilityState !== 'visible') return;+ if (!state.loaded) return;+ try {+ if (state.mode === 'public') await loadPublicCrew(state.publicTag);+ else if (state.me?.crew) {+ await loadMine();+ renderMine();+ }+ } catch {+ // A failed poll is not an error state — the last good render stands and+ // the next tick tries again.+ }+ };+ state.pollTimer = setInterval(tick, PRESENCE_POLL_MS);+ document.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'visible') tick();+ });+}++// ── boot ─────────────────────────────────────────────────────────────────────+function tagFromPath() {+ const m = location.pathname.match(/^\/crews\/([A-Za-z0-9]{2,6})\/?$/);+ return m ? m[1].toUpperCase() : '';+}++async function boot() {+ wireFoundForm();+ wireInviteSearch();++ const tag = tagFromPath();+ if (tag) {+ state.mode = 'public';+ state.publicTag = tag;+ $('cw-found-panel').hidden = true;+ $('cw-dir-panel').hidden = false;+ await Promise.all([loadPublicCrew(tag), loadDirectory()]);+ // A visitor who is signed in still gets their invites, so a link shared in+ // chat and an invite sitting in the app converge on the same page.+ try {+ await loadMine();+ renderInvites(state.me?.invites || []);+ } catch {+ /* an anonymous visitor simply has no invites */+ }+ state.loaded = true;+ } else {+ showSkeleton();+ await refresh();+ await loadDirectory();+ }+ startPolling();+}++boot();diff --git a/src/crews.css b/src/crews.cssnew file mode 100644index 000000000..5f0f91447--- /dev/null+++ b/src/crews.css@@ -0,0 +1,536 @@+/* Crew HQ (/crews) — the room, the roster, the directory.+ *+ * Everything here rides the site tokens in public/style.css. The only local+ * variables are the two the crest generator drives per crew (--crew-hue and+ * --crew-hue-2), so a crew's colour is data, not a hand-picked palette.+ */++.cw-wrap {+ max-width: 1180px;+ margin: 0 auto;+ padding: 0 18px 96px;+}++/* ── hero ────────────────────────────────────────────────────────────────── */+.cw-hero {+ padding: 34px 0 6px;+}+.cw-hero h1 {+ font-size: clamp(1.7rem, 4vw, 2.5rem);+ line-height: 1.15;+ letter-spacing: -0.02em;+ margin: 0 0 10px;+ color: var(--ink-bright, var(--ink));+}+.cw-hero p {+ margin: 0;+ max-width: 66ch;+ color: var(--ink-dim);+ line-height: 1.6;+}+.cw-hero a {+ color: inherit;+ text-decoration: underline;+ text-underline-offset: 3px;+}+.cw-hero a:hover {+ color: var(--ink-bright, var(--ink));+}++/* ── the room ────────────────────────────────────────────────────────────── */+/* A crew's headquarters: every member standing as their own agent. The floor+ glow and the horizon line are drawn with gradients rather than an image so+ the room weighs nothing and recolours itself from the crew crest. */+.cw-room {+ position: relative;+ margin: 26px 0 0;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg, 16px);+ background:+ radial-gradient(120% 90% at 50% 108%, hsl(var(--crew-hue, 210) 70% 22% / 0.55), transparent 62%),+ linear-gradient(180deg, var(--surface-1, rgba(255, 255, 255, 0.03)), rgba(0, 0, 0, 0.22));+ overflow: hidden;+}+.cw-room::after {+ /* horizon: a single hairline that reads as a floor without a texture */+ content: '';+ position: absolute;+ left: 0;+ right: 0;+ bottom: 92px;+ height: 1px;+ background: linear-gradient(90deg, transparent, hsl(var(--crew-hue, 210) 80% 62% / 0.35), transparent);+ pointer-events: none;+}+.cw-room-head {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 14px;+ padding: 18px 20px 6px;+ position: relative;+ z-index: 2;+}+.cw-room-title {+ min-width: 0;+}+.cw-room-title h2 {+ margin: 0;+ font-size: 1.25rem;+ letter-spacing: -0.01em;+ color: var(--ink-bright, var(--ink));+ overflow-wrap: anywhere;+}+.cw-room-title p {+ margin: 3px 0 0;+ font-size: 0.85rem;+ color: var(--ink-dim);+}+.cw-room-actions {+ margin-left: auto;+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+}++/* The stage scrolls horizontally rather than shrinking figures below the size+ where a face is legible. */+.cw-stage {+ position: relative;+ z-index: 1;+ display: flex;+ gap: 10px;+ align-items: flex-end;+ padding: 8px 20px 26px;+ overflow-x: auto;+ overflow-y: hidden;+ scroll-snap-type: x proximity;+ scrollbar-width: thin;+}+.cw-standee {+ flex: 0 0 auto;+ width: 172px;+ scroll-snap-align: center;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 8px;+ padding-bottom: 4px;+ text-decoration: none;+ color: inherit;+ border-radius: var(--radius-md, 12px);+ transition: transform 0.18s ease;+}+.cw-standee:hover,+.cw-standee:focus-visible {+ transform: translateY(-3px);+}+.cw-standee:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 3px;+}+.cw-figure {+ position: relative;+ width: 100%;+ height: 230px;+ display: grid;+ place-items: end center;+}+.cw-figure agent-3d,+.cw-figure .cw-figure-img {+ width: 100%;+ height: 100%;+ object-fit: contain;+ display: block;+}+/* Offline members are present but unlit: the room still shows the whole crew. */+.cw-standee[data-online='false'] .cw-figure {+ filter: grayscale(0.85) brightness(0.62);+ opacity: 0.75;+}+.cw-plinth {+ position: absolute;+ left: 50%;+ bottom: -6px;+ translate: -50% 0;+ width: 116px;+ height: 26px;+ border-radius: 50%;+ background: radial-gradient(closest-side, hsl(var(--crew-hue, 210) 85% 62% / 0.42), transparent);+ pointer-events: none;+}+.cw-standee[data-online='true'] .cw-plinth {+ animation: cw-pulse 3.2s ease-in-out infinite;+}+@keyframes cw-pulse {+ 0%, 100% { opacity: 0.55; }+ 50% { opacity: 1; }+}+.cw-nameplate {+ text-align: center;+ max-width: 100%;+}+.cw-nameplate b {+ display: block;+ font-size: 0.92rem;+ font-weight: 600;+ color: var(--ink-bright, var(--ink));+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.cw-nameplate span {+ display: block;+ font-size: 0.75rem;+ color: var(--ink-dim);+ margin-top: 2px;+}+.cw-live {+ color: var(--success);+}+.cw-live::before {+ content: '';+ display: inline-block;+ width: 6px;+ height: 6px;+ margin-right: 5px;+ border-radius: 50%;+ background: currentColor;+ vertical-align: middle;+ box-shadow: 0 0 0 0 currentColor;+ animation: cw-dot 2.4s ease-out infinite;+}+@keyframes cw-dot {+ 0% { box-shadow: 0 0 0 0 hsl(140 70% 60% / 0.55); }+ 70% { box-shadow: 0 0 0 7px hsl(140 70% 60% / 0); }+ 100% { box-shadow: 0 0 0 0 hsl(140 70% 60% / 0); }+}+@media (prefers-reduced-motion: reduce) {+ .cw-standee[data-online='true'] .cw-plinth,+ .cw-live::before { animation: none; }+ .cw-standee:hover, .cw-standee:focus-visible { transform: none; }+}++/* ── crest ───────────────────────────────────────────────────────────────── */+/* Every crew gets a deterministic crest from its tag, so a crew is recognisable+ before you read its name and no crew has to upload art to look like itself. */+.cw-crest {+ flex: 0 0 auto;+ width: 56px;+ height: 56px;+ border-radius: 14px;+ display: grid;+ place-items: center;+ font: 700 0.95rem/1 var(--font-mono, ui-monospace, monospace);+ letter-spacing: 0.04em;+ color: #fff;+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.45);+ background:+ linear-gradient(150deg, hsl(var(--crew-hue, 210) 78% 52%), hsl(var(--crew-hue-2, 260) 74% 42%));+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25), var(--shadow-1);+}+.cw-crest.sm {+ width: 38px;+ height: 38px;+ border-radius: 10px;+ font-size: 0.72rem;+}++/* ── panels ──────────────────────────────────────────────────────────────── */+.cw-cols {+ display: grid;+ grid-template-columns: minmax(0, 1.35fr) minmax(0, 1fr);+ gap: 16px;+ margin-top: 22px;+ align-items: start;+}+@media (max-width: 860px) {+ .cw-cols { grid-template-columns: 1fr; }+}+.cw-panel {+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg, 14px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ padding: 18px;+}+.cw-panel > h3 {+ margin: 0 0 4px;+ font-size: 1rem;+ color: var(--ink-bright, var(--ink));+}+.cw-panel > .cw-hint {+ margin: 0 0 14px;+ font-size: 0.84rem;+ color: var(--ink-dim);+ line-height: 1.55;+}++/* ── roster ──────────────────────────────────────────────────────────────── */+.cw-roster {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 6px;+}+.cw-row {+ display: flex;+ align-items: center;+ gap: 11px;+ padding: 9px 10px;+ border: 1px solid transparent;+ border-radius: var(--radius-md, 10px);+ transition: background 0.15s ease, border-color 0.15s ease;+}+.cw-row:hover {+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ border-color: var(--stroke);+}+.cw-avatar {+ flex: 0 0 auto;+ width: 34px;+ height: 34px;+ border-radius: 50%;+ object-fit: cover;+ background: var(--surface-3, rgba(255, 255, 255, 0.08));+ border: 1px solid var(--stroke);+}+.cw-row-main {+ min-width: 0;+ flex: 1 1 auto;+}+.cw-row-main b {+ display: block;+ font-size: 0.9rem;+ font-weight: 600;+ color: var(--ink);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.cw-row-main span {+ display: block;+ font-size: 0.76rem;+ color: var(--ink-dim);+ margin-top: 1px;+}+.cw-tag-badge {+ font: 600 0.68rem/1 var(--font-mono, ui-monospace, monospace);+ padding: 4px 7px;+ border-radius: var(--radius-pill, 999px);+ border: 1px solid var(--badge-border, var(--stroke-strong));+ background: var(--badge-bg, var(--surface-3));+ color: var(--badge-fg, var(--ink));+ text-transform: uppercase;+ letter-spacing: 0.05em;+ white-space: nowrap;+}+.cw-tag-badge.owner {+ background: var(--badge-warn-bg);+ color: var(--badge-warn-fg);+ border-color: var(--badge-warn-border);+}++/* ── controls ────────────────────────────────────────────────────────────── */+.cw-field {+ display: flex;+ flex-direction: column;+ gap: 5px;+ margin-bottom: 12px;+}+.cw-field label {+ font-size: 0.78rem;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: var(--ink-dim);+}+.cw-field input {+ font: inherit;+ font-size: 0.95rem;+ padding: 10px 12px;+ color: var(--ink);+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md, 10px);+ transition: border-color 0.15s ease, background 0.15s ease;+}+.cw-field input::placeholder { color: var(--ink-dim); }+.cw-field input:hover { border-color: var(--stroke-strong); }+.cw-field input:focus-visible {+ outline: none;+ border-color: var(--accent);+ background: var(--surface-3, rgba(255, 255, 255, 0.07));+}+.cw-field input[aria-invalid='true'] { border-color: var(--danger); }+.cw-field .cw-note {+ font-size: 0.76rem;+ color: var(--ink-dim);+ min-height: 1em;+}+.cw-field .cw-note[data-tone='bad'] { color: var(--danger); }+.cw-field .cw-note[data-tone='good'] { color: var(--success); }+#cw-found-tag { text-transform: uppercase; letter-spacing: 0.12em; font-family: var(--font-mono, ui-monospace, monospace); }++.cw-btn {+ font: inherit;+ font-size: var(--btn-text-size, 0.88rem);+ font-weight: 550;+ padding: 9px 14px;+ cursor: pointer;+ border-radius: var(--btn-radius, 10px);+ border: 1px solid var(--btn-secondary-border, var(--stroke-strong));+ background: var(--btn-secondary-bg, var(--surface-3));+ color: var(--btn-secondary-fg, var(--ink));+ transition: background 0.15s ease, border-color 0.15s ease, transform 0.1s ease, opacity 0.15s ease;+ white-space: nowrap;+}+.cw-btn:hover:not(:disabled) { background: var(--btn-secondary-bg-hover, rgba(255, 255, 255, 0.12)); }+.cw-btn:active:not(:disabled) { transform: translateY(1px); }+.cw-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.cw-btn:disabled { opacity: 0.45; cursor: not-allowed; }+.cw-btn.primary {+ background: var(--btn-primary-bg, var(--accent));+ color: var(--btn-primary-fg, #0a0a0a);+ border-color: var(--btn-primary-border, transparent);+}+.cw-btn.primary:hover:not(:disabled) { background: var(--btn-primary-bg-hover, rgba(255, 255, 255, 0.88)); }+.cw-btn.danger {+ background: var(--btn-danger-bg);+ color: var(--btn-danger-fg);+ border-color: var(--btn-danger-border);+}+.cw-btn.danger:hover:not(:disabled) { background: var(--btn-danger-bg-hover); }+.cw-btn.sm { padding: 6px 10px; font-size: 0.8rem; }++/* ── search results ──────────────────────────────────────────────────────── */+.cw-results {+ list-style: none;+ margin: 10px 0 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 4px;+ max-height: 320px;+ overflow-y: auto;+}++/* ── invites ─────────────────────────────────────────────────────────────── */+.cw-invite {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 12px;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md, 12px);+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ margin-bottom: 8px;+}+.cw-invite .cw-row-main { flex: 1 1 auto; }+.cw-invite-actions { display: flex; gap: 6px; }++/* ── directory ───────────────────────────────────────────────────────────── */+.cw-dir {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));+ gap: 10px;+ margin-top: 12px;+}+.cw-dir-card {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 13px 14px;+ text-decoration: none;+ color: inherit;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg, 14px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ transition: border-color 0.15s ease, background 0.15s ease, transform 0.12s ease;+}+.cw-dir-card:hover {+ border-color: var(--stroke-strong);+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ transform: translateY(-2px);+}+.cw-dir-card:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.cw-faces { display: flex; margin-top: 5px; }+.cw-faces img,+.cw-faces .cw-face-blank {+ width: 20px;+ height: 20px;+ border-radius: 50%;+ object-fit: cover;+ border: 1px solid var(--bg-0);+ background: var(--surface-3, rgba(255, 255, 255, 0.09));+ margin-right: -6px;+}++/* ── states ──────────────────────────────────────────────────────────────── */+.cw-empty {+ text-align: center;+ padding: 30px 18px;+ color: var(--ink-dim);+ font-size: 0.9rem;+ line-height: 1.6;+}+.cw-empty strong { display: block; color: var(--ink); margin-bottom: 5px; font-size: 1rem; }+.cw-error {+ border: 1px solid var(--badge-danger-border, var(--stroke));+ background: var(--badge-danger-bg, var(--surface-2));+ color: var(--ink);+ border-radius: var(--radius-md, 12px);+ padding: 14px 16px;+ margin: 18px 0;+ display: flex;+ align-items: center;+ gap: 12px;+ flex-wrap: wrap;+}+.cw-error p { margin: 0; flex: 1 1 220px; font-size: 0.88rem; }++.cw-skeleton { display: flex; gap: 10px; padding: 8px 20px 26px; }+.cw-shimmer {+ background: linear-gradient(90deg, var(--skeleton-base) 25%, var(--skeleton-sheen) 37%, var(--skeleton-base) 63%);+ background-size: 400% 100%;+ animation: cw-shimmer 1.4s ease infinite;+ border-radius: var(--skeleton-radius, 10px);+}+.cw-skeleton .cw-shimmer { width: 172px; height: 268px; flex: 0 0 auto; }+@keyframes cw-shimmer { 0% { background-position: 100% 50%; } 100% { background-position: 0 50%; } }+@media (prefers-reduced-motion: reduce) { .cw-shimmer { animation: none; } }++/* A live region that announces the result of every mutation for screen readers+ and doubles as the visible confirmation nobody should have to guess at. */+.cw-toast {+ position: fixed;+ left: 50%;+ bottom: 22px;+ translate: -50% 0;+ z-index: 90;+ max-width: min(92vw, 460px);+ padding: 11px 16px;+ border-radius: var(--radius-pill, 999px);+ border: 1px solid var(--stroke-strong);+ background: var(--modal-bg, rgba(10, 11, 18, 0.96));+ color: var(--ink);+ font-size: 0.88rem;+ box-shadow: var(--shadow-3);+ opacity: 0;+ transform: translateY(8px);+ pointer-events: none;+ transition: opacity 0.2s ease, transform 0.2s ease;+}+.cw-toast[data-show='true'] { opacity: 1; transform: translateY(0); }+.cw-toast[data-tone='bad'] { border-color: var(--badge-danger-border); color: var(--danger); }+.cw-toast[data-tone='good'] { border-color: var(--badge-success-border); }++.cw-sr {+ position: absolute;+ width: 1px;+ height: 1px;+ overflow: hidden;+ clip: rect(0 0 0 0);+ clip-path: inset(50%);+ white-space: nowrap;+}