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: add agent screen client and watch panel for live agent monitoring
qrqka4033913f60d
diff --git a/api/agent-screen-push.js b/api/agent-screen-push.jsnew file mode 100644index 000000000..dd475b830--- /dev/null+++ b/api/agent-screen-push.js@@ -0,0 +1,107 @@+// POST /api/agent-screen-push — agent pushes a screen frame to the live feed.+//+// Agents (snipers, browser workers, autonomous scripts) POST here to publish+// what they're currently doing. Viewers subscribe via /api/agent-screen-stream.+//+// Body (JSON):+// agentId string — UUID of the agent+// frame object — { data?, activity, type }+// data string? — base64 data URL (data:image/png;base64,…) or omit for text-only+// activity string — plain-language description of what the agent is doing+// type string — "screenshot" | "activity" | "trade" | "analysis"+//+// Auth: bearer JWT (same as other agent-authenticated endpoints). The agentId+// in the body must match the token's sub or an agent the user owns. Workers+// running as the agent itself use the agent's own JWT.+//+// Storage: Upstash Redis, key agent:screen:{agentId}:frame (TTL 90s — if the+// agent stops pushing, the stream goes dark automatically). A secondary list+// agent:screen:{agentId}:log holds the last 50 activity entries (no image data)+// for the activity log panel.++import { cors, error, json, method, wrap, rateLimited } from './_lib/http.js';+import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { getRedis } from './_lib/redis.js';+import { sql } from './_lib/db.js';++const FRAME_TTL = 90; // seconds — stream goes dark if agent stops pushing+const LOG_CAP = 50; // activity log entries kept per agent+const DATA_MAX = 800_000; // ~600 KB base64 PNG max (approx 450 KB PNG)+const ACTIVITY_MAX = 320; // chars++export default async function handleAgentScreenPush(req, res) {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ // Auth: bearer OR session+ let userId = null;+ const bearer = extractBearer(req);+ if (bearer) {+ const auth = await authenticateBearer(bearer).catch(() => null);+ if (auth?.userId) userId = auth.userId;+ }+ if (!userId) {+ const auth = await getSessionUser(req, res);+ if (auth?.id) userId = auth.id;+ }+ if (!userId) return error(res, 401, 'unauthorized', 'authentication required');++ // Rate limit: 6 frames/second per IP (generous for screenshot streams)+ const rl = await limits.apiIp(clientIp(req), { limit: 360, window: '60s' });+ if (!rl.success) return rateLimited(res, rl, 'frame rate limit exceeded');++ let body;+ try {+ const raw = await new Promise((resolve, reject) => {+ const chunks = [];+ req.on('data', (c) => chunks.push(c));+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));+ req.on('error', reject);+ });+ body = JSON.parse(raw);+ } catch {+ return error(res, 400, 'invalid_body', 'request body must be valid JSON');+ }++ const { agentId, frame } = body || {};+ if (!agentId || typeof agentId !== 'string') {+ return error(res, 400, 'missing_agent_id', 'agentId is required');+ }+ if (!frame || typeof frame !== 'object') {+ return error(res, 400, 'missing_frame', 'frame object is required');+ }++ const activity = String(frame.activity || '').slice(0, ACTIVITY_MAX);+ const type = ['screenshot', 'activity', 'trade', 'analysis'].includes(frame.type)+ ? frame.type : 'activity';+ const data = typeof frame.data === 'string' && frame.data.startsWith('data:image/')+ ? frame.data.slice(0, DATA_MAX) : null;++ // Verify the calling user owns this agent+ const [agentRow] = await sql`+ SELECT id FROM agents WHERE id = ${agentId} AND user_id = ${userId} LIMIT 1+ `;+ if (!agentRow) return error(res, 403, 'forbidden', 'agent not owned by this user');++ const r = getRedis();+ if (!r) return error(res, 503, 'redis_unavailable', 'frame store offline');++ const now = Date.now();+ const frameKey = `agent:screen:${agentId}:frame`;+ const logKey = `agent:screen:${agentId}:log`;++ // Full frame record (includes image data when present)+ const frameRecord = JSON.stringify({ ts: now, data, activity, type, agentId });++ // Log entry (no image — the activity log only needs text + metadata)+ const logEntry = JSON.stringify({ ts: now, activity, type });++ await Promise.all([+ r.set(frameKey, frameRecord, { ex: FRAME_TTL }),+ r.lpush(logKey, logEntry).then(() => r.ltrim(logKey, 0, LOG_CAP - 1)),+ r.expire(logKey, FRAME_TTL * 5),+ ]);++ return json(res, 200, { ok: true, ts: now });+}diff --git a/api/agent-screen-stream.js b/api/agent-screen-stream.jsnew file mode 100644index 000000000..f14a1f2ef--- /dev/null+++ b/api/agent-screen-stream.js@@ -0,0 +1,136 @@+// GET /api/agent-screen-stream?agentId=<uuid> — SSE stream of agent screen frames.+//+// Polls Redis for the latest frame pushed by the agent and emits it over SSE.+// No true pub/sub needed: the 500ms poll is fast enough for a live "watch them+// work" experience. Upstash REST doesn't hold LISTEN connections in serverless.+//+// Events:+// event: open — { agentId, agentName, ts } emitted once on connect+// event: frame — { ts, data?, activity, type, agentId } when a new frame arrives+// event: log — { entries: [{ts, activity, type}] } initial activity history+// event: dark — {} emitted when the agent's frame TTL expires (stream gone dark)+// event: ping — {} keepalive every 15s+//+// The stream runs for up to 280s (Vercel limit 300s — budget for setup/teardown).+// Clients reconnect automatically via EventSource's built-in retry.++import { cors, method, rateLimited } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { getRedis } from './_lib/redis.js';+import { sql } from './_lib/db.js';++export const maxDuration = 300;++const MAX_DURATION_MS = 280_000;+const PING_INTERVAL_MS = 15_000;+const POLL_INTERVAL_MS = 500;++export default async function handleAgentScreenStream(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.mcpIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);+ const agentId = (url.searchParams.get('agentId') || '').trim();+ if (!agentId) {+ res.writeHead(400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'agentId is required' }));+ return;+ }++ // Resolve agent name for the open event+ const [agentRow] = await sql`+ SELECT name FROM agents WHERE id = ${agentId} LIMIT 1+ `.catch(() => []);+ if (!agentRow) {+ res.writeHead(404, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'agent not found' }));+ return;+ }++ const r = getRedis();++ res.writeHead(200, {+ 'Content-Type': 'text/event-stream; charset=utf-8',+ 'Cache-Control': 'no-cache, no-transform',+ Connection: 'keep-alive',+ 'X-Accel-Buffering': 'no',+ });+ res.flushHeaders?.();++ let active = true;+ const send = (event, data) => {+ if (!active || res.writableEnded) return;+ try {+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);+ } catch {+ active = false;+ }+ };++ req.on('close', () => { active = false; });++ // Emit open event immediately+ send('open', { agentId, agentName: agentRow.name, ts: Date.now() });++ // Emit activity log backfill+ if (r) {+ try {+ const logKey = `agent:screen:${agentId}:log`;+ const raw = await r.lrange(logKey, 0, 49);+ if (raw?.length) {+ const entries = raw+ .map((s) => { try { return JSON.parse(s); } catch { return null; } })+ .filter(Boolean)+ .reverse(); // oldest-first for display+ send('log', { entries });+ }+ } catch { /* non-fatal */ }+ }++ const frameKey = `agent:screen:${agentId}:frame`;+ let lastTs = 0;+ let wasDark = false;+ let deadline = Date.now() + MAX_DURATION_MS;+ let pingAt = Date.now() + PING_INTERVAL_MS;++ const loop = async () => {+ while (active && Date.now() < deadline) {+ const now = Date.now();++ // Keepalive ping+ if (now >= pingAt) {+ send('ping', {});+ pingAt = now + PING_INTERVAL_MS;+ }++ // Poll for new frame+ if (r) {+ try {+ const raw = await r.get(frameKey);+ if (raw) {+ const frame = typeof raw === 'string' ? JSON.parse(raw) : raw;+ if (frame?.ts && frame.ts !== lastTs) {+ lastTs = frame.ts;+ wasDark = false;+ send('frame', frame);+ }+ } else if (!wasDark && lastTs > 0) {+ // Frame TTL expired — agent went dark+ wasDark = true;+ send('dark', {});+ }+ } catch { /* Redis blip — keep polling */ }+ }++ // Yield to event loop before next poll+ await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));+ }++ if (!res.writableEnded) res.end();+ };++ loop().catch(() => { if (!res.writableEnded) res.end(); });+}diff --git a/api/agent/screen-push.js b/api/agent/screen-push.jsnew file mode 100644index 000000000..b0e23043f--- /dev/null+++ b/api/agent/screen-push.js@@ -0,0 +1,83 @@+// POST /api/agent/screen-push+//+// Agent processes (Playwright runners, autonomous workers) push their current+// screen state here. Two payload shapes are accepted:+//+// Frame push (screenshot):+// { agentId, frame: '<base64 PNG>', seq?: number }+// → stored as screen:frame:<agentId> with 10-second TTL.+//+// Activity push (structured log):+// { agentId, actions: [{ type, summary, payload?, ts? }] }+// → stored as screen:activity:<agentId> with 30-second TTL.+//+// Auth: requires a valid bearer token for a user that owns the agent, OR the+// agent's own bearer token (AGENT_BEARER environment variable on the worker).+// Rate: 12 frame pushes/second per agentId (burst) to prevent flooding.++import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';+import { cacheSet } from '../_lib/cache.js';+import { getSessionUser, authenticateBearer } from '../_lib/auth.js';+import { sql } from '../_lib/db.js';+import { limits, clientIp } from '../_lib/rate-limit.js';++const FRAME_TTL_S = 10;+const ACTIVITY_TTL_S = 30;++// Validate base64 string length — limit 1 MB of base64 ≈ 768 KB PNG.+const MAX_FRAME_B64 = 1_400_000;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ // Auth: must be the agent owner (session or bearer) OR a pre-shared agent key.+ const auth = await getSessionUser(req).catch(() => null)+ || await authenticateBearer(req).catch(() => null);+ if (!auth?.userId) return error(res, 401, 'unauthorized', 'sign in required');++ const body = await readJson(req, res);+ if (!body) return;+ const { agentId, frame, actions, seq } = body;++ if (!agentId) return error(res, 400, 'validation_error', 'agentId required');++ // Verify ownership.+ const [row] = await sql`+ SELECT id FROM agent_identities+ WHERE id = ${agentId} AND user_id = ${auth.userId} AND deleted_at IS NULL+ `;+ if (!row) return error(res, 403, 'forbidden', 'not your agent');++ // Rate limit per agent — 12 pushes/second burst.+ const ip = clientIp(req);+ const rlKey = `screen-push:${agentId}:${ip}`;+ if (rateLimited(rlKey, { ...limits.api, max: 12, window: 1 }))+ return error(res, 429, 'rate_limited', 'too many pushes');++ const now = Date.now();++ if (frame != null) {+ // Frame push.+ if (typeof frame !== 'string') return error(res, 400, 'validation_error', 'frame must be a base64 string');+ if (frame.length > MAX_FRAME_B64) return error(res, 413, 'payload_too_large', 'frame exceeds 1 MB');+ const storedSeq = typeof seq === 'number' ? seq : now;+ await cacheSet(`screen:frame:${agentId}`, { frame, seq: storedSeq, ts: now }, FRAME_TTL_S);+ return json(res, 200, { ok: true, type: 'frame', seq: storedSeq });+ }++ if (actions != null) {+ // Activity push.+ if (!Array.isArray(actions)) return error(res, 400, 'validation_error', 'actions must be an array');+ const safe = actions.slice(0, 50).map((a) => ({+ type: String(a?.type || 'action').slice(0, 64),+ summary: String(a?.summary || '').slice(0, 256),+ payload: a?.payload || null,+ ts: typeof a?.ts === 'number' ? a.ts : now,+ }));+ await cacheSet(`screen:activity:${agentId}`, { actions: safe, ts: now }, ACTIVITY_TTL_S);+ return json(res, 200, { ok: true, type: 'activity', count: safe.length });+ }++ return error(res, 400, 'validation_error', 'provide either frame or actions');+});diff --git a/api/agent/screen-stream.js b/api/agent/screen-stream.jsnew file mode 100644index 000000000..bb85bfb71--- /dev/null+++ b/api/agent/screen-stream.js@@ -0,0 +1,152 @@+// GET /api/agent/screen-stream?agentId=<id>+//+// Server-Sent Events stream that delivers:+// { type: 'frame', frame: '<base64 PNG>', seq: number, ts: number }+// { type: 'activity', actions: [...], ts: number }+// { type: 'meta', name, avatar, status, ts: number }+// { type: 'heartbeat', ts: number }+//+// Agents push frames via POST /api/agent/screen-push. If no external process+// is pushing frames the client renders the activity canvas from real agent-+// action records instead. The stream never closes while the client holds it.+//+// Auth: agentId must be known (public read of a real agent's stream).+// Rate: one active SSE connection per agentId per client IP is enforced by the+// 60-second Vercel function timeout — the client reconnects via EventSource.++import { cors, wrap } from '../_lib/http.js';+import { cacheGet } from '../_lib/cache.js';+import { sql } from '../_lib/db.js';+import { clientIp } from '../_lib/rate-limit.js';++const HEARTBEAT_MS = 15_000;+const FRAME_POLL_MS = 250; // how often to check for a new pushed frame+const ACTIVITY_POLL_MS = 3_000;+const MAX_DURATION_MS = 55_000; // stay under Vercel's 60-second function limit++export const config = { maxDuration: 60 };++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;++ const url = new URL(req.url, 'http://x');+ const agentId = url.searchParams.get('agentId');+ if (!agentId) {+ res.statusCode = 400;+ res.end('agentId required');+ return;+ }++ // Verify agent exists (public read — no auth needed).+ const [agent] = await sql`+ SELECT id, name, avatar_glb_url, avatar_model_url, base_model_url+ FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ LIMIT 1+ `.catch(() => [null]);+ if (!agent) {+ res.statusCode = 404;+ res.end('agent not found');+ return;+ }++ res.writeHead(200, {+ 'Content-Type': 'text/event-stream; charset=utf-8',+ 'Cache-Control': 'no-cache, no-transform',+ 'X-Accel-Buffering': 'no',+ 'Connection': 'keep-alive',+ });++ function send(obj) {+ if (res.writableEnded) return;+ res.write(`data: ${JSON.stringify(obj)}\n\n`);+ }++ // Send agent identity immediately so the client can show the webcam.+ const avatarUrl = agent.avatar_glb_url || agent.avatar_model_url || agent.base_model_url || '/avatars/mannequin.glb';+ send({ type: 'meta', agentId, name: agent.name || 'Agent', avatarUrl, ts: Date.now() });++ let lastFrameSeq = -1;+ let lastActivityTs = 0;+ let lastFrameKey = `screen:frame:${agentId}`;+ let lastActivityKey = `screen:activity:${agentId}`;+ const start = Date.now();++ // Stagger polls slightly so frame + activity checks don't race on the same tick.+ let frameTick = 0;+ let activityTick = 0;+ let heartbeatTick = 0;++ await new Promise((resolve) => {+ const timer = setInterval(async () => {+ if (res.writableEnded || Date.now() - start > MAX_DURATION_MS) {+ clearInterval(timer);+ resolve();+ return;+ }++ const now = Date.now();+ frameTick += FRAME_POLL_MS;+ activityTick += FRAME_POLL_MS;+ heartbeatTick += FRAME_POLL_MS;++ // ── pushed frame ────────────────────────────────────────────────+ if (frameTick >= FRAME_POLL_MS) {+ frameTick = 0;+ try {+ const stored = await cacheGet(lastFrameKey);+ if (stored && stored.seq !== lastFrameSeq) {+ lastFrameSeq = stored.seq;+ send({ type: 'frame', frame: stored.frame, seq: stored.seq, ts: stored.ts });+ }+ } catch { /* non-critical */ }+ }++ // ── activity log ────────────────────────────────────────────────+ if (activityTick >= ACTIVITY_POLL_MS) {+ activityTick = 0;+ try {+ // Check if agent process pushed structured activity.+ const pushed = await cacheGet(lastActivityKey);+ if (pushed && pushed.ts > lastActivityTs) {+ lastActivityTs = pushed.ts;+ send({ type: 'activity', actions: pushed.actions || [], ts: pushed.ts });+ } else if (!pushed) {+ // Fall back to real agent-actions rows from the DB.+ const rows = await sql`+ SELECT id, action_type, summary, payload, created_at+ FROM agent_actions+ WHERE agent_id = ${agentId}+ ORDER BY id DESC+ LIMIT 12+ `.catch(() => []);+ if (rows.length) {+ send({+ type: 'activity',+ actions: rows.map((r) => ({+ id: String(r.id),+ type: r.action_type || 'action',+ summary: r.summary || r.action_type || 'action',+ payload: r.payload || null,+ ts: r.created_at ? new Date(r.created_at).getTime() : now,+ })),+ ts: now,+ });+ }+ }+ } catch { /* non-critical */ }+ }++ // ── heartbeat ───────────────────────────────────────────────────+ if (heartbeatTick >= HEARTBEAT_MS) {+ heartbeatTick = 0;+ send({ type: 'heartbeat', ts: now });+ }+ }, FRAME_POLL_MS);++ req.on('close', () => { clearInterval(timer); resolve(); });+ req.on('error', () => { clearInterval(timer); resolve(); });+ });++ if (!res.writableEnded) res.end();+});diff --git a/pages/agent-screen.html b/pages/agent-screen.htmlnew file mode 100644index 000000000..2cecb320c--- /dev/null+++ b/pages/agent-screen.html@@ -0,0 +1,429 @@+<!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" />+ <title>Agent Screen · three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="theme-color" content="#060a12" />+ <meta name="description" content="Watch your agent in real time — see their screen and avatar as they autonomously trade, browse, and act." />++ <meta property="og:type" content="website" />+ <meta property="og:url" content="https://three.ws/agent-screen" />+ <meta property="og:title" content="Agent Screen · three.ws" />+ <meta property="og:description" content="Watch your agent work — live screen and avatar feed." />+ <meta property="og:image" content="https://three.ws/og-image.png" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:image" content="https://three.ws/og-image.png" />++ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />++ <style>+ :root {+ --screen-accent: #5b8fff;+ --screen-live: #3ddc84;+ --screen-dark: rgba(255,255,255,0.3);+ }++ body {+ overflow: hidden;+ display: flex;+ flex-direction: column;+ min-height: 100vh;+ background: #060a12;+ }++ /* ── header ── */+ .asc-header {+ display: flex;+ align-items: center;+ gap: 0.9rem;+ padding: 0.6rem 1rem;+ border-bottom: 1px solid rgba(255,255,255,0.07);+ background: rgba(6, 10, 18, 0.95);+ backdrop-filter: blur(12px);+ flex: none;+ z-index: 30;+ }+ .asc-header .back {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+ color: rgba(255,255,255,0.6);+ text-decoration: none;+ font-size: 0.82rem;+ font-weight: 600;+ padding: 0.3rem 0.55rem;+ border-radius: 7px;+ transition: background 0.15s, color 0.15s;+ }+ .asc-header .back:hover { color: #fff; background: rgba(255,255,255,0.07); }+ .asc-agent-info { display: flex; align-items: center; gap: 0.65rem; }+ .asc-agent-name {+ font-size: 0.95rem;+ font-weight: 680;+ color: #eef2fa;+ letter-spacing: -0.01em;+ }+ .asc-live-badge {+ display: inline-flex;+ align-items: center;+ gap: 0.35rem;+ background: rgba(61,220,132,0.12);+ color: var(--screen-live);+ font-size: 0.72rem;+ font-weight: 700;+ letter-spacing: 0.07em;+ text-transform: uppercase;+ padding: 0.25rem 0.6rem;+ border-radius: 999px;+ border: 1px solid rgba(61,220,132,0.25);+ }+ .asc-live-badge .dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--screen-live);+ animation: asc-pulse 1.4s ease-in-out infinite;+ }+ .asc-live-badge.dark {+ background: rgba(255,255,255,0.06);+ color: var(--screen-dark);+ border-color: rgba(255,255,255,0.1);+ }+ .asc-live-badge.dark .dot {+ background: var(--screen-dark);+ animation: none;+ }+ .asc-header-right {+ margin-left: auto;+ display: flex;+ align-items: center;+ gap: 0.6rem;+ }+ .asc-btn {+ appearance: none;+ background: rgba(255,255,255,0.07);+ border: 1px solid rgba(255,255,255,0.12);+ color: rgba(255,255,255,0.75);+ border-radius: 8px;+ padding: 0.35rem 0.75rem;+ font: inherit;+ font-size: 0.8rem;+ cursor: pointer;+ transition: background 0.15s, color 0.15s;+ }+ .asc-btn:hover { background: rgba(255,255,255,0.12); color: #fff; }++ /* ── main layout ── */+ .asc-main {+ flex: 1;+ min-height: 0;+ display: flex;+ overflow: hidden;+ }++ /* ── screen panel (left 64%) ── */+ .asc-screen-panel {+ flex: 0 0 64%;+ min-width: 0;+ display: flex;+ flex-direction: column;+ border-right: 1px solid rgba(255,255,255,0.06);+ background: #04060d;+ position: relative;+ }+ .asc-screen-label {+ padding: 0.5rem 0.9rem;+ font-size: 0.72rem;+ font-weight: 600;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: rgba(255,255,255,0.35);+ border-bottom: 1px solid rgba(255,255,255,0.05);+ flex: none;+ }+ .asc-screen-wrap {+ flex: 1;+ min-height: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ position: relative;+ overflow: hidden;+ }+ #asc-screen-canvas {+ max-width: 100%;+ max-height: 100%;+ display: block;+ border-radius: 4px;+ image-rendering: crisp-edges;+ }+ .asc-screen-overlay {+ position: absolute;+ inset: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 1rem;+ color: rgba(255,255,255,0.5);+ font-size: 0.9rem;+ pointer-events: none;+ }+ .asc-screen-overlay .pulse-ring {+ width: 56px;+ height: 56px;+ border: 2px solid rgba(91,143,255,0.35);+ border-radius: 50%;+ animation: asc-ring 2s ease-out infinite;+ position: relative;+ }+ .asc-screen-overlay .pulse-ring::after {+ content: '';+ position: absolute;+ inset: 8px;+ border-radius: 50%;+ background: rgba(91,143,255,0.12);+ animation: asc-inner 2s ease-out infinite;+ }+ .asc-screen-overlay p { margin: 0; text-align: center; }+ .asc-screen-overlay small { font-size: 0.75rem; color: rgba(255,255,255,0.3); }++ /* ── right panel ── */+ .asc-right-panel {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ background: #060a14;+ }++ /* ── webcam section ── */+ .asc-webcam-section {+ flex: 0 0 auto;+ border-bottom: 1px solid rgba(255,255,255,0.06);+ }+ .asc-webcam-label {+ padding: 0.5rem 0.9rem;+ font-size: 0.72rem;+ font-weight: 600;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: rgba(255,255,255,0.35);+ border-bottom: 1px solid rgba(255,255,255,0.05);+ }+ .asc-webcam-wrap {+ padding: 0.9rem;+ display: flex;+ justify-content: center;+ }+ .asc-webcam-bezel {+ position: relative;+ border-radius: 14px;+ overflow: hidden;+ border: 2px solid rgba(255,255,255,0.1);+ background: #0a0d1a;+ box-shadow: 0 4px 24px rgba(0,0,0,0.5), 0 0 0 1px rgba(255,255,255,0.04);+ aspect-ratio: 4/3;+ width: 100%;+ max-width: 300px;+ }+ .asc-webcam-bezel video,+ .asc-webcam-bezel canvas {+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+ }+ .asc-webcam-badge {+ position: absolute;+ top: 8px;+ left: 10px;+ display: flex;+ align-items: center;+ gap: 5px;+ background: rgba(0,0,0,0.65);+ backdrop-filter: blur(4px);+ border-radius: 6px;+ padding: 3px 8px;+ font-size: 0.7rem;+ font-weight: 600;+ color: #fff;+ }+ .asc-webcam-badge .cam-dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--screen-live);+ }+ .asc-webcam-idle {+ display: flex;+ align-items: center;+ justify-content: center;+ height: 100%;+ color: rgba(255,255,255,0.3);+ font-size: 0.82rem;+ }++ /* ── activity log ── */+ .asc-log-section { flex: 1; min-height: 0; display: flex; flex-direction: column; }+ .asc-log-label {+ padding: 0.5rem 0.9rem;+ font-size: 0.72rem;+ font-weight: 600;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: rgba(255,255,255,0.35);+ border-bottom: 1px solid rgba(255,255,255,0.05);+ flex: none;+ }+ #asc-log {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ padding: 0.6rem 0;+ display: flex;+ flex-direction: column-reverse;+ scrollbar-width: thin;+ scrollbar-color: rgba(255,255,255,0.1) transparent;+ }+ .asc-log-entry {+ display: flex;+ align-items: flex-start;+ gap: 0.55rem;+ padding: 0.4rem 0.9rem;+ font-size: 0.8rem;+ line-height: 1.4;+ border-bottom: 1px solid rgba(255,255,255,0.03);+ animation: asc-fadein 0.25s ease;+ }+ .asc-log-entry:first-child { border-bottom: none; }+ .asc-log-time { color: rgba(255,255,255,0.28); font-size: 0.72rem; flex: none; padding-top: 1px; }+ .asc-log-type {+ flex: none;+ font-size: 0.68rem;+ font-weight: 700;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ padding: 1px 6px;+ border-radius: 4px;+ }+ .asc-log-type.screenshot { background: rgba(91,143,255,0.15); color: #7aaeff; }+ .asc-log-type.trade { background: rgba(61,220,132,0.15); color: #4ddd96; }+ .asc-log-type.analysis { background: rgba(255,192,80,0.15); color: #ffc85a; }+ .asc-log-type.activity { background: rgba(255,255,255,0.07); color: rgba(255,255,255,0.5); }+ .asc-log-text { color: rgba(255,255,255,0.78); }+ .asc-log-empty {+ display: flex;+ align-items: center;+ justify-content: center;+ height: 80px;+ color: rgba(255,255,255,0.2);+ font-size: 0.82rem;+ }++ /* ── current activity bar ── */+ .asc-activity-bar {+ padding: 0.55rem 0.9rem;+ background: rgba(255,255,255,0.03);+ border-top: 1px solid rgba(255,255,255,0.06);+ font-size: 0.82rem;+ color: rgba(255,255,255,0.6);+ display: flex;+ align-items: center;+ gap: 0.5rem;+ min-height: 38px;+ flex: none;+ }+ .asc-activity-icon { font-size: 0.9rem; flex: none; }+ #asc-current-activity { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }++ /* ── no-agent state ── */+ .asc-no-agent {+ flex: 1;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 1.2rem;+ text-align: center;+ padding: 2rem;+ color: #e8edf7;+ font-family: system-ui, sans-serif;+ }+ .asc-no-agent h2 { margin: 0; font-size: 1.15rem; font-weight: 680; color: #c8d4f0; }+ .asc-no-agent p { margin: 0; font-size: 0.88rem; color: rgba(255,255,255,0.45); max-width: 340px; }+ .asc-no-agent a {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+ background: linear-gradient(135deg, #4a7fff, #8260ff);+ color: #fff;+ border-radius: 9px;+ padding: 0.55rem 1.1rem;+ font-weight: 650;+ font-size: 0.88rem;+ text-decoration: none;+ transition: opacity 0.15s;+ }+ .asc-no-agent a:hover { opacity: 0.88; }++ /* ── animations ── */+ @keyframes asc-pulse { 0%,100%{opacity:1}50%{opacity:0.35} }+ @keyframes asc-ring { 0%{transform:scale(1);opacity:0.8}100%{transform:scale(1.6);opacity:0} }+ @keyframes asc-inner { 0%{opacity:0.5}100%{opacity:0} }+ @keyframes asc-fadein { from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:none} }++ /* ── fullscreen mode ── */+ .asc-screen-panel:fullscreen { background: #000; }+ .asc-screen-panel:fullscreen .asc-screen-label { display: none; }+ .asc-screen-panel:fullscreen .asc-screen-wrap { align-items: stretch; }+ .asc-screen-panel:fullscreen #asc-screen-canvas { max-height: 100%; border-radius: 0; }++ /* ── responsive ── */+ @media (max-width: 700px) {+ .asc-main { flex-direction: column; }+ .asc-screen-panel { flex: 0 0 55vh; border-right: none; border-bottom: 1px solid rgba(255,255,255,0.06); }+ .asc-right-panel { flex: 1; }+ .asc-webcam-wrap { padding: 0.6rem; }+ .asc-webcam-bezel { max-width: 180px; }+ }+ </style>+ </head>+ <body>+ <script src="/nav.js"></script>++ <header class="asc-header">+ <a class="back" id="asc-back" href="/agents">← Agents</a>+ <div class="asc-agent-info">+ <span class="asc-agent-name" id="asc-agent-name">Loading…</span>+ <span class="asc-live-badge dark" id="asc-live-badge">+ <span class="dot"></span>+ <span id="asc-badge-text">Connecting</span>+ </span>+ </div>+ <div class="asc-header-right">+ <button class="asc-btn" id="asc-fullscreen-btn" title="Fullscreen screen view">⛶ Fullscreen</button>+ <a class="asc-btn" id="asc-agent-link" href="/agents" style="text-decoration:none">View Agent →</a>+ </div>+ </header>++ <div class="asc-main" id="asc-main">+ <!-- populated by agent-screen.js -->+ <div id="asc-no-agent" class="asc-no-agent" style="display:flex">+ <h2>No agent selected</h2>+ <p>Open this page from an agent's profile to watch them work in real time.</p>+ <a href="/agents">Browse agents →</a>+ </div>+ </div>++ <script type="module" src="/src/agent-screen.js"></script>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/pages/dashboard-next/watch.html b/pages/dashboard-next/watch.htmlnew file mode 100644index 000000000..aef2a467d--- /dev/null+++ b/pages/dashboard-next/watch.html@@ -0,0 +1,74 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Watch · Agent · three.ws</title>+ <meta name="robots" content="noindex" />+ <link rel="icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/dashboard-next/shell.css" />+ <style>+ /* Override shell max-width for the watch view — screen needs room */+ .dn-content { max-width: 1200px !important; }+ .watch-header {+ display: flex;+ align-items: center;+ gap: 12px;+ margin-bottom: 20px;+ }+ .watch-header-avatar {+ width: 40px;+ height: 40px;+ border-radius: 50%;+ object-fit: cover;+ background: rgba(255,255,255,0.06);+ border: 1px solid rgba(255,255,255,0.1);+ flex-shrink: 0;+ }+ .watch-header-name {+ font-size: 18px;+ font-weight: 700;+ color: var(--ink, #f0f0f4);+ }+ .watch-header-sub {+ font-size: 13px;+ color: var(--ink-dim, #888);+ margin-top: 1px;+ }+ .watch-header-back {+ margin-left: auto;+ font-size: 13px;+ color: var(--ink-dim, #888);+ text-decoration: none;+ padding: 6px 12px;+ border-radius: 6px;+ border: 1px solid rgba(255,255,255,0.08);+ transition: background 0.15s, color 0.15s;+ }+ .watch-header-back:hover {+ background: rgba(255,255,255,0.06);+ color: var(--ink, #f0f0f4);+ }+ #watch-mount { width: 100%; }+ .watch-loading {+ display: flex;+ align-items: center;+ justify-content: center;+ min-height: 320px;+ color: var(--ink-dim, #888);+ font-size: 14px;+ }+ .watch-error {+ padding: 24px;+ color: var(--ink-dim, #888);+ font-size: 14px;+ text-align: center;+ }+ </style>+ </head>+ <body>+ <script src="/embed.js"></script>+ <script type="module" src="/src/dashboard-next/pages/watch.js"></script>+ </body>+</html>diff --git a/src/agent-screen.js b/src/agent-screen.jsnew file mode 100644index 000000000..e391c6263--- /dev/null+++ b/src/agent-screen.js@@ -0,0 +1,316 @@+// /agent-screen — live agent screen viewer.+//+// URL: /agent-screen?agentId=<uuid>+//+// Two surfaces, one SSE stream:+// Left (64%) — "Screen": renders the agent's latest screenshot frames onto+// a canvas. Scales to fit, letterboxed. Fullscreen button for+// focus mode. Shows a pulsing "waiting" overlay while dark.+//+// Right (36%) — "Webcam": an offscreen Three.js renderer pointed at the+// agent's avatar head → captureStream() → <video> with a+// camera-feed bezel. Gives the agent presence — you're not+// just watching a screen, you're watching someone work.+//+// Bottom-right — Activity log: scrolling list of what the agent narrated+// with each push.++import {+ PerspectiveCamera,+ WebGLRenderer,+ Scene,+ AmbientLight,+ DirectionalLight,+ Vector3,+ Box3,+} from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';+import { AnimationManager } from './animation-manager.js';+import { glbCanonicalize } from './glb-canonicalize.js';+import { createAgentScreenClient } from './shared/agent-screen-client.js';+import { agentAvatarGlb } from './shared/agent-3d.js';++const params = new URLSearchParams(location.search);+const agentId = params.get('agentId') || '';++const noAgentEl = document.getElementById('asc-no-agent');+const mainEl = document.getElementById('asc-main');+const agentNameEl = document.getElementById('asc-agent-name');+const liveBadgeEl = document.getElementById('asc-live-badge');+const badgeTextEl = document.getElementById('asc-badge-text');+const backEl = document.getElementById('asc-back');+const agentLinkEl = document.getElementById('asc-agent-link');+const fsBtn = document.getElementById('asc-fullscreen-btn');++if (!agentId) {+ // noAgentEl already visible from HTML+} else {+ noAgentEl.style.display = 'none';+ boot(agentId);+}++async function boot(id) {+ // Build the split-view DOM+ mainEl.innerHTML = `+ <div class="asc-screen-panel" id="asc-screen-panel">+ <div class="asc-screen-label">Screen</div>+ <div class="asc-screen-wrap">+ <canvas id="asc-screen-canvas"></canvas>+ <div class="asc-screen-overlay" id="asc-screen-overlay">+ <div class="pulse-ring"></div>+ <p>Waiting for agent…</p>+ <small>The agent will appear here once it starts broadcasting</small>+ </div>+ </div>+ </div>+ <div class="asc-right-panel">+ <div class="asc-webcam-section">+ <div class="asc-webcam-label">Avatar Cam</div>+ <div class="asc-webcam-wrap">+ <div class="asc-webcam-bezel" id="asc-webcam-bezel">+ <div class="asc-webcam-idle" id="asc-webcam-idle">Loading avatar…</div>+ <div class="asc-webcam-badge" id="asc-webcam-badge" style="display:none">+ <span class="cam-dot"></span>+ <span id="asc-webcam-name">—</span>+ </div>+ </div>+ </div>+ </div>+ <div class="asc-log-section">+ <div class="asc-log-label">Activity Log</div>+ <div id="asc-log">+ <div class="asc-log-empty" id="asc-log-empty">No activity yet</div>+ </div>+ </div>+ <div class="asc-activity-bar">+ <span class="asc-activity-icon">⚡</span>+ <span id="asc-current-activity">Waiting for agent…</span>+ </div>+ </div>+ `;++ const screenCanvas = document.getElementById('asc-screen-canvas');+ const screenOverlay = document.getElementById('asc-screen-overlay');+ const screenCtx = screenCanvas.getContext('2d');+ const logEl = document.getElementById('asc-log');+ const logEmpty = document.getElementById('asc-log-empty');+ const currentActivity = document.getElementById('asc-current-activity');+ const webcamBezel = document.getElementById('asc-webcam-bezel');+ const webcamIdle = document.getElementById('asc-webcam-idle');+ const webcamBadge = document.getElementById('asc-webcam-badge');+ const webcamName = document.getElementById('asc-webcam-name');++ // ── resolve agent metadata ─────────────────────────────────────────────+ let agentName = 'Agent';+ let avatarGlbUrl = null;+ try {+ const res = await fetch(`/api/agents/${encodeURIComponent(id)}`);+ if (res.ok) {+ const j = await res.json();+ const agent = j.agent || j;+ agentName = agent.name || 'Agent';+ agentNameEl.textContent = agentName;+ document.title = `${agentName} · Agent Screen · three.ws`;+ webcamName.textContent = agentName;+ backEl.href = `/agents/${id}`;+ agentLinkEl.href = `/agents/${id}`;+ agentLinkEl.textContent = `View ${agentName} →`;+ try {+ avatarGlbUrl = await agentAvatarGlb(agent);+ } catch { /* fall through to default */ }+ }+ } catch { /* non-fatal */ }++ // ── avatar webcam ──────────────────────────────────────────────────────+ const webcamRenderer = new WebGLRenderer({ antialias: true, alpha: true });+ webcamRenderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));+ webcamRenderer.setClearColor(0x0a0d1a, 1);++ const webcamScene = new Scene();+ webcamScene.add(new AmbientLight(0xffffff, 0.7));+ const sun = new DirectionalLight(0xffffff, 1.2);+ sun.position.set(1.5, 2.5, 2);+ webcamScene.add(sun);+ const rim = new DirectionalLight(0x8090ff, 0.4);+ rim.position.set(-2, 1, -1);+ webcamScene.add(rim);++ const webcamCamera = new PerspectiveCamera(38, 4 / 3, 0.01, 20);+ webcamCamera.position.set(0, 1.62, 0.9);+ webcamCamera.lookAt(0, 1.55, 0);++ let webcamMixer = null;+ let webcamAnimManager = null;+ let webcamAvatar = null;+ let webcamRafId = null;+ let webcamStream = null;++ async function mountAvatarWebcam(glbUrl) {+ try {+ const loader = new GLTFLoader();+ const gltf = await loader.loadAsync(glbUrl || '/avatars/default.glb');+ const model = cloneSkinnedScene(gltf.scene);+ glbCanonicalize(model);++ webcamScene.add(model);+ webcamAvatar = model;++ // Frame avatar in the camera: center on head+ const box = new Box3().setFromObject(model);+ const h = box.max.y;+ webcamCamera.position.set(0, h - 0.12, 0.72);+ webcamCamera.lookAt(0, h - 0.18, 0);++ // Drive idle animation+ webcamAnimManager = new AnimationManager(model, { loop: true });+ if (gltf.animations?.length) {+ webcamMixer = webcamAnimManager.init(gltf.animations);+ webcamAnimManager.play('idle');+ }++ // Size the renderer to match the bezel+ const bw = webcamBezel.clientWidth || 300;+ const bh = Math.round(bw * 3 / 4);+ webcamRenderer.setSize(bw, bh);++ // Inject canvas into the bezel+ const canvas = webcamRenderer.domElement;+ canvas.style.cssText = 'width:100%;height:100%;object-fit:cover;border-radius:12px;';+ webcamIdle.style.display = 'none';+ webcamBezel.appendChild(canvas);+ webcamBadge.style.display = 'flex';++ // Start render loop — captureStream feeds the "live" feel+ let last = 0;+ function webcamTick(t) {+ webcamRafId = requestAnimationFrame(webcamTick);+ const dt = Math.min((t - last) / 1000, 0.1);+ last = t;+ if (webcamMixer) webcamMixer.update(dt);+ webcamRenderer.render(webcamScene, webcamCamera);+ }+ webcamRafId = requestAnimationFrame(webcamTick);+ } catch (err) {+ console.warn('[agent-screen] avatar webcam load failed:', err);+ webcamIdle.textContent = 'Avatar unavailable';+ }+ }++ if (avatarGlbUrl) {+ mountAvatarWebcam(avatarGlbUrl);+ } else {+ mountAvatarWebcam('/avatars/default.glb');+ }++ // ── screen canvas rendering ────────────────────────────────────────────+ let lastFrameImg = null;++ function renderFrame(frame) {+ if (!frame?.data) return;+ const img = new Image();+ img.onload = () => {+ screenCanvas.width = img.naturalWidth || 1280;+ screenCanvas.height = img.naturalHeight || 720;+ screenCtx.drawImage(img, 0, 0);+ lastFrameImg = img;+ };+ img.src = frame.data;+ }++ function setLive() {+ liveBadgeEl.classList.remove('dark');+ badgeTextEl.textContent = 'LIVE';+ screenOverlay.style.display = 'none';+ }++ function setDark() {+ liveBadgeEl.classList.add('dark');+ badgeTextEl.textContent = 'OFFLINE';+ screenOverlay.style.display = 'flex';+ screenOverlay.innerHTML = `+ <div class="pulse-ring" style="border-color:rgba(255,255,255,0.15)"></div>+ <p>Agent is offline</p>+ <small>Stream will resume when the agent reconnects</small>+ `;+ currentActivity.textContent = 'Agent offline';+ }++ // ── activity log ──────────────────────────────────────────────────────+ const MAX_LOG = 80;+ let logCount = 0;++ function fmtTime(ts) {+ const d = new Date(ts);+ return d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' });+ }++ function addLogEntry({ ts, activity, type }) {+ logEmpty?.remove();+ const entry = document.createElement('div');+ entry.className = 'asc-log-entry';+ const typeLabel = type || 'activity';+ entry.innerHTML = `+ <span class="asc-log-time">${fmtTime(ts || Date.now())}</span>+ <span class="asc-log-type ${typeLabel}">${typeLabel}</span>+ <span class="asc-log-text">${esc(activity || '')}</span>+ `;+ logEl.prepend(entry);+ logCount++;+ // Trim old entries+ while (logCount > MAX_LOG) {+ logEl.lastElementChild?.remove();+ logCount--;+ }+ }++ // ── SSE client ─────────────────────────────────────────────────────────+ const client = createAgentScreenClient(id, {+ onOpen({ agentName: n }) {+ if (n) { agentNameEl.textContent = n; agentName = n; webcamName.textContent = n; }+ badgeTextEl.textContent = 'Connecting…';+ },+ onFrame(frame) {+ setLive();+ if (frame.data) renderFrame(frame);+ if (frame.activity) {+ currentActivity.textContent = frame.activity;+ addLogEntry(frame);+ }+ },+ onLog(entries) {+ entries.forEach(addLogEntry);+ },+ onDark() { setDark(); },+ onError() {+ badgeTextEl.textContent = 'Reconnecting…';+ liveBadgeEl.classList.add('dark');+ },+ });++ client.connect();++ // ── fullscreen ─────────────────────────────────────────────────────────+ const screenPanel = document.getElementById('asc-screen-panel');+ fsBtn.addEventListener('click', () => {+ if (!document.fullscreenElement) {+ screenPanel.requestFullscreen?.().catch(() => {});+ } else {+ document.exitFullscreen?.().catch(() => {});+ }+ });+ document.addEventListener('fullscreenchange', () => {+ fsBtn.textContent = document.fullscreenElement ? '✕ Exit' : '⛶ Fullscreen';+ });++ // Cleanup on unload+ window.addEventListener('beforeunload', () => {+ client.disconnect();+ if (webcamRafId) cancelAnimationFrame(webcamRafId);+ webcamRenderer.dispose();+ });+}++function esc(s) {+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}diff --git a/src/dashboard-next/pages/watch.js b/src/dashboard-next/pages/watch.jsnew file mode 100644index 000000000..80246a019--- /dev/null+++ b/src/dashboard-next/pages/watch.js@@ -0,0 +1,73 @@+// Dashboard · Watch — /dashboard-next/watch?agentId=<id>+//+// Full-page "remote desktop + webcam" view for a single agent.+// Requires ?agentId= in the URL. Falls back to a graceful error when the+// agent isn't found or the viewer isn't the owner (public watch of live+// agents is allowed — the stream itself is public, but the panel is most+// useful on your own agents dashboard).++import { mountWatchPanel } from '../../shared/agent-watch-panel.js';+import { mountDashboardShell } from '../shell.js';++const params = new URLSearchParams(location.search);+const agentId = params.get('agentId');++async function init() {+ const shell = await mountDashboardShell({ title: 'Watch', activeNav: 'agents' });+ const content = shell?.content || document.body;++ if (!agentId) {+ content.innerHTML = `+<div class="watch-error">+ No agent selected.<br>+ <a href="/dashboard-next/agents.html" style="color:inherit;text-decoration:underline">+ Go to your agents →+ </a>+</div>`;+ return;+ }++ // Fetch agent meta so we can show the header.+ let agent = null;+ try {+ const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}`, { credentials: 'include' });+ if (r.ok) agent = (await r.json())?.agent || null;+ } catch { /* non-critical */ }++ if (!agent) {+ content.innerHTML = `<div class="watch-error">Agent not found or access denied.</div>`;+ return;+ }++ const avatarImg = agent.avatar_image_url || agent.avatar_url || '';+ const backHref = `/agents/${encodeURIComponent(agentId)}`;++ content.innerHTML = `+<div class="watch-header">+ ${avatarImg+ ? `<img class="watch-header-avatar" src="${avatarImg}" alt="${agent.name || 'Agent'}">`+ : `<div class="watch-header-avatar"></div>`}+ <div>+ <div class="watch-header-name">${agent.name || 'Agent'}</div>+ <div class="watch-header-sub">Live screen · ${agentId.slice(0, 8)}…</div>+ </div>+ <a class="watch-header-back" href="${backHref}">← Agent profile</a>+</div>+<div id="watch-mount"></div>`;++ const mount = document.getElementById('watch-mount');+ const avatarUrl = agent.avatar_glb_url || agent.avatar_model_url || agent.base_model_url || '';++ await mountWatchPanel({+ agentId,+ agentName: agent.name || 'Agent',+ avatarUrl,+ isOwner: !!agent.isOwner,+ container: mount,+ });+}++init().catch((err) => {+ console.error('[watch] init error', err);+ document.body.innerHTML += `<div class="watch-error">Failed to load watch view.</div>`;+});diff --git a/src/game/agent-desk.js b/src/game/agent-desk.jsnew file mode 100644index 000000000..804a6406a--- /dev/null+++ b/src/game/agent-desk.js@@ -0,0 +1,412 @@+// agent-desk — a live "working agent" desk object for the 3D world.+//+// Places a desk in the scene with:+// • A flat-screen monitor whose face is a live CanvasTexture. When the agent+// has a Playwright process pushing frames the monitor shows those verbatim.+// When no frames arrive it paints a real-time activity canvas drawn from+// /api/agent-actions — same data the 2D watch panel uses.+// • A keyboard + mouse prop on the desk surface.+// • An agent avatar seated behind the desk (idle-animated, driven by the+// same retargeting pipeline as every other avatar in the world).+// • Proximity detection: when the local player walks within NEAR_DIST units+// the monitor "wakes up" (brighter emissive, faster poll) and a HUD prompt+// appears offering to open the full 2D watch view.+//+// Follows chart-screen.js in every structural detail — CanvasTexture updated+// per-frame, update(dt) called from the scene loop, dispose() for cleanup.+//+// Usage:+// import { createAgentDesk } from './agent-desk.js';+// const desk = createAgentDesk(scene, { agentId, agentName, avatarUrl }, {+// position: [x, 0, z],+// rotationY: Math.PI,+// });+// // in the scene loop:+// desk.update(dt, playerPosition);+// // to open the watch panel when the player interacts:+// desk.openWatch(); // navigates to /dashboard-next/watch?agentId=…+// // cleanup:+// desk.dispose();++import {+ Group, Mesh, MeshBasicMaterial, MeshStandardMaterial,+ PlaneGeometry, BoxGeometry, CylinderGeometry,+ CanvasTexture, SRGBColorSpace, DoubleSide, Vector3,+} from 'three';++const ACTIVITY_URL = (id) =>+ `/api/agent-actions?agent_id=${encodeURIComponent(id)}&limit=12`;+const FRAME_SSE_URL = (id) =>+ `/api/agent/screen-stream?agentId=${encodeURIComponent(id)}`;++const NEAR_DIST = 8; // units — player proximity to activate+const POLL_MS = 4000; // activity poll interval (far)+const POLL_NEAR_MS = 1500; // activity poll interval (near)+const REDRAW_MS = 100; // ~10fps canvas repaint+// Canvas resolution — 16:9 to match the 2D panel.+const CW = 1280, CH = 720;++// Monitor physical dimensions (world units).+const MON_W = 3.6;+const MON_H = (MON_W * CH) / CW;++// ── canvas painting ───────────────────────────────────────────────────────────++function paintDesk(ctx, actions, status, agentName, t) {+ const text = '#f0f0f4', dim = 'rgba(255,255,255,0.35)', faint = 'rgba(255,255,255,0.12)';+ const up = '#5fd08a', bg0 = '#080809', bg1 = '#0d0d11';+ const pulse = 0.5 + 0.5 * Math.sin(t * 3);++ // Background gradient+ const bg = ctx.createLinearGradient(0, 0, 0, CH);+ bg.addColorStop(0, bg1);+ bg.addColorStop(1, bg0);+ ctx.fillStyle = bg;+ ctx.fillRect(0, 0, CW, CH);++ // Top bar+ ctx.fillStyle = 'rgba(255,255,255,0.03)';+ ctx.fillRect(0, 0, CW, 48);+ ctx.strokeStyle = 'rgba(255,255,255,0.05)';+ ctx.lineWidth = 1;+ ctx.beginPath(); ctx.moveTo(0, 48); ctx.lineTo(CW, 48); ctx.stroke();++ // Status dot + name+ ctx.beginPath();+ ctx.arc(28, 24, 6, 0, Math.PI * 2);+ ctx.fillStyle = status === 'live'+ ? `rgba(95,208,138,${0.55 + pulse * 0.45})`+ : 'rgba(120,120,128,0.5)';+ ctx.fill();++ ctx.font = '700 16px Inter, system-ui, sans-serif';+ ctx.fillStyle = text;+ ctx.textAlign = 'left';+ ctx.textBaseline = 'middle';+ const name = (agentName || 'Agent').slice(0, 30);+ ctx.fillText(name, 48, 24);+ ctx.fillStyle = status === 'live' ? up : dim;+ ctx.font = '500 13px Inter, system-ui, sans-serif';+ ctx.fillText(status === 'live' ? '· live' : '· idle', 48 + ctx.measureText(name + ' ').width, 24);++ // Clock+ const now = new Date();+ const clock = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false });+ ctx.font = '600 14px Inter, system-ui, monospace';+ ctx.fillStyle = dim;+ ctx.textAlign = 'right';+ ctx.fillText(clock, CW - 20, 24);+ ctx.textAlign = 'left';++ // Terminal window+ const pad = 28;+ const winX = pad, winY = 62, winW = CW - pad * 2, winH = CH - 62 - pad;+ const r = 8;++ ctx.fillStyle = '#0c0c10';+ ctx.beginPath();+ roundRect(ctx, winX, winY, winW, winH, r);+ ctx.fill();+ ctx.strokeStyle = 'rgba(255,255,255,0.055)';+ ctx.lineWidth = 1;+ ctx.stroke();++ // Titlebar+ const tbH = 34;+ ctx.fillStyle = 'rgba(255,255,255,0.03)';+ ctx.beginPath();+ roundRect(ctx, winX, winY, winW, tbH, [r, r, 0, 0]);+ ctx.fill();+ ctx.strokeStyle = 'rgba(255,255,255,0.05)';+ ctx.beginPath(); ctx.moveTo(winX, winY + tbH); ctx.lineTo(winX + winW, winY + tbH); ctx.stroke();++ // Traffic lights+ [['#ff5f57'], ['#febc2e'], ['#28c840']].forEach(([c], i) => {+ ctx.beginPath();+ ctx.arc(winX + 16 + i * 18, winY + tbH / 2, 5, 0, Math.PI * 2);+ ctx.fillStyle = c;+ ctx.fill();+ });++ // Title+ ctx.font = '500 12px Inter, system-ui, sans-serif';+ ctx.fillStyle = faint;+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';+ ctx.fillText(`${name} — live activity`, winX + winW / 2, winY + tbH / 2);+ ctx.textAlign = 'left';++ // Lines+ const lH = 32;+ const cX = winX + 20;+ let lY = winY + tbH + 24;+ const maxL = Math.floor((winH - tbH - 50) / lH);++ if (!actions.length) {+ ctx.font = '500 14px "Courier New", monospace';+ ctx.fillStyle = faint;+ ctx.textBaseline = 'alphabetic';+ ctx.fillText('> Waiting for agent activity…', cX, lY);+ if (Math.sin(t * 4) > 0) {+ ctx.fillStyle = faint;+ ctx.fillRect(cX + ctx.measureText('> Waiting for agent activity…').width + 3, lY - 14, 8, 16);+ }+ } else {+ actions.slice(0, maxL).forEach((a, i) => {+ const latest = i === 0;+ const age = Math.max(0, Math.round((Date.now() - (a.ts || Date.now())) / 1000));+ const ts = age < 5 ? 'now' : age < 60 ? `${age}s` : `${Math.round(age / 60)}m`;++ ctx.textBaseline = 'alphabetic';+ ctx.font = '600 12px "Courier New", monospace';+ ctx.fillStyle = latest ? up : 'rgba(255,255,255,0.18)';+ const prefix = ` [${ts}] `;+ ctx.fillText(prefix, cX, lY + i * lH);+ const pw = ctx.measureText(prefix).width;++ ctx.font = `${latest ? '600' : '400'} 13px "Courier New", monospace`;+ ctx.fillStyle = latest ? text : dim;+ const summary = (a.summary || a.type || 'action').slice(0, 88);+ ctx.fillText(summary, cX + pw, lY + i * lH);++ if (latest && Math.sin(t * 4) > 0) {+ const tw = pw + ctx.measureText(summary).width;+ ctx.fillStyle = up;+ ctx.fillRect(cX + tw + 3, lY + i * lH - 13, 7, 14);+ }+ });+ }++ // Status bar+ const sbY = winY + winH - 24;+ ctx.fillStyle = 'rgba(95,208,138,0.06)';+ ctx.fillRect(winX + 1, sbY, winW - 2, 23);+ ctx.strokeStyle = 'rgba(255,255,255,0.04)';+ ctx.beginPath(); ctx.moveTo(winX, sbY); ctx.lineTo(winX + winW, sbY); ctx.stroke();+ ctx.font = '500 11px Inter, system-ui, sans-serif';+ ctx.textBaseline = 'middle';+ ctx.fillStyle = 'rgba(95,208,138,0.6)';+ ctx.fillText(`three.ws · ${actions.length || 0} actions`, cX, sbY + 12);+ ctx.textAlign = 'right';+ ctx.fillStyle = faint;+ ctx.fillText('walk up · press E to watch', winX + winW - 10, sbY + 12);+ ctx.textAlign = 'left';++ tex.needsUpdate = true; // eslint-disable-line no-use-before-define+}++let tex; // assigned after canvas is created so paintDesk can reference it++function roundRect(ctx, x, y, w, h, r) {+ const tl = Array.isArray(r) ? r[0] : r;+ const tr = Array.isArray(r) ? r[1] : r;+ const br = Array.isArray(r) ? r[2] : r;+ const bl = Array.isArray(r) ? r[3] : r;+ ctx.beginPath();+ ctx.moveTo(x + tl, y);+ ctx.arcTo(x + w, y, x + w, y + h, tr);+ ctx.arcTo(x + w, y + h, x, y + h, br);+ ctx.arcTo(x, y + h, x, y, bl);+ ctx.arcTo(x, y, x + w, y, tl);+ ctx.closePath();+}++// ── factory ───────────────────────────────────────────────────────────────────++/**+ * Create an agent desk and add it to the scene.+ *+ * @param {THREE.Scene} scene+ * @param {{ agentId:string, agentName:string, avatarUrl?:string }} agent+ * @param {{ position?:[number,number,number], rotationY?:number }} [opts]+ * @returns {{ group:THREE.Group, update(dt:number, playerPos?:THREE.Vector3):void, openWatch():void, dispose():void }}+ */+export function createAgentDesk(scene, agent, opts = {}) {+ const position = opts.position || [0, 0, 0];+ const rotationY = opts.rotationY || 0;++ const group = new Group();+ group.position.set(...position);+ group.rotation.y = rotationY;++ const metalMat = new MeshStandardMaterial({ color: 0x1a1a1f, roughness: 0.4, metalness: 0.7 });+ const darkMat = new MeshStandardMaterial({ color: 0x101012, roughness: 0.6, metalness: 0.3 });+ const woodMat = new MeshStandardMaterial({ color: 0x2a1f14, roughness: 0.8, metalness: 0.0 });++ // ── Desk surface ────────────────────────────────────────────────────────+ const deskW = 4.8, deskD = 2.0, deskH = 0.08;+ const deskY = 0.78; // standard desk height+ const deskTop = new Mesh(new BoxGeometry(deskW, deskH, deskD), woodMat);+ deskTop.position.set(0, deskY, 0);+ deskTop.castShadow = true; deskTop.receiveShadow = true;+ group.add(deskTop);++ // Desk legs (4)+ for (const [sx, sz] of [[-1, -1], [1, -1], [-1, 1], [1, 1]]) {+ const leg = new Mesh(new BoxGeometry(0.08, deskY, 0.08), metalMat);+ leg.position.set(sx * (deskW / 2 - 0.15), deskY / 2, sz * (deskD / 2 - 0.15));+ leg.castShadow = true;+ group.add(leg);+ }++ // ── Monitor stand ───────────────────────────────────────────────────────+ const standH = 0.55;+ const stand = new Mesh(new CylinderGeometry(0.04, 0.08, standH, 12), metalMat);+ stand.position.set(0, deskY + deskH / 2 + standH / 2, -0.35);+ stand.castShadow = true;+ group.add(stand);++ // Monitor base plate+ const base = new Mesh(new BoxGeometry(0.6, 0.02, 0.3), metalMat);+ base.position.set(0, deskY + deskH / 2 + 0.01, -0.35);+ base.castShadow = true; base.receiveShadow = true;+ group.add(base);++ // Monitor bezel+ const bezelMat = new MeshStandardMaterial({ color: 0x080809, roughness: 0.3, metalness: 0.8 });+ const bezel = new Mesh(+ new BoxGeometry(MON_W + 0.22, MON_H + 0.22, 0.12),+ bezelMat,+ );+ const monCY = deskY + deskH / 2 + standH + MON_H / 2 + 0.02;+ bezel.position.set(0, monCY, -0.35);+ bezel.castShadow = true;+ group.add(bezel);++ // ── Live screen face ────────────────────────────────────────────────────+ const canvas = document.createElement('canvas');+ canvas.width = CW; canvas.height = CH;+ const ctx = canvas.getContext('2d');+ tex = new CanvasTexture(canvas);+ tex.colorSpace = SRGBColorSpace;+ tex.anisotropy = 8;++ const screenMat = new MeshBasicMaterial({ map: tex, toneMapped: false });+ const screen = new Mesh(new PlaneGeometry(MON_W, MON_H), screenMat);+ screen.position.set(0, monCY, -0.35 + 0.07);+ screen.userData.agentDesk = true;+ group.add(screen);++ // ── Keyboard ────────────────────────────────────────────────────────────+ const kb = new Mesh(new BoxGeometry(1.2, 0.03, 0.36), darkMat);+ kb.position.set(0, deskY + deskH / 2 + 0.015, 0.3);+ kb.castShadow = true; kb.receiveShadow = true;+ group.add(kb);++ // ── Mouse ───────────────────────────────────────────────────────────────+ const mouse = new Mesh(new BoxGeometry(0.1, 0.025, 0.15), darkMat);+ mouse.position.set(0.75, deskY + deskH / 2 + 0.012, 0.32);+ mouse.castShadow = true; mouse.receiveShadow = true;+ group.add(mouse);++ scene.add(group);++ // ── Live state ───────────────────────────────────────────────────────────+ let actions = [];+ let frameImg = null; // latest pushed frame as an Image, or null+ let status = 'idle';+ let destroyed = false;+ let near = false;+ let pollTimer = null;+ let acc = 0;+ let t = 0;+ let es = null;++ // Initial paint so the screen isn't blank before the first fetch.+ paintDesk(ctx, [], 'idle', agent.agentName || 'Agent', 0);++ function connectSSE() {+ if (es) { try { es.close(); } catch { /* */ } }+ es = new EventSource(FRAME_SSE_URL(agent.agentId));+ es.onmessage = (e) => {+ let msg;+ try { msg = JSON.parse(e.data); } catch { return; }+ if (msg.type === 'frame') {+ const img = new Image();+ img.onload = () => { frameImg = img; };+ img.src = 'data:image/png;base64,' + msg.frame;+ status = 'live';+ }+ if (msg.type === 'activity') {+ actions = msg.actions || [];+ }+ };+ es.onerror = () => { status = 'idle'; };+ }++ async function fetchActivity() {+ if (destroyed) return;+ try {+ const r = await fetch(ACTIVITY_URL(agent.agentId));+ if (r.ok) {+ const d = await r.json();+ const rows = d?.data?.actions || d?.actions || [];+ if (rows.length) actions = rows;+ }+ } catch { /* non-critical */ }+ if (!destroyed) {+ const delay = near ? POLL_NEAR_MS : POLL_MS;+ pollTimer = setTimeout(fetchActivity, delay);+ }+ }++ connectSSE();+ fetchActivity();++ // ── public API ────────────────────────────────────────────────────────────+ return {+ group,+ screen,+ agentId: agent.agentId,++ update(dt, playerPos) {+ if (destroyed) return;+ t += dt;+ acc += dt;++ // Proximity check — brighten screen when player is near.+ if (playerPos) {+ const deskWorldPos = new Vector3();+ group.getWorldPosition(deskWorldPos);+ const dist = playerPos.distanceTo(deskWorldPos);+ const wasNear = near;+ near = dist < NEAR_DIST;+ if (near !== wasNear) {+ // Swap poll frequency.+ clearTimeout(pollTimer);+ fetchActivity();+ // Screen emissive boost.+ screenMat.opacity = near ? 1.0 : 0.92;+ }+ }++ if (acc < REDRAW_MS / 1000) return;+ acc = 0;++ if (frameImg && status === 'live') {+ ctx.drawImage(frameImg, 0, 0, CW, CH);+ tex.needsUpdate = true;+ } else {+ paintDesk(ctx, actions, status, agent.agentName || 'Agent', t);+ }+ },++ openWatch() {+ const url = `/dashboard-next/watch?agentId=${encodeURIComponent(agent.agentId)}`;+ window.open(url, '_blank');+ },++ dispose() {+ destroyed = true;+ clearTimeout(pollTimer);+ try { es?.close(); } catch { /* */ }+ scene.remove(group);+ group.traverse((n) => {+ if (!n.isMesh) return;+ n.geometry?.dispose?.();+ const mats = Array.isArray(n.material) ? n.material : [n.material];+ for (const m of mats) { m?.map?.dispose?.(); m?.dispose?.(); }+ });+ },+ };+}diff --git a/src/shared/agent-screen-client.js b/src/shared/agent-screen-client.jsnew file mode 100644index 000000000..4ea18aeea--- /dev/null+++ b/src/shared/agent-screen-client.js@@ -0,0 +1,104 @@+// agent-screen-client.js — SSE client for the agent screen stream.+//+// Manages the EventSource connection to /api/agent-screen-stream, handles+// reconnection with backoff, and exposes a clean event interface so the+// 2D dashboard and 3D walk desk can both subscribe without duplicating logic.+//+// Usage:+// const client = createAgentScreenClient(agentId, {+// onFrame(frame) — called with { ts, data?, activity, type, agentId }+// onLog(entries) — called with [{ ts, activity, type }] (backfill)+// onOpen(info) — called with { agentId, agentName }+// onDark() — called when the agent's stream goes dark+// onError(err) — called on connection error (non-fatal, will retry)+// });+// client.connect();+// client.disconnect();+// client.isConnected() → boolean++const STREAM_URL = (agentId) => `/api/agent-screen-stream?agentId=${encodeURIComponent(agentId)}`;+const RECONNECT_DELAYS = [500, 1000, 2000, 5000, 10000]; // ms++export function createAgentScreenClient(agentId, handlers = {}) {+ const { onFrame, onLog, onOpen, onDark, onError } = handlers;++ let es = null;+ let reconnectTimer = null;+ let reconnectAttempt = 0;+ let destroyed = false;+ let connected = false;++ function connect() {+ if (destroyed || es) return;+ es = new EventSource(STREAM_URL(agentId));++ es.addEventListener('open', () => {+ reconnectAttempt = 0;+ connected = true;+ });++ es.addEventListener('frame', (e) => {+ try {+ const frame = JSON.parse(e.data);+ onFrame?.(frame);+ } catch { /* malformed event */ }+ });++ es.addEventListener('log', (e) => {+ try {+ const { entries } = JSON.parse(e.data);+ onLog?.(entries || []);+ } catch { /* malformed event */ }+ });++ es.addEventListener('open-info', (e) => {+ // Note: 'open' is a native EventSource event; we use 'open-info' for our+ // custom payload but the SSE sends event: open — handle both.+ try {+ onOpen?.(JSON.parse(e.data));+ } catch { /* malformed event */ }+ });++ // The SSE spec fires 'open' for the HTTP connection; we name our custom+ // open-metadata event 'open' in the stream. EventSource conflates them, so+ // we listen on the 'message' handler for untyped events and on named event+ // listeners for typed ones. The server sends `event: open` for our custom+ // metadata — this will NOT fire the native 'open' listener, it fires the+ // named 'open' listener below.+ es.addEventListener('open', (e) => {+ if (e.data) {+ try { onOpen?.(JSON.parse(e.data)); } catch { /* ok */ }+ }+ });++ es.addEventListener('dark', () => {+ onDark?.();+ });++ es.addEventListener('ping', () => {+ // keepalive — no action needed+ });++ es.onerror = () => {+ connected = false;+ es?.close();+ es = null;+ if (destroyed) return;+ onError?.(new Error('stream disconnected'));+ const delay = RECONNECT_DELAYS[Math.min(reconnectAttempt, RECONNECT_DELAYS.length - 1)];+ reconnectAttempt++;+ reconnectTimer = setTimeout(connect, delay);+ };+ }++ function disconnect() {+ destroyed = true;+ connected = false;+ if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }+ if (es) { es.close(); es = null; }+ }++ function isConnected() { return connected && !destroyed; }++ return { connect, disconnect, isConnected };+}diff --git a/src/shared/agent-watch-panel.js b/src/shared/agent-watch-panel.jsnew file mode 100644index 000000000..fdd01ea74--- /dev/null+++ b/src/shared/agent-watch-panel.js@@ -0,0 +1,773 @@+// agent-watch-panel — live "remote desktop + webcam" view for any agent.+//+// Two surfaces in one component:+// Screen — left/main pane. When the agent has a Playwright process pushing+// frames via POST /api/agent/screen-push, renders them at the raw+// resolution. When no frames are coming, paints a "desktop" canvas+// from real agent-actions rows: task log, recent actions, live+// status indicator — so the screen is never blank.+// Webcam — right/inset pane. The agent's 3D GLB avatar rendered into an+// offscreen Three.js canvas, zoomed on the face, piped into a+// <video> element via captureStream(). Webcam bezel overlay.+//+// Usage (same pattern as mountStagePanel / mountLaborPanel):+// const handle = await mountWatchPanel({ agentId, agentName, avatarUrl, isOwner, container });+// // later:+// handle?.destroy();+//+// The panel is entirely self-contained: it manages its own SSE connection,+// Three.js renderer, timers, and styles. Disposing cleans up everything.++import { Viewer } from '../viewer.js';+import { IdleAnimation } from '../idle-animation.js';++const STREAM_URL = (id) => `/api/agent/screen-stream?agentId=${encodeURIComponent(id)}`;+const ACTIONS_URL = (id) => `/api/agent-actions?agent_id=${encodeURIComponent(id)}&limit=20`;++// Canvas dimensions for the activity screen (no frames mode).+const CW = 1280, CH = 720;++const STYLE_ID = 'tws-watch-panel-styles';++function injectStyles() {+ if (document.getElementById(STYLE_ID)) return;+ const s = document.createElement('style');+ s.id = STYLE_ID;+ s.textContent = `+.wp-root {+ display: flex;+ flex-direction: column;+ gap: 12px;+ width: 100%;+ font-family: var(--font-sans, 'Inter', system-ui, sans-serif);+}+.wp-stage {+ display: grid;+ grid-template-columns: 1fr 240px;+ gap: 12px;+ align-items: start;+}+@media (max-width: 700px) {+ .wp-stage { grid-template-columns: 1fr; }+}++/* ── Screen pane ───────────────────────────────────────────── */+.wp-screen-wrap {+ position: relative;+ width: 100%;+ aspect-ratio: 16/9;+ background: #09090c;+ border-radius: 10px;+ overflow: hidden;+ border: 1px solid rgba(255,255,255,0.07);+ box-shadow: 0 0 0 1px rgba(0,0,0,0.5), 0 8px 32px rgba(0,0,0,0.6);+}+.wp-screen-bezel {+ position: absolute;+ inset: 0;+ pointer-events: none;+ z-index: 3;+ border-radius: 10px;+ box-shadow: inset 0 0 0 1.5px rgba(255,255,255,0.06),+ inset 0 1px 0 rgba(255,255,255,0.04);+}+.wp-screen-canvas {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ display: block;+ object-fit: contain;+ border-radius: 9px;+}+.wp-screen-badge {+ position: absolute;+ top: 10px;+ left: 12px;+ z-index: 4;+ display: flex;+ align-items: center;+ gap: 6px;+ background: rgba(0,0,0,0.55);+ backdrop-filter: blur(8px);+ -webkit-backdrop-filter: blur(8px);+ border: 1px solid rgba(255,255,255,0.08);+ border-radius: 20px;+ padding: 4px 10px 4px 8px;+ font-size: 11px;+ font-weight: 700;+ color: rgba(255,255,255,0.75);+ letter-spacing: 0.04em;+ text-transform: uppercase;+}+.wp-screen-badge-dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: #5fd08a;+ animation: wp-pulse 2s ease-in-out infinite;+}+.wp-screen-badge-dot.offline { background: #666; animation: none; }+@keyframes wp-pulse {+ 0%,100% { opacity: 1; transform: scale(1); }+ 50% { opacity: 0.4; transform: scale(0.7); }+}+.wp-screen-expand {+ position: absolute;+ bottom: 10px;+ right: 12px;+ z-index: 4;+ background: rgba(0,0,0,0.5);+ backdrop-filter: blur(8px);+ -webkit-backdrop-filter: blur(8px);+ border: 1px solid rgba(255,255,255,0.1);+ border-radius: 6px;+ color: rgba(255,255,255,0.6);+ font-size: 12px;+ padding: 4px 8px;+ cursor: pointer;+ transition: background 0.15s, color 0.15s;+}+.wp-screen-expand:hover { background: rgba(255,255,255,0.12); color: #fff; }++/* ── Webcam pane ────────────────────────────────────────────── */+.wp-cam-wrap {+ position: relative;+ width: 100%;+ aspect-ratio: 3/4;+ background: #0d0d10;+ border-radius: 10px;+ overflow: hidden;+ border: 1px solid rgba(255,255,255,0.07);+ box-shadow: 0 0 0 1px rgba(0,0,0,0.5), 0 4px 16px rgba(0,0,0,0.5);+}+.wp-cam-canvas {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ display: block;+ object-fit: cover;+}+.wp-cam-video {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ display: block;+ object-fit: cover;+}+.wp-cam-bezel {+ position: absolute;+ inset: 0;+ pointer-events: none;+ z-index: 2;+ border-radius: 10px;+ /* Webcam vignette + scanlines effect */+ background: radial-gradient(ellipse at center, transparent 55%, rgba(0,0,0,0.55) 100%);+ box-shadow: inset 0 0 0 1.5px rgba(255,255,255,0.05);+}+.wp-cam-bezel::after {+ content: '';+ position: absolute;+ inset: 0;+ background: repeating-linear-gradient(+ 0deg,+ transparent,+ transparent 2px,+ rgba(0,0,0,0.04) 2px,+ rgba(0,0,0,0.04) 4px+ );+ pointer-events: none;+}+.wp-cam-label {+ position: absolute;+ bottom: 8px;+ left: 10px;+ z-index: 3;+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: rgba(255,255,255,0.5);+}+.wp-cam-corner {+ position: absolute;+ top: 8px;+ right: 8px;+ z-index: 3;+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: rgba(95,208,138,0.8);+ box-shadow: 0 0 6px rgba(95,208,138,0.5);+}++/* ── Activity log ───────────────────────────────────────────── */+.wp-log {+ width: 100%;+ background: rgba(255,255,255,0.02);+ border: 1px solid rgba(255,255,255,0.06);+ border-radius: 8px;+ overflow: hidden;+}+.wp-log-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 8px 14px;+ border-bottom: 1px solid rgba(255,255,255,0.05);+ font-size: 11px;+ font-weight: 700;+ letter-spacing: 0.05em;+ text-transform: uppercase;+ color: rgba(255,255,255,0.4);+}+.wp-log-list {+ max-height: 180px;+ overflow-y: auto;+ scrollbar-width: thin;+ scrollbar-color: rgba(255,255,255,0.1) transparent;+}+.wp-log-row {+ display: flex;+ align-items: flex-start;+ gap: 10px;+ padding: 7px 14px;+ border-bottom: 1px solid rgba(255,255,255,0.03);+ transition: background 0.1s;+}+.wp-log-row:last-child { border-bottom: none; }+.wp-log-row:hover { background: rgba(255,255,255,0.03); }+.wp-log-type {+ flex-shrink: 0;+ font-size: 9px;+ font-weight: 800;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: rgba(255,255,255,0.28);+ padding-top: 2px;+ min-width: 56px;+}+.wp-log-summary {+ flex: 1;+ font-size: 12px;+ color: rgba(255,255,255,0.7);+ line-height: 1.4;+}+.wp-log-time {+ flex-shrink: 0;+ font-size: 11px;+ color: rgba(255,255,255,0.25);+ padding-top: 2px;+}+.wp-log-empty {+ padding: 18px 14px;+ font-size: 12px;+ color: rgba(255,255,255,0.3);+ text-align: center;+}+`;+ document.head.appendChild(s);+}++// ── helpers ───────────────────────────────────────────────────────────────────++const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({+ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''',+}[c]));++function relTime(ts) {+ const s = Math.max(0, Math.round((Date.now() - ts) / 1000));+ if (s < 5) return 'now';+ if (s < 60) return `${s}s`;+ const m = Math.round(s / 60);+ if (m < 60) return `${m}m`;+ return `${Math.round(m / 60)}h`;+}++// ── activity desktop canvas (no-frame fallback) ───────────────────────────────++function paintActivityCanvas(ctx, actions, status, agentName, t) {+ const W = CW, H = CH;+ const up = '#5fd08a', dim = 'rgba(255,255,255,0.35)', faint = 'rgba(255,255,255,0.15)';+ const text = '#f0f0f4', bg0 = '#0a0a0e', bg1 = '#101014';++ // Background+ const bg = ctx.createLinearGradient(0, 0, 0, H);+ bg.addColorStop(0, bg1);+ bg.addColorStop(1, bg0);+ ctx.fillStyle = bg;+ ctx.fillRect(0, 0, W, H);++ // Taskbar+ ctx.fillStyle = 'rgba(255,255,255,0.04)';+ ctx.fillRect(0, 0, W, 52);+ ctx.strokeStyle = 'rgba(255,255,255,0.06)';+ ctx.lineWidth = 1;+ ctx.beginPath(); ctx.moveTo(0, 52); ctx.lineTo(W, 52); ctx.stroke();++ // Taskbar: agent name + status dot+ const pulse = 0.5 + 0.5 * Math.sin(t * 3);+ ctx.beginPath();+ ctx.arc(32, 26, 7, 0, Math.PI * 2);+ ctx.fillStyle = status === 'live'+ ? `rgba(95,208,138,${0.5 + pulse * 0.5})`+ : 'rgba(120,120,128,0.6)';+ ctx.fill();++ ctx.font = '700 18px Inter, system-ui, sans-serif';+ ctx.fillStyle = text;+ ctx.textAlign = 'left';+ ctx.textBaseline = 'middle';+ const displayName = (agentName || 'Agent').slice(0, 28);+ ctx.fillText(displayName, 54, 26);++ ctx.font = '500 15px Inter, system-ui, sans-serif';+ ctx.fillStyle = status === 'live' ? up : dim;+ const statusLabel = status === 'live' ? '● LIVE' : '○ IDLE';+ ctx.fillText(statusLabel, 54 + ctx.measureText(displayName + ' ').width, 26);++ // Taskbar right: clock+ const now = new Date();+ const clock = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false });+ ctx.font = '600 16px Inter, system-ui, monospace';+ ctx.fillStyle = dim;+ ctx.textAlign = 'right';+ ctx.fillText(clock, W - 24, 26);+ ctx.textAlign = 'left';++ // Terminal window+ const pad = 32;+ const winX = pad, winY = 72, winW = W - pad * 2, winH = H - 72 - pad;+ const r = 10;++ // Window shadow+ ctx.save();+ ctx.shadowColor = 'rgba(0,0,0,0.7)';+ ctx.shadowBlur = 32;+ ctx.shadowOffsetY = 8;+ ctx.fillStyle = 'rgba(0,0,0,0)';+ ctx.beginPath();+ ctx.roundRect?.(winX, winY, winW, winH, r) || fallbackRect(ctx, winX, winY, winW, winH, r);+ ctx.fill();+ ctx.restore();++ // Window background+ ctx.fillStyle = '#0d0d11';+ ctx.beginPath();+ ctx.roundRect?.(winX, winY, winW, winH, r) || fallbackRect(ctx, winX, winY, winW, winH, r);+ ctx.fill();+ ctx.strokeStyle = 'rgba(255,255,255,0.06)';+ ctx.lineWidth = 1;+ ctx.stroke();++ // Window titlebar+ const tbH = 38;+ ctx.fillStyle = 'rgba(255,255,255,0.035)';+ ctx.beginPath();+ ctx.roundRect?.(winX, winY, winW, tbH, [r, r, 0, 0]) || fallbackRect(ctx, winX, winY, winW, tbH, 0);+ ctx.fill();+ ctx.strokeStyle = 'rgba(255,255,255,0.05)';+ ctx.beginPath(); ctx.moveTo(winX, winY + tbH); ctx.lineTo(winX + winW, winY + tbH); ctx.stroke();++ // Traffic lights+ const dots = ['#ff5f57', '#febc2e', '#28c840'];+ dots.forEach((c, i) => {+ ctx.beginPath();+ ctx.arc(winX + 18 + i * 20, winY + tbH / 2, 6, 0, Math.PI * 2);+ ctx.fillStyle = c;+ ctx.fill();+ });++ // Window title+ ctx.font = '600 14px Inter, system-ui, sans-serif';+ ctx.fillStyle = dim;+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';+ ctx.fillText(`${displayName} — activity log`, winX + winW / 2, winY + tbH / 2);+ ctx.textAlign = 'left';++ // Terminal content+ const lineH = 36;+ const contentX = winX + 24;+ let lineY = winY + tbH + 28;+ const maxLines = Math.floor((winH - tbH - 56) / lineH);++ if (!actions.length) {+ ctx.font = '500 16px "Courier New", monospace';+ ctx.fillStyle = faint;+ ctx.textBaseline = 'alphabetic';+ ctx.fillText('> Waiting for agent activity…', contentX, lineY);+ // blinking cursor+ if (Math.sin(t * 4) > 0) {+ const cw = ctx.measureText('> Waiting for agent activity…').width;+ ctx.fillStyle = faint;+ ctx.fillRect(contentX + cw + 4, lineY - 16, 10, 18);+ }+ } else {+ const display = actions.slice(0, maxLines);+ display.forEach((a, i) => {+ const isLatest = i === 0;+ ctx.font = `${isLatest ? '700' : '400'} 15px "Courier New", monospace`;+ ctx.fillStyle = isLatest ? text : faint;+ ctx.textBaseline = 'alphabetic';++ // Prompt prefix+ const prefix = isLatest+ ? ` [${relTime(a.ts)}] `+ : ` [${relTime(a.ts)}] `;+ ctx.fillStyle = isLatest ? up : 'rgba(255,255,255,0.2)';+ ctx.font = '600 13px "Courier New", monospace';+ ctx.fillText(prefix, contentX, lineY + i * lineH);+ const prefixW = ctx.measureText(prefix).width;++ // Summary+ ctx.fillStyle = isLatest ? text : dim;+ ctx.font = `${isLatest ? '600' : '400'} 14px "Courier New", monospace`;+ const summary = (a.summary || a.type || 'action').slice(0, 90);+ ctx.fillText(summary, contentX + prefixW, lineY + i * lineH);++ // Latest line: blinking cursor+ if (isLatest && Math.sin(t * 4) > 0) {+ const tw = prefixW + ctx.measureText(summary).width;+ ctx.fillStyle = up;+ ctx.fillRect(contentX + tw + 4, lineY + i * lineH - 14, 8, 16);+ }+ });+ }++ // Status bar at bottom of window+ const sbY = winY + winH - 28;+ ctx.fillStyle = 'rgba(95,208,138,0.08)';+ ctx.fillRect(winX + 1, sbY, winW - 2, 27);+ ctx.strokeStyle = 'rgba(255,255,255,0.05)';+ ctx.beginPath(); ctx.moveTo(winX, sbY); ctx.lineTo(winX + winW, sbY); ctx.stroke();+ ctx.font = '600 12px Inter, system-ui, sans-serif';+ ctx.fillStyle = 'rgba(95,208,138,0.7)';+ ctx.textBaseline = 'middle';+ ctx.fillText(+ `three.ws agent · ${actions.length ? actions.length + ' actions' : 'idle'}`,+ contentX,+ sbY + 14,+ );+ ctx.textAlign = 'right';+ ctx.fillStyle = faint;+ ctx.fillText('powered by three.ws', winX + winW - 12, sbY + 14);+ ctx.textAlign = 'left';+}++function fallbackRect(ctx, x, y, w, h, r) {+ ctx.beginPath();+ ctx.moveTo(x + r, y);+ ctx.arcTo(x + w, y, x + w, y + h, r);+ ctx.arcTo(x + w, y + h, x, y + h, r);+ ctx.arcTo(x, y + h, x, y, r);+ ctx.arcTo(x, y, x + w, y, r);+ ctx.closePath();+}++// ── WatchPanel class ──────────────────────────────────────────────────────────++class WatchPanel {+ constructor(el, { agentId, agentName, avatarUrl, isOwner }) {+ this.el = el;+ this.agentId = agentId;+ this.agentName = agentName;+ this.avatarUrl = avatarUrl || '/avatars/mannequin.glb';+ this.isOwner = isOwner;++ this._es = null;+ this._destroyed = false;+ this._actions = [];+ this._lastFrame = null;+ this._streamStatus = 'connecting'; // connecting | live | idle+ this._t = 0;+ this._rafId = null;+ this._activityRaf = null;+ this._viewer = null;+ this._idleAnim = null;++ this._buildDOM();+ }++ _buildDOM() {+ this.el.innerHTML = `+<div class="wp-root">+ <div class="wp-stage">+ <div class="wp-screen-wrap" id="wp-sw">+ <canvas class="wp-screen-canvas" id="wp-canvas" width="${CW}" height="${CH}"></canvas>+ <div class="wp-screen-bezel"></div>+ <div class="wp-screen-badge">+ <div class="wp-screen-badge-dot offline" id="wp-dot"></div>+ <span id="wp-badge-label">Connecting…</span>+ </div>+ <button class="wp-screen-expand" id="wp-expand" title="Full screen">⛶</button>+ </div>+ <div class="wp-cam-wrap" id="wp-cw">+ <video class="wp-cam-video" id="wp-video" autoplay muted playsinline></video>+ <canvas class="wp-cam-canvas" id="wp-cam-canvas" style="display:none"></canvas>+ <div class="wp-cam-bezel"></div>+ <div class="wp-cam-label">${esc(this.agentName || 'Agent')}</div>+ <div class="wp-cam-corner"></div>+ </div>+ </div>+ <div class="wp-log">+ <div class="wp-log-head">+ <span>Activity log</span>+ <span id="wp-log-count" style="font-weight:400">—</span>+ </div>+ <div class="wp-log-list" id="wp-log-list">+ <div class="wp-log-empty">Loading activity…</div>+ </div>+ </div>+</div>`;++ this._canvas = this.el.querySelector('#wp-canvas');+ this._ctx = this._canvas.getContext('2d');+ this._dot = this.el.querySelector('#wp-dot');+ this._badge = this.el.querySelector('#wp-badge-label');+ this._video = this.el.querySelector('#wp-video');+ this._logList = this.el.querySelector('#wp-log-list');+ this._logCount = this.el.querySelector('#wp-log-count');++ // Expand to fullscreen+ this.el.querySelector('#wp-expand').addEventListener('click', () => {+ const wrap = this.el.querySelector('#wp-sw');+ wrap.requestFullscreen?.() || wrap.webkitRequestFullscreen?.();+ });+ }++ async start() {+ // Connect SSE stream.+ this._connectStream();++ // Boot the avatar webcam.+ await this._bootWebcam();++ // Start the activity canvas render loop.+ this._startCanvasLoop();+ }++ _connectStream() {+ if (this._es) { try { this._es.close(); } catch { /* */ } }+ const es = new EventSource(STREAM_URL(this.agentId));+ this._es = es;++ es.onmessage = (e) => {+ let msg;+ try { msg = JSON.parse(e.data); } catch { return; }++ if (msg.type === 'meta') {+ if (msg.avatarUrl && msg.avatarUrl !== this.avatarUrl) {+ this.avatarUrl = msg.avatarUrl;+ this._rebootWebcam();+ }+ }+ if (msg.type === 'frame') {+ this._renderFrame(msg.frame);+ this._setStatus('live');+ }+ if (msg.type === 'activity') {+ this._actions = msg.actions || [];+ this._renderLog();+ }+ if (msg.type === 'heartbeat') {+ if (this._streamStatus !== 'live') this._setStatus('idle');+ }+ };++ es.onerror = () => {+ this._setStatus('idle');+ // EventSource auto-reconnects; give it a moment.+ };+ }++ _setStatus(s) {+ this._streamStatus = s;+ if (s === 'live') {+ this._dot.classList.remove('offline');+ this._badge.textContent = 'Live';+ } else if (s === 'idle') {+ this._dot.classList.add('offline');+ this._badge.textContent = 'Idle';+ } else {+ this._dot.classList.add('offline');+ this._badge.textContent = 'Connecting…';+ }+ }++ _renderFrame(b64) {+ if (this._destroyed) return;+ const img = new Image();+ img.onload = () => {+ if (this._destroyed) return;+ this._ctx.drawImage(img, 0, 0, CW, CH);+ };+ img.src = 'data:image/png;base64,' + b64;+ }++ _startCanvasLoop() {+ let lastActivity = 0;+ const loop = (ts) => {+ if (this._destroyed) return;+ this._rafId = requestAnimationFrame(loop);+ this._t = ts / 1000;++ // Only repaint the activity canvas when no live frames are flowing.+ if (this._streamStatus !== 'live') {+ this._ctx.clearRect(0, 0, CW, CH);+ paintActivityCanvas(+ this._ctx,+ this._actions,+ this._streamStatus,+ this.agentName,+ this._t,+ );+ }++ // Poll DB for activity if we don't have pushed actions.+ if (!this._actions.length || Date.now() - lastActivity > 5000) {+ if (!this._fetchingActivity) {+ this._fetchingActivity = true;+ lastActivity = Date.now();+ fetch(ACTIONS_URL(this.agentId), { credentials: 'include' })+ .then((r) => r.ok ? r.json() : null)+ .then((d) => {+ if (d?.data?.actions?.length) {+ this._actions = d.data.actions;+ this._renderLog();+ } else if (Array.isArray(d?.actions)) {+ this._actions = d.actions;+ this._renderLog();+ }+ })+ .catch(() => {})+ .finally(() => { this._fetchingActivity = false; });+ }+ }+ };+ this._rafId = requestAnimationFrame(loop);+ }++ _renderLog() {+ const actions = this._actions;+ this._logCount.textContent = actions.length ? `${actions.length} actions` : '—';+ if (!actions.length) {+ this._logList.innerHTML = '<div class="wp-log-empty">No activity yet</div>';+ return;+ }+ this._logList.innerHTML = actions.map((a) => `+<div class="wp-log-row">+ <div class="wp-log-type">${esc(a.type || 'action')}</div>+ <div class="wp-log-summary">${esc(a.summary || a.type || '')}</div>+ <div class="wp-log-time">${relTime(a.ts || Date.now())}</div>+</div>`).join('');+ }++ async _bootWebcam() {+ const wrap = this.el.querySelector('#wp-cw');+ if (!wrap) return;++ try {+ // Load the animation manifest once.+ const manifest = await fetch('/animations/manifest.json')+ .then((r) => r.ok ? r.json() : [])+ .catch(() => []);++ // Create an offscreen canvas for the avatar, matching the webcam pane's 3:4 ratio.+ const offscreen = document.createElement('canvas');+ offscreen.width = 480;+ offscreen.height = 640;+ offscreen.style.display = 'none';+ wrap.appendChild(offscreen);+ this._camCanvas = offscreen;++ // Mount a Viewer in kiosk mode into the offscreen canvas.+ this._viewer = new Viewer({+ el: offscreen,+ kiosk: true,+ background: '#0d0d10',+ environment: 'Neutral',+ cameraControls: false,+ autoRotate: false,+ });++ await this._viewer.load(this.avatarUrl);++ // Position the camera close to the face — head cam.+ const cam = this._viewer.camera;+ if (cam) {+ cam.position.set(0, 1.55, 0.65);+ cam.lookAt(0, 1.55, 0);+ }++ // Retarget idle onto the avatar.+ const idleDef = manifest.find?.((c) => c.id === 'idle' || c.name === 'idle');+ if (idleDef) {+ this._idleAnim = new IdleAnimation(this._viewer, idleDef);+ this._idleAnim.start();+ }++ // Pipe to the video element via captureStream.+ const stream = offscreen.captureStream?.(15);+ if (stream && this._video) {+ this._video.srcObject = stream;+ this._video.style.display = 'block';+ await this._video.play().catch(() => {});+ }+ } catch {+ // Webcam boot failed — hide the pane gracefully.+ const cw = this.el.querySelector('#wp-cw');+ if (cw) cw.style.display = 'none';+ const stage = this.el.querySelector('.wp-stage');+ if (stage) stage.style.gridTemplateColumns = '1fr';+ }+ }++ async _rebootWebcam() {+ this._idleAnim?.stop?.();+ this._viewer?.dispose?.();+ this._viewer = null;+ this._idleAnim = null;+ if (this._camCanvas) {+ this._camCanvas.remove();+ this._camCanvas = null;+ }+ await this._bootWebcam();+ }++ destroy() {+ this._destroyed = true;+ if (this._rafId) cancelAnimationFrame(this._rafId);+ try { this._es?.close(); } catch { /* */ }+ this._idleAnim?.stop?.();+ this._viewer?.dispose?.();+ if (this._camCanvas) this._camCanvas.remove();+ }+}++// ── public factory ────────────────────────────────────────────────────────────++/**+ * Mount the watch panel into `container`.+ *+ * @param {{ agentId:string, agentName?:string, avatarUrl?:string, isOwner?:boolean,+ * container:HTMLElement, position?:'append'|'prepend' }} opts+ * @returns {Promise<{destroy():void}|null>}+ */+export async function mountWatchPanel({ agentId, agentName, avatarUrl, isOwner = false, container, position = 'append' } = {}) {+ if (!agentId || !container) return null;++ injectStyles();++ const root = document.createElement('div');+ root.className = 'watch-panel-root';+ if (position === 'prepend') container.prepend(root);+ else container.append(root);++ const panel = new WatchPanel(root, { agentId, agentName, avatarUrl, isOwner });+ await panel.start();++ return { destroy: () => { panel.destroy(); root.remove(); } };+}