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(desktop): add the lazy-loaded Grid world with a Grid button in the campus and a world=grid deep link
nirholasf35d07d93f84
diff --git a/src/desktop/grid/grid.css b/src/desktop/grid/grid.cssnew file mode 100644index 000000000..c597d8181--- /dev/null+++ b/src/desktop/grid/grid.css@@ -0,0 +1,64 @@+/* The Grid: neon HUD over a black wireframe room. Monochrome on purpose. */+.gd {+ --gd-ink: #19ffb0;+ --gd-dim: #0d7a55;+ --gd-bg: #020a07;+ position: fixed;+ inset: 0;+ z-index: 9000;+ background: #000504;+ color: var(--gd-ink);+ font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ touch-action: none;+}+.gd[hidden] { display: none; }+.gd-canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; outline: none; }+.gd-hud { position: absolute; inset: 0; pointer-events: none; }+.gd-hud > * { pointer-events: auto; }++.gd-top { position: absolute; top: 0; left: 0; right: 0; display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: max(12px, env(safe-area-inset-top)) 16px 0; pointer-events: none; }+.gd-top > * { pointer-events: auto; }+.gd-brand { display: flex; align-items: baseline; gap: 10px; text-shadow: 0 0 12px rgba(25, 255, 176, 0.5); }+.gd-brand b { font-size: 18px; letter-spacing: 0.02em; }+.gd-brand span { color: var(--gd-dim); font-size: 13px; text-transform: uppercase; letter-spacing: 0.14em; }+.gd-tools { display: flex; gap: 8px; flex-wrap: wrap; justify-content: flex-end; }++.gd-tool {+ display: inline-flex; align-items: center; gap: 8px; min-height: 40px; padding: 0 14px;+ background: rgba(2, 10, 7, 0.82); color: var(--gd-ink); font: inherit; font-size: 13px;+ border: 1px solid var(--gd-dim); border-radius: 0; cursor: pointer;+ transition: background 120ms, border-color 120ms, color 120ms, transform 120ms;+}+.gd-tool:hover { background: #0a3d2c; border-color: var(--gd-ink); }+.gd-tool:active { transform: translateY(1px); background: var(--gd-ink); color: var(--gd-bg); }+.gd-tool:focus-visible, .gd-prompt:focus-visible { outline: 2px solid var(--gd-ink); outline-offset: 2px; }++.gd-prompt {+ position: absolute; left: 50%; bottom: 150px; transform: translateX(-50%);+ display: flex; align-items: center; gap: 14px; max-width: min(520px, calc(100vw - 32px));+ padding: 12px 16px; background: rgba(2, 10, 7, 0.9); border: 1px solid var(--gd-ink);+ box-shadow: 0 0 24px rgba(25, 255, 176, 0.25);+}+.gd-prompt[hidden] { display: none; }+.gd-key { min-width: 34px; padding: 6px 10px; text-align: center; font: inherit; font-weight: 700; background: var(--gd-ink); color: var(--gd-bg); }+.gd-prompt b { display: block; font-size: 15px; }+.gd-prompt span { display: block; color: var(--gd-dim); font-size: 12px; margin-top: 2px; }++.gd-tier { position: absolute; left: 50%; bottom: 56px; transform: translateX(-50%); width: min(380px, calc(100vw - 32px)); text-align: center; text-shadow: 0 0 10px rgba(25, 255, 176, 0.45); }+.gd-tier-name { display: block; font-size: 15px; letter-spacing: 0.1em; }+.gd-bar { height: 8px; margin: 8px 0 6px; border: 1px solid var(--gd-dim); background: rgba(2, 10, 7, 0.8); }+.gd-bar i { display: block; height: 100%; width: 0; background: var(--gd-ink); box-shadow: 0 0 10px var(--gd-ink); transition: width 400ms ease-out; }+.gd-tier-note { display: block; color: var(--gd-dim); font-size: 11px; }++.gd-help { position: absolute; left: 0; right: 0; bottom: 14px; text-align: center; color: var(--gd-dim); font-size: 11px; letter-spacing: 0.06em; pointer-events: none; }++@media (max-width: 640px) {+ .gd-tool span { display: none; }+ .gd-tool { padding: 0 12px; }+ .gd-prompt { bottom: 128px; }+ .gd-tier { bottom: 40px; }+}+@media (prefers-reduced-motion: reduce) {+ .gd-tool, .gd-bar i { transition: none; }+}+.in-grid body { overflow: hidden; }diff --git a/src/desktop/grid/index.js b/src/desktop/grid/index.jsnew file mode 100644index 000000000..ba3f455d6--- /dev/null+++ b/src/desktop/grid/index.js@@ -0,0 +1,324 @@+// The Grid: a neon wireframe room where the platform's apps are things you+// walk up to. A live board, a directory, a wallet-moves wall and one kiosk per+// app, all fed by the same real endpoints the desktop and the Field use. Your+// byte tier comes from the gems you mined in the campus. E opens the app on+// the desktop; the campus and the desktop are one button away.++import {+ AmbientLight, BoxGeometry, Color, DirectionalLight, EdgesGeometry, GridHelper, LineBasicMaterial, LineSegments,+ Mesh, MeshBasicMaterial, PerspectiveCamera, PlaneGeometry, Raycaster, Scene, Vector2,+} from 'three';+import { createPlayer } from '../../docs-world/player.js';+import { createControls } from '../../docs-world/controls.js';+import { createCameraModeController, CAMERA_MODE_LABELS } from '../../game/camera-modes.js';+import { createFrameGovernor, FPS_ACTIVE, FPS_IDLE, getPowerSaver, onPowerSaverChange, trackWindowFocus } from '../../shared/frame-governor.js';+import { createRenderer } from '../../webgl-support.js';+import { loadLaunches, loadPulse, loadStats, loadToken } from '../../field/data.js';+import { icon } from '../icons.js';+import { createMiner } from '../world/mine.js';+import { ROOM, ROOM_BOUND, SPAWN, WALLS, kioskLayout, nearestSurface, tierFor } from './logic.js';+import { INK, DIM, createSurface, paintBoard, paintDirectory, paintKiosk, paintPulse } from './panels.js';+import './grid.css';++const REFRESH_MS = 30_000;+const PULSE_LIMIT = 24;++const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);++async function loadNewAgents() {+ const r = await fetch('/api/agents/public?sort=newest&limit=8', { credentials: 'omit', headers: { accept: 'application/json' } });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const d = await r.json();+ return Array.isArray(d.agents) ? d.agents : [];+}++/**+ * @param {{+ * apps: Array<{id:string,title:string,desc?:string,hue:number}>,+ * directory: Array<{id:string,title:string,desc?:string}>,+ * reducedMotion?: boolean,+ * onLeave: (o: { app?: string|null, to?: 'desktop'|'campus' }) => void,+ * }} o+ */+export function createGrid({ apps, directory, reducedMotion = false, onLeave }) {+ const el = document.createElement('div');+ el.className = 'gd';+ el.hidden = true;+ el.innerHTML = `+ <canvas class="gd-canvas" aria-label="The Grid, a 3D room of live three.ws apps"></canvas>+ <div class="gd-hud">+ <div class="gd-top">+ <div class="gd-brand"><b>three.ws</b><span>The Grid</span></div>+ <div class="gd-tools">+ <button type="button" class="gd-tool gd-cam" title="Camera (C)">${icon('camera', 18)}<span class="gd-cam-label"></span></button>+ <button type="button" class="gd-tool gd-campus" title="Walk the campus">${icon('compass', 18)}<span>Campus</span></button>+ <button type="button" class="gd-tool gd-desk" title="Go to the desktop">${icon('desktop', 18)}<span>Desktop</span></button>+ </div>+ </div>+ <div class="gd-prompt" hidden role="status"><kbd class="gd-key">E</kbd><div><b></b><span></span></div></div>+ <div class="gd-tier" role="img" aria-label="Byte tier"><b class="gd-tier-name">TIER 1 - BYTE</b><div class="gd-bar"><i></i></div><small class="gd-tier-note"></small></div>+ <div class="gd-help">WASD move Shift run Drag to look E open C camera</div>+ </div>`;+ document.body.append(el);+ const $ = (s) => el.querySelector(s);+ const canvas = $('.gd-canvas');+ const prompt = $('.gd-prompt');+ const isTouch = matchMedia('(pointer: coarse)').matches;+ if (isTouch) $('.gd-help').hidden = true;++ // ---- renderer and scene ----+ const renderer = createRenderer({ canvas, antialias: true, alpha: false, powerPreference: 'high-performance' }, { fallback: canvas.parentElement });+ renderer.setPixelRatio(Math.min(devicePixelRatio || 1, 2));+ renderer.setSize(innerWidth, innerHeight, false);+ const scene = new Scene();+ scene.background = new Color(0x000504);+ const camera = new PerspectiveCamera(58, innerWidth / innerHeight, 0.1, 120);+ scene.add(new AmbientLight(0x7dffd0, 1.15));+ const key = new DirectionalLight(0xbfffe8, 1.6);+ key.position.set(6, 12, 8);+ scene.add(key);++ const lineMat = new LineBasicMaterial({ color: new Color(INK), transparent: true, opacity: 0.85 });+ const dimMat = new LineBasicMaterial({ color: new Color(DIM), transparent: true, opacity: 0.55 });+ const room = new LineSegments(new EdgesGeometry(new BoxGeometry(ROOM.half * 2, ROOM.height, ROOM.half * 2)), lineMat);+ room.position.y = ROOM.height / 2;+ scene.add(room);+ // Depth cues the void lacks: a metre grid on the floor and rings on the ceiling.+ const floor = new GridHelper(ROOM.half * 2, ROOM.half, new Color(INK), new Color(DIM));+ floor.material.transparent = true;+ floor.material.opacity = 0.32;+ scene.add(floor);+ const ceiling = new GridHelper(ROOM.half * 2, 6, new Color(DIM), new Color(DIM));+ ceiling.material.transparent = true;+ ceiling.material.opacity = 0.18;+ ceiling.position.y = ROOM.height;+ scene.add(ceiling);++ // ---- live state ----+ const S = {+ stats: { status: 'loading' },+ agents: { status: 'loading' },+ launches: { status: 'loading' },+ pulse: { status: 'loading' },+ token: { status: 'loading' },+ };+ const kioskDefs = kioskLayout(apps);+ const surfaces = [...WALLS, ...kioskDefs].map((def) => {+ const px = def.kind === 'board' ? [2048, 819] : def.kind === 'kiosk' ? [640, Math.round(640 * (def.h / def.w))] : [1024, 640];+ const surf = createSurface(px[0], px[1], renderer.capabilities.getMaxAnisotropy());+ const mesh = new Mesh(new PlaneGeometry(def.w, def.h), new MeshBasicMaterial({ map: surf.texture, toneMapped: false }));+ mesh.position.set(def.x, def.y, def.z);+ mesh.rotation.y = def.yaw;+ mesh.userData.surfaceId = def.id;+ scene.add(mesh);+ const edge = new LineSegments(new EdgesGeometry(mesh.geometry), lineMat);+ edge.position.copy(mesh.position);+ edge.rotation.copy(mesh.rotation);+ edge.translateZ(0.02);+ scene.add(edge);+ if (def.kind === 'kiosk') {+ // A plinth line drops to the floor so the slab reads as standing.+ const stand = new LineSegments(new EdgesGeometry(new BoxGeometry(def.w * 0.9, 0.12, 0.5)), dimMat);+ stand.position.set(def.x, 0.06, def.z + 0.2);+ scene.add(stand);+ }+ return { def, surf, mesh, edge, hot: false };+ });+ const byId = new Map(surfaces.map((s) => [s.def.id, s]));+ const pickables = surfaces.map((s) => s.mesh);+ // Kiosks are solid: the player walks up to one, not through it.+ const solids = kioskDefs.map((k) => ({ obb: { x: k.x, z: k.z, yaw: k.yaw, hw: k.w / 2 + 0.1, hd: 0.45 } }));++ function paint(s) {+ switch (s.def.kind) {+ case 'board': return paintBoard(s.surf, S, s.hot);+ case 'directory': return paintDirectory(s.surf, directory, s.hot);+ case 'pulse': return paintPulse(s.surf, S, s.hot);+ default: return paintKiosk(s.surf, s.def, s.hot);+ }+ }+ function repaint(kinds) {+ for (const s of surfaces) if (!kinds || kinds.includes(s.def.kind)) { paint(s); s.surf.texture.needsUpdate = true; }+ }++ // ---- feeds ----+ let timers = [];+ async function feed(key, load, kinds) {+ try {+ S[key] = { status: 'ok', items: await load() };+ } catch (err) {+ S[key] = { status: 'error', error: err?.message === 'no price' ? 'No price yet' : `Feed unavailable (${err?.message || 'network'})` };+ }+ repaint(kinds);+ }+ const FEEDS = {+ stats: () => feed('stats', loadStats, ['board']),+ agents: () => feed('agents', loadNewAgents, ['board']),+ launches: () => feed('launches', () => loadLaunches(5), ['board']),+ pulse: () => feed('pulse', async () => (await loadPulse({ limit: PULSE_LIMIT })).events, ['board', 'pulse']),+ token: () => feed('token', loadToken, ['board']),+ };+ function refreshAll() {+ return Promise.all(Object.values(FEEDS).map((f) => f()));+ }++ // ---- the player ----+ const player = createPlayer(scene, renderer, { spawn: SPAWN, yaw: SPAWN.yaw, bound: ROOM_BOUND, keepout: 0 });+ const cameraCtl = createCameraModeController({ storageKey: 'tws:grid-camera', onChange: syncCamera });+ function syncCamera() {+ $('.gd-cam-label').textContent = CAMERA_MODE_LABELS[cameraCtl.mode];+ player.setVisible(!cameraCtl.isFirstPerson());+ }+ syncCamera();+ $('.gd-cam').addEventListener('click', () => cameraCtl.cycle(camera));++ // ---- tier from the gems mined in the campus ----+ const tierEl = $('.gd-tier');+ const tierName = $('.gd-tier-name');+ const tierBar = $('.gd-bar i');+ const tierNote = $('.gd-tier-note');+ const miner = createMiner({+ onBalance(b) {+ if (b.offline) {+ tierName.textContent = 'TIER -';+ tierBar.style.width = '0%';+ tierNote.textContent = 'Gem ledger unreachable. It retries when you come back.';+ return;+ }+ const t = tierFor(Number(b.points) || 0);+ tierName.textContent = `TIER ${t.level} - ${t.name.toUpperCase()}`;+ tierBar.style.width = `${Math.round(t.progress * 100)}%`;+ tierEl.setAttribute('aria-label', `Tier ${t.level}, ${t.name}`);+ tierNote.textContent = t.next ? `${t.toNext} points to ${t.next}. Mine gems in the campus.` : 'Top tier reached.';+ },+ });++ // ---- input, proximity, interaction ----+ const controls = createControls(canvas, {+ onInteract: () => interact(),+ onCycleCamera: () => cameraCtl.cycle(camera),+ onTap: (e) => tap(e),+ });+ controls.orbit.yaw = SPAWN.yaw;+ controls.orbit.dist = 8;+ controls.orbit.pitch = 0.17;+ const ray = new Raycaster();+ const ndc = new Vector2();+ function tap(e) {+ const r = canvas.getBoundingClientRect();+ ndc.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1);+ ray.setFromCamera(ndc, camera);+ const hit = ray.intersectObjects(pickables, false)[0];+ if (!hit) return;+ const s = byId.get(hit.object.userData.surfaceId);+ if (!s) return;+ if (nearest === s) return interact();+ // Out of reach: step up to it, facing in, close enough to use.+ const d = s.def;+ const x = d.x + Math.sin(d.yaw) * 2.6;+ const z = d.z + Math.cos(d.yaw) * 2.6;+ const yaw = d.yaw + Math.PI;+ player.root.position.set(x, 0, z);+ player.root.rotation.y = yaw;+ controls.orbit.yaw = yaw;+ }++ let nearest = null;+ function updateNearest() {+ const p = player.position;+ const def = nearestSurface(p.x, p.z, surfaces.map((s) => s.def));+ const n = def ? byId.get(def.id) : null;+ if (n === nearest) return;+ if (nearest) { nearest.hot = false; paint(nearest); nearest.surf.texture.needsUpdate = true; }+ nearest = n;+ if (n) {+ n.hot = true;+ paint(n);+ n.surf.texture.needsUpdate = true;+ prompt.querySelector('b').textContent = n.def.title;+ prompt.querySelector('span').textContent = n.def.sub;+ prompt.querySelector('.gd-key').textContent = isTouch ? 'Tap' : 'E';+ }+ prompt.hidden = !n;+ }+ function interact() {+ if (!nearest) return;+ leave({ app: nearest.def.app });+ }+ $('.gd-desk').addEventListener('click', () => leave({ app: null, to: 'desktop' }));+ $('.gd-campus').addEventListener('click', () => leave({ app: null, to: 'campus' }));++ // ---- frame loop ----+ const governor = createFrameGovernor();+ const focus = trackWindowFocus();+ let saver = getPowerSaver();+ onPowerSaverChange((on) => (saver = on));+ let last = 0;+ let running = false;+ const limit = ROOM.half - 0.6;+ function frame(now) {+ const cap = saver || !focus.focused ? FPS_IDLE : FPS_ACTIVE;+ if (!governor.shouldRun(now, cap)) return;+ const dt = Math.min(0.05, last ? (now - last) / 1000 : 0.016);+ last = now;+ player.update(dt, controls.readMove(), controls.orbit.yaw, controls.run, solids);+ updateNearest();+ cameraCtl.tick(dt);+ cameraCtl.apply(camera, player.position, player.height, controls.orbit, 0.35);+ // The camera never leaves the room: walls would otherwise block the view.+ camera.position.x = Math.max(-limit, Math.min(limit, camera.position.x));+ camera.position.z = Math.max(-limit, Math.min(limit, camera.position.z));+ camera.position.y = Math.max(0.4, Math.min(ROOM.height - 0.5, camera.position.y));+ renderer.render(scene, camera);+ }+ function startLoop() {+ if (running) return;+ running = true;+ last = 0;+ governor.reset();+ renderer.setAnimationLoop(frame);+ }+ function stopLoop() {+ running = false;+ renderer.setAnimationLoop(null);+ }+ function resize() {+ renderer.setSize(innerWidth, innerHeight, false);+ camera.aspect = innerWidth / innerHeight;+ camera.updateProjectionMatrix();+ }+ addEventListener('resize', () => { if (!el.hidden) resize(); });++ // ---- lifecycle ----+ function leave(o) {+ stopLoop();+ timers.forEach(clearInterval);+ timers = [];+ el.hidden = true;+ document.documentElement.classList.remove('in-grid');+ onLeave(o);+ }+ let entered = false;+ function enter() {+ el.hidden = false;+ controls.enabled = true;+ // The desktop beneath may hold keyboard focus in an input (search, Run); controls ignore keys typed into one.+ document.activeElement?.blur?.();+ document.documentElement.classList.add('in-grid');+ resize();+ repaint();+ if (!entered) entered = true;+ refreshAll();+ miner.refresh();+ timers = [setInterval(() => { if (!document.hidden) { refreshAll(); miner.refresh(); } }, REFRESH_MS)];+ startLoop();+ }+ function dispose() {+ stopLoop();+ timers.forEach(clearInterval);+ surfaces.forEach((s) => { s.surf.dispose(); s.mesh.geometry.dispose(); s.mesh.material.dispose(); s.edge.geometry.dispose(); });+ renderer.dispose();+ el.remove();+ }+ return { el, enter, dispose, get entered() { return entered; } };+}diff --git a/src/desktop/grid/logic.js b/src/desktop/grid/logic.jsnew file mode 100644index 000000000..5ebf8230d--- /dev/null+++ b/src/desktop/grid/logic.js@@ -0,0 +1,127 @@+// The Grid's pure rules: the room, where every surface hangs, which one is in+// reach, the byte-tier ladder and the text helpers the panels use. No DOM and+// no three.js, so tests/desktop-grid.test.js can check all of it.++/** The room is a square of this half-width, in metres. Walls stand on it. */+export const ROOM = { half: 18, height: 10 };++/** The player may roam inside this radius (the room is square, the bound is round). */+export const ROOM_BOUND = 16.5;++export const SPAWN = { x: 0, z: 13, yaw: Math.PI };++/** Distance at which a surface arms its prompt. */+export const REACH = 3.6;++/** Byte-tier ladder. A tier is earned at its `at` gem points (mined in the campus). */+export const TIERS = [+ { name: 'Byte', at: 0 },+ { name: 'Kilobyte', at: 10 },+ { name: 'Megabyte', at: 30 },+ { name: 'Gigabyte', at: 80 },+ { name: 'Terabyte', at: 200 },+ { name: 'Petabyte', at: 500 },+ { name: 'Exabyte', at: 1200 },+ { name: 'Zettabyte', at: 3000 },+ { name: 'Yottabyte', at: 7500 },+];++/**+ * The tier for a gem-point balance: its number (1-based), name, and how far+ * the player is toward the next one (1 at the top tier).+ */+export function tierFor(points) {+ const p = Number.isFinite(points) && points > 0 ? points : 0;+ let i = 0;+ while (i + 1 < TIERS.length && p >= TIERS[i + 1].at) i++;+ const next = TIERS[i + 1] || null;+ const progress = next ? (p - TIERS[i].at) / (next.at - TIERS[i].at) : 1;+ return { level: i + 1, name: TIERS[i].name, progress, next: next ? next.name : null, toNext: next ? next.at - p : 0 };+}++/**+ * The info walls. Each hangs flat on a wall, centred at (x, y, z), turned to+ * face into the room by `yaw`. `app` is the desktop app E opens.+ */+export const WALLS = [+ { id: 'board', kind: 'board', title: 'Live board', sub: 'New agents, launches, wallet moves and $THREE', app: 'discover', x: 0, y: 6.5, z: -ROOM.half + 0.05, yaw: 0, w: 16, h: 6.4 },+ { id: 'wiki', kind: 'directory', title: 'Directory', sub: 'Every app in the room', app: 'apps', x: -ROOM.half + 0.05, y: 3.9, z: -2, yaw: Math.PI / 2, w: 10, h: 6.25 },+ { id: 'pulse', kind: 'pulse', title: 'Pulse', sub: 'Live agent wallet activity', app: 'pulse', x: ROOM.half - 0.05, y: 3.9, z: -2, yaw: -Math.PI / 2, w: 10, h: 6.25 },+];++export const KIOSK = { w: 3.3, h: 3.1, z: -11.5, gap: 0.45 };++/**+ * Standing kiosks, one per app, in a centred row across the room. Returns+ * placed surfaces; `x` is centred on the room and the row never leaves it.+ */+export function kioskLayout(apps, { half = ROOM.half - 2.5 } = {}) {+ const n = apps.length;+ if (!n) return [];+ const pitch = Math.min(KIOSK.w + KIOSK.gap, (half * 2) / n);+ const start = -((n - 1) * pitch) / 2;+ return apps.map((a, i) => ({+ id: `kiosk:${a.id}`,+ kind: 'kiosk',+ app: a.id,+ title: a.title,+ sub: a.desc || '',+ hue: a.hue,+ x: start + i * pitch,+ y: KIOSK.h / 2,+ z: KIOSK.z,+ yaw: 0,+ w: Math.min(KIOSK.w, pitch - 0.2),+ h: KIOSK.h,+ }));+}++/** The surface in reach of (x, z), nearest first, or null. */+export function nearestSurface(x, z, surfaces, reach = REACH) {+ let best = null;+ for (const s of surfaces) {+ // Distance to the surface's face, not its centre, so wide boards arm along their length.+ const dx = x - s.x;+ const dz = z - s.z;+ const cos = Math.cos(s.yaw);+ const sin = Math.sin(s.yaw);+ const along = dx * cos - dz * sin; // across the face+ const out = dx * sin + dz * cos; // out from the face+ const lateral = Math.max(0, Math.abs(along) - s.w / 2);+ const d = Math.hypot(lateral, out);+ if (out < -0.4 || d > reach) continue;+ if (!best || d < best.d) best = { d, surface: s };+ }+ return best ? best.surface : null;+}++/** Clip to `n` characters with an ellipsis. */+export function clip(s, n) {+ const t = String(s ?? '').replace(/\s+/g, ' ').trim();+ return t.length > n ? `${t.slice(0, Math.max(0, n - 1))}…` : t;+}++/** Break text into lines no wider than `max` characters; words longer than a line are cut. */+export function wrap(text, max) {+ const out = [];+ let line = '';+ for (const raw of String(text ?? '').split(/\s+/).filter(Boolean)) {+ let word = raw;+ while (word.length > max) {+ if (line) { out.push(line); line = ''; }+ out.push(word.slice(0, max));+ word = word.slice(max);+ }+ if (!line) line = word;+ else if (line.length + 1 + word.length <= max) line += ` ${word}`;+ else { out.push(line); line = word; }+ }+ if (line) out.push(line);+ return out;+}++/** A wallet address as `AbCd...wXyZ`. Anything short is returned whole. */+export function shortWallet(addr) {+ const a = String(addr ?? '');+ return a.length > 12 ? `${a.slice(0, 4)}...${a.slice(-4)}` : a;+}diff --git a/src/desktop/grid/panels.js b/src/desktop/grid/panels.jsnew file mode 100644index 000000000..5d9a7cc1d--- /dev/null+++ b/src/desktop/grid/panels.js@@ -0,0 +1,204 @@+// Canvas painters for the Grid's surfaces. Each takes the live state the+// controller holds and draws one neon-on-black panel. A feed that has not+// landed draws a skeleton; a feed that failed says so and names the retry.++import { CanvasTexture, SRGBColorSpace, LinearFilter } from 'three';+import { clip, wrap } from './logic.js';+import { describeEvent, fmtUsd, fmtPct, fmtCount, relTime } from '../../field/logic.js';++export const INK = '#19ffb0';+export const DIM = '#0d7a55';+export const FAINT = '#073d2b';+export const BG = '#020a07';+const FONT = '"JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';++/** A canvas surface and the texture that mirrors it. */+export function createSurface(w, h, anisotropy = 4) {+ const canvas = document.createElement('canvas');+ canvas.width = w;+ canvas.height = h;+ const ctx = canvas.getContext('2d');+ const texture = new CanvasTexture(canvas);+ texture.colorSpace = SRGBColorSpace;+ texture.minFilter = LinearFilter;+ texture.generateMipmaps = false;+ texture.anisotropy = anisotropy;+ return { canvas, ctx, texture, w, h, dispose: () => texture.dispose() };+}++function font(ctx, px, weight = 500) {+ ctx.font = `${weight} ${px}px ${FONT}`;+}++function frame(ctx, w, h, hot) {+ ctx.fillStyle = BG;+ ctx.fillRect(0, 0, w, h);+ ctx.strokeStyle = hot ? INK : DIM;+ ctx.lineWidth = hot ? 6 : 3;+ ctx.strokeRect(1.5, 1.5, w - 3, h - 3);+}++function heading(ctx, x, y, title, tag, scale = 1) {+ ctx.textBaseline = 'alphabetic';+ ctx.fillStyle = INK;+ font(ctx, 46 * scale, 700);+ ctx.fillText(title, x, y);+ if (tag) {+ const tw = ctx.measureText(title).width;+ ctx.fillStyle = DIM;+ font(ctx, 22 * scale, 500);+ ctx.fillText(tag, x + tw + 18 * scale, y);+ }+}++function card(ctx, x, y, w, h, lines, hot) {+ ctx.fillStyle = hot ? '#0a3d2c' : '#05261b';+ ctx.fillRect(x, y, w, h);+ ctx.strokeStyle = DIM;+ ctx.lineWidth = 2;+ ctx.strokeRect(x + 1, y + 1, w - 2, h - 2);+ let ly = y + 30;+ for (const l of lines) {+ ctx.fillStyle = l.dim ? DIM : INK;+ font(ctx, l.px || 22, l.bold ? 700 : 500);+ ctx.fillText(l.text, x + 14, ly);+ ly += (l.px || 22) + 8;+ }+}++function skeleton(ctx, x, y, w, rows, rowH, gap) {+ for (let i = 0; i < rows; i++) {+ ctx.fillStyle = FAINT;+ ctx.fillRect(x, y + i * (rowH + gap), w, rowH);+ }+}++function notice(ctx, x, y, w, title, body) {+ ctx.fillStyle = INK;+ font(ctx, 24, 700);+ ctx.fillText(title, x, y);+ ctx.fillStyle = DIM;+ font(ctx, 20, 500);+ wrap(body, Math.floor(w / 12)).forEach((l, i) => ctx.fillText(l, x, y + 32 + i * 26));+}++/** `{ status: 'loading' | 'ok' | 'error', items, error }` per feed. */+const live = (s) => s && s.status === 'ok';++/**+ * The back-wall board: four live columns, the way a task board reads.+ * @param {{ stats: object, agents: object, launches: object, pulse: object, token: object }} S+ */+export function paintBoard(surface, S, hot) {+ const { ctx, w, h } = surface;+ frame(ctx, w, h, hot);+ const pad = 36;+ heading(ctx, pad, 74, 'three.ws', 'LIVE BOARD');+ if (live(S.stats)) {+ const t = S.stats.items;+ ctx.textAlign = 'right';+ ctx.fillStyle = DIM;+ font(ctx, 24, 500);+ ctx.fillText(`${fmtCount(t.agents)} agents | ${fmtCount(t.launches)} launches | ${fmtCount(t.strategies)} strategies`, w - pad, 70);+ ctx.textAlign = 'left';+ }+ const cols = [+ { title: 'NEW AGENTS', feed: S.agents, retry: 'agents', rows: (a) => [{ text: clip(a.name || 'Unnamed agent', 20), bold: true, px: 24 }, { text: clip(a.description || 'No description yet', 28), dim: true }], count: 5 },+ { title: 'LAUNCHES', feed: S.launches, retry: 'launches', rows: (l) => [{ text: clip(l.name || 'Unnamed', 20), bold: true, px: 24 }, { text: `$${clip(String(l.symbol || '').toUpperCase(), 8)} by ${clip(l.agent?.name || 'an agent', 14)}`, dim: true }], count: 5 },+ { title: 'WALLET MOVES', feed: S.pulse, retry: 'pulse', rows: (e) => [{ text: clip(describeEvent(e), 30), bold: true, px: 20 }, { text: `${e.kind || 'move'}${e.usd ? ` ${fmtUsd(e.usd)}` : ''} ${relTime(e.ts)}`, dim: true }], count: 5 },+ { title: '$THREE', feed: S.token, retry: 'token', rows: null, count: 0 },+ ];+ const gap = 20;+ const top = 112;+ const cw = (w - pad * 2 - gap * (cols.length - 1)) / cols.length;+ cols.forEach((c, i) => {+ const x = pad + i * (cw + gap);+ ctx.fillStyle = INK;+ font(ctx, 22, 700);+ ctx.fillText(c.title, x, top + 14);+ ctx.strokeStyle = DIM;+ ctx.lineWidth = 2;+ ctx.beginPath();+ ctx.moveTo(x, top + 28);+ ctx.lineTo(x + cw, top + 28);+ ctx.stroke();+ const y0 = top + 46;+ if (!c.feed || c.feed.status === 'loading') return skeleton(ctx, x, y0, cw, 5, 96, 14);+ if (c.feed.status === 'error') return notice(ctx, x, y0 + 24, cw, 'Offline', `${c.feed.error || 'The feed did not answer'}. It retries on its own.`);+ if (c.title === '$THREE') {+ const t = c.feed.items;+ card(ctx, x, y0, cw, 150, [+ { text: fmtUsd(t.price) || '--', bold: true, px: 44 },+ { text: fmtPct(t.change) ? `${fmtPct(t.change)} 24h` : '24h change unavailable', dim: true, px: 22 },+ ]);+ card(ctx, x, y0 + 164, cw, 118, [{ text: `cap ${fmtUsd(t.cap) || '--'}`, px: 22 }, { text: `vol ${fmtUsd(t.volume) || '--'}`, dim: true }, { text: `${fmtCount(t.holders)} holders`, dim: true }]);+ return;+ }+ const items = c.feed.items.slice(0, c.count);+ if (!items.length) return notice(ctx, x, y0 + 24, cw, 'Nothing yet', 'New entries appear here the moment they land.');+ items.forEach((it, k) => card(ctx, x, y0 + k * 110, cw, 98, c.rows(it)));+ });+}++/** The side wall that lists every app and what it does. */+export function paintDirectory(surface, apps, hot) {+ const { ctx, w, h } = surface;+ frame(ctx, w, h, hot);+ heading(ctx, 36, 70, 'DIRECTORY', `${apps.length} apps`, 0.9);+ const rowH = Math.floor((h - 130) / Math.max(apps.length, 1));+ apps.forEach((a, i) => {+ const y = 112 + i * rowH;+ ctx.fillStyle = i % 2 ? '#04180f' : '#052217';+ ctx.fillRect(28, y, w - 56, rowH - 6);+ ctx.fillStyle = INK;+ font(ctx, 26, 700);+ ctx.fillText(a.title, 46, y + rowH / 2 - 2);+ ctx.fillStyle = DIM;+ font(ctx, 19, 500);+ ctx.fillText(clip(a.desc || '', 56), 46, y + rowH / 2 + 24);+ });+}++/** The wallet-moves wall. */+export function paintPulse(surface, S, hot) {+ const { ctx, w, h } = surface;+ frame(ctx, w, h, hot);+ heading(ctx, 36, 70, 'PULSE', 'WALLET MOVES', 0.9);+ const f = S.pulse;+ if (!f || f.status === 'loading') return skeleton(ctx, 36, 110, w - 72, 6, 60, 14);+ if (f.status === 'error') return notice(ctx, 36, 140, w - 72, 'Pulse is offline', `${f.error || 'The feed did not answer'}. It retries on its own.`);+ if (!f.items.length) return notice(ctx, 36, 140, w - 72, 'Quiet right now', 'Agent wallet moves appear here as they happen.');+ f.items.slice(0, 7).forEach((e, i) => {+ const y = 110 + i * 70;+ ctx.fillStyle = i % 2 ? '#04180f' : '#052217';+ ctx.fillRect(28, y, w - 56, 62);+ ctx.fillStyle = INK;+ font(ctx, 21, 700);+ ctx.fillText(clip(describeEvent(e), 52), 44, y + 27);+ ctx.fillStyle = DIM;+ font(ctx, 18, 500);+ ctx.fillText(`${e.kind || 'move'}${e.usd ? ` ${fmtUsd(e.usd)}` : ''} ${relTime(e.ts)}`, 44, y + 51);+ });+}++/** One app's standing kiosk. */+export function paintKiosk(surface, app, hot) {+ const { ctx, w, h } = surface;+ frame(ctx, w, h, hot);+ ctx.fillStyle = hot ? '#0a3d2c' : '#05261b';+ ctx.fillRect(24, 24, w - 48, h * 0.34);+ ctx.textAlign = 'center';+ ctx.fillStyle = INK;+ // Shrink the title until it fits the slab, so long names never clip.+ let px = 66;+ font(ctx, px, 700);+ while (px > 30 && ctx.measureText(app.title.toUpperCase()).width > w - 80) font(ctx, (px -= 4), 700);+ ctx.fillText(app.title.toUpperCase(), w / 2, 24 + h * 0.34 / 2 + px * 0.34);+ ctx.fillStyle = DIM;+ font(ctx, 29, 500);+ wrap(app.sub || '', 20).slice(0, 4).forEach((l, i) => ctx.fillText(l, w / 2, h * 0.52 + i * 38));+ ctx.fillStyle = hot ? INK : DIM;+ font(ctx, 30, 700);+ ctx.fillText(hot ? 'PRESS E TO OPEN' : 'OPEN APP', w / 2, h - 30);+ ctx.textAlign = 'left';+}diff --git a/src/desktop/main.js b/src/desktop/main.jsindex d13732417..37e43474a 100644--- a/src/desktop/main.js+++ b/src/desktop/main.js@@ -8,7 +8,7 @@ import './desktop.css';import './styles.css';import './boot.css';import { createShell } from './shell.js';-import { APPS } from './apps.js';+import { APPS, ALL_APPS } from './apps.js';import { deepLinkApp, initialsOf, sanitizePrefs } from './layout.js';import { runBootSteps, entryMode, showBoot, gpuName } from './boot-logic.js';import { createBootScreen, playChime } from './boot.js';@@ -195,15 +195,36 @@ async function main() {};let world = null;+ let grid = null;let lastPlace = null;+ const wantsGrid = webgl && new URLSearchParams(location.search).get('world') === 'grid';+ /** The Grid loads on first use: it brings its own scene, so the desktop boot stays light. */+ async function enterGrid() {+ if (!grid) {+ const { createGrid } = await import('./grid/index.js');+ grid = createGrid({+ apps: APPS.filter((a) => a.dock),+ directory: ALL_APPS.filter((a) => a.desktop && a.id !== 'welcome'),+ reducedMotion,+ onLeave({ app, to }) {+ if (to === 'campus' && world) return world.enter();+ if (app && shell.hasApp(app)) shell.launchId(app);+ else landOnDesktop();+ },+ });+ }+ grid.enter();+ }if (webgl) {const { createWorld } = await import('./world/index.js');world = createWorld({shell,apps: APPS.filter((a) => a.dock),reducedMotion,- onDesktop({ app, place }) {+ onGrid: true,+ onDesktop({ app, place, grid: toGrid }) {document.documentElement.classList.remove('in-world');+ if (toGrid) return enterGrid();lastPlace = place || null;if (app && shell.hasApp(app)) shell.launchId(app);else landOnDesktop();@@ -214,7 +235,10 @@ async function main() {// The world mounts under the boot screen (its fade is already black), so// the boot dissolves straight into the campus with no desktop flash.- if (choice === 'world' && world) await Promise.all([world.enter(), boot?.dismiss()]);+ if (wantsGrid) {+ await boot?.dismiss();+ await enterGrid();+ } else if (choice === 'world' && world) await Promise.all([world.enter(), boot?.dismiss()]);else {if (boot) await boot.dismiss();landOnDesktop();diff --git a/src/desktop/world/index.js b/src/desktop/world/index.jsindex a580b9d34..c678efe8b 100644--- a/src/desktop/world/index.js+++ b/src/desktop/world/index.js@@ -49,7 +49,7 @@ async function settled(el) {* onDesktop: (o: { app?: string|null, place?: string|null }) => void,* }} o*/-export function createWorld({ shell, apps, reducedMotion = false, onDesktop }) {+export function createWorld({ shell, apps, reducedMotion = false, onDesktop, onGrid }) {const el = h('div', 'wd');el.hidden = true;el.innerHTML = `@@ -61,6 +61,7 @@ export function createWorld({ shell, apps, reducedMotion = false, onDesktop }) {<button type="button" class="wd-tool wd-gems" aria-haspopup="dialog" aria-expanded="false" title="Your gems">${icon('gem', 18)}<span class="wd-gems-pts">0</span></button><button type="button" class="wd-tool wd-cam" title="Camera (C)">${icon('camera', 18)}<span class="wd-cam-label"></span></button><button type="button" class="wd-tool wd-vr" hidden title="Enter VR">${icon('vr', 18)}<span>VR</span></button>+ ${onGrid ? `<button type="button" class="wd-tool wd-grid" title="Step into the Grid">${icon('grid', 18)}<span>Grid</span></button>` : ''}<button type="button" class="wd-tool wd-desk" title="Go straight to the desktop">${icon('desktop', 18)}<span>Desktop</span></button></div></div>@@ -312,6 +313,7 @@ export function createWorld({ shell, apps, reducedMotion = false, onDesktop }) {});$('.wd-vr').addEventListener('click', () => wearHeadset());$('.wd-desk').addEventListener('click', () => sitDown());+ $('.wd-grid')?.addEventListener('click', () => { talk.close(); leaveTo({ grid: true }); });async function interact() {if (busy || !nearest) return;diff --git a/tests/desktop-grid.test.js b/tests/desktop-grid.test.jsnew file mode 100644index 000000000..bb13c114e--- /dev/null+++ b/tests/desktop-grid.test.js@@ -0,0 +1,99 @@+import { describe, it, expect } from 'vitest';+import { ROOM, ROOM_BOUND, SPAWN, TIERS, WALLS, KIOSK, tierFor, kioskLayout, nearestSurface, clip, wrap, shortWallet } from '../src/desktop/grid/logic.js';+import { APPS, ALL_APPS } from '../src/desktop/apps.js';++describe('the Grid byte tiers', () => {+ it('starts at Byte with no points and treats junk as zero', () => {+ expect(tierFor(0)).toMatchObject({ level: 1, name: 'Byte', next: 'Kilobyte', progress: 0, toNext: 10 });+ expect(tierFor(NaN).level).toBe(1);+ expect(tierFor(-5).level).toBe(1);+ });+ it('moves up exactly at each threshold', () => {+ TIERS.forEach((t, i) => expect(tierFor(t.at).level).toBe(i + 1));+ expect(tierFor(29).name).toBe('Kilobyte');+ expect(tierFor(30).name).toBe('Megabyte');+ });+ it('reports progress toward the next tier and tops out at 1', () => {+ expect(tierFor(20).progress).toBeCloseTo(0.5);+ const top = tierFor(1e9);+ expect(top.name).toBe('Yottabyte');+ expect(top).toMatchObject({ progress: 1, next: null, toNext: 0 });+ });+});++describe('the Grid layout', () => {+ const dock = APPS.filter((a) => a.dock);+ const kiosks = kioskLayout(dock);++ it('gives every dock app one kiosk that opens that app', () => {+ expect(kiosks.map((k) => k.app)).toEqual(dock.map((a) => a.id));+ expect(new Set(kiosks.map((k) => k.id)).size).toBe(kiosks.length);+ });+ it('keeps the kiosk row centred, inside the walls and non-overlapping', () => {+ const xs = kiosks.map((k) => k.x);+ expect(xs[0] + xs[xs.length - 1]).toBeCloseTo(0);+ kiosks.forEach((k) => expect(Math.abs(k.x) + k.w / 2).toBeLessThan(ROOM.half));+ for (let i = 1; i < kiosks.length; i++) expect(kiosks[i].x - kiosks[i - 1].x).toBeGreaterThanOrEqual(kiosks[i].w);+ });+ it('handles zero and one app', () => {+ expect(kioskLayout([])).toEqual([]);+ expect(kioskLayout([dock[0]])[0].x).toBeCloseTo(0);+ });+ it('points every wall into the room and opens a real app', () => {+ const ids = new Set(ALL_APPS.map((a) => a.id));+ for (const w of WALLS) {+ expect(ids.has(w.app)).toBe(true);+ const nx = Math.sin(w.yaw) * 1;+ const nz = Math.cos(w.yaw) * 1;+ // stepping one metre along the normal from the wall lands inside the room+ expect(Math.abs(w.x + nx)).toBeLessThan(ROOM.half);+ expect(Math.abs(w.z + nz)).toBeLessThan(ROOM.half);+ }+ });+ it('spawns the player inside the roaming bound, facing the board', () => {+ expect(Math.hypot(SPAWN.x, SPAWN.z)).toBeLessThan(ROOM_BOUND);+ expect(KIOSK.z).toBeGreaterThan(-ROOM.half);+ });+});++describe('the Grid proximity', () => {+ const all = [...WALLS, ...kioskLayout(APPS.filter((a) => a.dock))];++ it('arms nothing in the middle of an empty floor', () => {+ expect(nearestSurface(0, 13, all)).toBeNull();+ });+ it('arms the board along its length, not just at its centre', () => {+ expect(nearestSurface(6, -15.5, all)?.id).toBe('board');+ expect(nearestSurface(-6, -15.5, all)?.id).toBe('board');+ });+ it('arms the side walls from inside the room', () => {+ expect(nearestSurface(-15.5, -2, all)?.id).toBe('wiki');+ expect(nearestSurface(15.5, -2, all)?.id).toBe('pulse');+ });+ it('does not arm a surface from behind it', () => {+ expect(nearestSurface(0, -19.5, [WALLS[0]])).toBeNull();+ });+ it('picks the closest kiosk', () => {+ const k = kioskLayout(APPS.filter((a) => a.dock));+ const mid = k[3];+ expect(nearestSurface(mid.x, mid.z + 1.6, k)?.id).toBe(mid.id);+ });+});++describe('the Grid text helpers', () => {+ it('clips with an ellipsis and collapses whitespace', () => {+ expect(clip('a b\n c', 10)).toBe('a b c');+ expect(clip('abcdefghij', 5)).toBe('abcd…');+ expect(clip(null, 5)).toBe('');+ });+ it('wraps on words and cuts words longer than a line', () => {+ expect(wrap('one two three', 7)).toEqual(['one two', 'three']);+ expect(wrap('abcdefghij', 4)).toEqual(['abcd', 'efgh', 'ij']);+ expect(wrap('', 5)).toEqual([]);+ });+ it('shortens wallets and leaves short strings alone', () => {+ expect(shortWallet('xcgUabcdefghijkliPnp')).toBe('xcgU...iPnp');+ expect(shortWallet('abc')).toBe('abc');+ expect(shortWallet(undefined)).toBe('');+ });+});