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 a menu bar panel with the agent in 3D, wallet balance, start/stop, approvals and quick ask
nirholas05c918b68fc0
diff --git a/apps/desktop/README.md b/apps/desktop/README.mdindex 991f44ac8..46f283e96 100644--- a/apps/desktop/README.md+++ b/apps/desktop/README.md@@ -40,6 +40,9 @@ and says it out loud.[three.ws/companion](https://three.ws/companion). This app is a body, not asecond set of rules.- **Pauses from the tray**, and can start at login.+- **Menu bar panel.** Click the tray icon for a popover with your agent in 3D,+ its wallet balance, start and stop, pending approvals and a one-line ask box.+ See [docs/desktop-menu-bar-panel.md](../../docs/desktop-menu-bar-panel.md).## Install and rundiff --git a/apps/desktop/src/main.js b/apps/desktop/src/main.jsindex 306005d02..49d8fc8b5 100644--- a/apps/desktop/src/main.js+++ b/apps/desktop/src/main.js@@ -33,6 +33,8 @@ import { createNotifier } from './main/notifier.js';import { createUpdater } from './main/updater.js';import { createCompanion } from './main/companion.js';import { createLocalRuntimeService } from './main/local-runtime.js';+import { createPanel } from './main/panel.js';+import { trayTitle, trayTooltip } from './panel/model.js';import { detectEditors, connectEditor, disconnectEditor, mcpServers } from './main/editors.js';const SRC = dirname(fileURLToPath(import.meta.url));@@ -74,6 +76,8 @@ let notifier;let updater;let companion;let localRuntime;+let panel;+let trayMenu = null;let store;function sendToConsole(channel, payload) {@@ -147,18 +151,24 @@ function trayIcon() {return img;}+function updateTrayTitle(snapshot) {+ if (!state.tray) return;+ const view = { signedIn: snapshot.signedIn, name: snapshot.user?.name, pendingApprovals: snapshot.pending.length, unread: snapshot.unread };+ state.tray.setToolTip(trayTooltip(view));+ if (process.platform === 'darwin') state.tray.setTitle(trayTitle(view));+}+function refreshTray() {if (!state.tray) return;const s = session.status();const c = companion.status();const u = updater.state();const who = s.signedIn ? (s.user?.name || 'Signed in') : 'Not signed in';- state.tray.setToolTip(`three.ws Desktop: ${who}${state.unread ? `, ${state.unread} unread` : ''}`);- if (process.platform === 'darwin') state.tray.setTitle(state.unread ? String(state.unread) : '');+ panel?.touch();const template = [{ label: `three.ws Desktop · ${who}`, enabled: false },- { type: 'separator' },+ { label: 'Show panel', click: () => panel.show() },{ label: 'Open console', accelerator: 'CommandOrControl+Shift+Space', click: () => openConsole() },...(s.signedIn ? [{ label: state.unread ? `Notifications (${state.unread} unread)` : 'Notifications', click: () => openConsole('notifications') },@@ -190,7 +200,10 @@ function refreshTray() {{ type: 'separator' },{ label: 'Quit three.ws', role: 'quit' },];- state.tray.setContextMenu(Menu.buildFromTemplate(template));+ trayMenu = Menu.buildFromTemplate(template);+ // Linux indicators often deliver no click events, so the menu stays attached+ // there. Elsewhere a left click opens the panel and a right click the menu.+ if (process.platform === 'linux') state.tray.setContextMenu(trayMenu);}function setCompanionMode(enabled) {@@ -434,8 +447,10 @@ function boot() {openBrowser: (url) => shell.openExternal(url),onChange: (status) => {sendToConsole('session:changed', status);- if (status.signedIn) notifier?.start();- else notifier?.stop();+ if (status.signedIn) {+ notifier?.start();+ panel?.sync();+ } else notifier?.stop();refreshTray();},});@@ -468,10 +483,29 @@ function boot() {onFace: (face) => companion.setFace(face),});+ panel = createPanel({+ srcDir: SRC,+ session,+ api,+ runtime: localRuntime.runtime,+ companion,+ getUnread: () => state.unread,+ readSettings,+ writeSettings,+ openConsole,+ setCompanionMode,+ openExternal,+ onChange: updateTrayTitle,+ });+ panel.setReview((id) => localRuntime.decideThroughDialog(id));+registerIpc();+ panel.register();state.tray = new Tray(trayIcon());- state.tray.on('click', () => (process.platform === 'darwin' ? state.tray.popUpContextMenu() : openConsole()));+ state.tray.on('click', () => panel.toggle());+ state.tray.on('right-click', () => trayMenu && state.tray.popUpContextMenu(trayMenu));+ panel.attachTray(state.tray);refreshTray();if (readSettings().companionMode) companion.enable();@@ -502,6 +536,7 @@ if (!app.requestSingleInstanceLock()) {// Closing the console leaves the app in the tray; Quit lives in the tray menu.app.on('window-all-closed', () => {});app.on('before-quit', () => {+ panel?.stop();companion?.stop();notifier?.stop();localRuntime?.runtime.stop();diff --git a/apps/desktop/src/main/panel.js b/apps/desktop/src/main/panel.jsnew file mode 100644index 000000000..4b4f508df--- /dev/null+++ b/apps/desktop/src/main/panel.js@@ -0,0 +1,306 @@+// The menu bar panel: a small popover under the tray icon (above it on a+// taskbar) that shows your agent alive in 3D with the numbers you would+// otherwise open the console for. It owns no business logic. Everything it+// shows comes from the same services the console uses (cloud agents, wallet,+// local runtime, notifications, companion), and every action goes through a+// typed channel to those services. Approving a trade is not one of them: the+// panel can only ask for the native review dialog.++import { BrowserWindow, ipcMain, screen } from 'electron';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { PANEL_WIDTH, PANEL_HEIGHT, placePanel, anchorFor, shouldOpenOnClick, faceView, localSummary } from '../panel/model.js';++const SYNC_VISIBLE_MS = 45_000;+const SYNC_HIDDEN_MS = 5 * 60_000;++export function createPanel({ srcDir, session, api, runtime, companion, getUnread, readSettings, writeSettings, openConsole, setCompanionMode, openExternal, onChange }) {+ let win = null;+ let tray = null;+ let lastBlurHideAt = 0;+ let timer = null;+ let syncing = false;+ let syncedAt = null;+ let syncError = null;+ let agents = [];+ let wallet = null;+ let walletFor = null;+ const asks = new Map();++ const send = (channel, payload) => {+ if (win && !win.isDestroyed()) win.webContents.send(channel, payload);+ };++ function selectedAgent() {+ const want = readSettings().panelAgent;+ return agents.find((a) => a.id === want) || agents[0] || null;+ }++ function localAgentName(id) {+ return runtime.listAgents().find((a) => a.id === id)?.name || 'Local agent';+ }++ /** Everything the panel draws, built from caches so it is instant and never hits the network. */+ function snapshot() {+ const status = session.status();+ const local = runtime.listAgents();+ const pending = runtime.listApprovals({ status: 'pending' }).map((a) => ({+ id: a.id,+ agentName: localAgentName(a.agentId || a.agent_id),+ text: String(a.text || '').split('\n').slice(0, 2).join(' '),+ hash: String(a.hash || '').slice(0, 12),+ }));+ const selected = selectedAgent();+ const c = companion.status();+ return {+ signedIn: status.signedIn,+ user: status.user ? { name: status.user.name || null } : null,+ apiBase: session.apiBase(),+ agents: agents.map((a) => ({ id: a.id, name: a.name, status: a.status, isPublished: a.isPublished })),+ selected: selected ? { id: selected.id, name: selected.name, status: selected.status, isPublished: selected.isPublished, solanaAddress: selected.solanaAddress } : null,+ wallet: wallet && walletFor === selected?.id ? wallet : null,+ local: { agents: local.map((a) => ({ id: a.id, name: a.name, status: a.status })), face: runtime.face(), summary: localSummary(local) },+ face: faceView(runtime.face()),+ pending,+ unread: getUnread(),+ companion: { enabled: c.enabled, paused: c.paused, signedIn: c.signedIn },+ syncing,+ syncedAt,+ syncError,+ };+ }++ function push() {+ const snap = snapshot();+ send('panel:state', snap);+ onChange?.(snap);+ }++ /** Refreshes the network-backed parts (agents, wallet) and pushes the result. */+ async function sync() {+ if (!session.status().signedIn) {+ agents = [];+ wallet = null;+ walletFor = null;+ syncedAt = null;+ syncError = null;+ }+ if (syncing || !session.status().signedIn) {+ push();+ return;+ }+ syncing = true;+ push();+ try {+ agents = await api.listAgents();+ syncError = null;+ const selected = selectedAgent();+ if (selected) {+ try {+ const w = await api.wallet(selected.id);+ wallet = { sol: w.sol, address: w.address, network: w.network, error: w.balanceError || null };+ } catch (err) {+ wallet = { sol: null, address: selected.solanaAddress, network: null, error: err.message };+ }+ walletFor = selected.id;+ }+ syncedAt = Date.now();+ } catch (err) {+ syncError = err.code === 'signed_out' ? null : err.message || 'Could not reach three.ws';+ } finally {+ syncing = false;+ push();+ }+ }++ function schedule() {+ clearTimeout(timer);+ const visible = win && !win.isDestroyed() && win.isVisible();+ timer = setTimeout(() => {+ sync().finally(schedule);+ }, visible ? SYNC_VISIBLE_MS : SYNC_HIDDEN_MS);+ }++ // ── Window ──────────────────────────────────────────────────────────────++ function ensureWindow() {+ if (win && !win.isDestroyed()) return win;+ win = new BrowserWindow({+ width: PANEL_WIDTH,+ height: PANEL_HEIGHT,+ show: false,+ frame: false,+ resizable: false,+ movable: false,+ minimizable: false,+ maximizable: false,+ fullscreenable: false,+ skipTaskbar: true,+ alwaysOnTop: true,+ transparent: process.platform === 'darwin',+ hasShadow: true,+ roundedCorners: true,+ backgroundColor: process.platform === 'darwin' ? '#00000000' : '#0d0d10',+ ...(process.platform === 'darwin' ? { vibrancy: 'under-window', visualEffectState: 'active' } : {}),+ webPreferences: {+ preload: join(srcDir, 'panel-preload.cjs'),+ contextIsolation: true,+ nodeIntegration: false,+ sandbox: true,+ },+ });+ if (process.platform === 'darwin') win.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });+ win.loadFile(join(srcDir, 'panel', 'index.html'));+ win.on('blur', () => {+ if (win.webContents.isDevToolsOpened()) return;+ if (win.isVisible()) {+ lastBlurHideAt = Date.now();+ win.hide();+ schedule();+ }+ });+ win.on('closed', () => {+ win = null;+ });+ return win;+ }++ function show() {+ const w = ensureWindow();+ const anchor = anchorFor(tray?.getBounds(), screen.getCursorScreenPoint());+ const display = screen.getDisplayNearestPoint({ x: anchor.x, y: anchor.y });+ w.setBounds(placePanel(anchor, { width: PANEL_WIDTH, height: PANEL_HEIGHT }, display.workArea));+ w.show();+ w.focus();+ send('panel:show', snapshot());+ sync();+ schedule();+ }++ function hide() {+ if (win && !win.isDestroyed() && win.isVisible()) win.hide();+ schedule();+ }++ function toggle() {+ if (win && !win.isDestroyed() && win.isVisible()) return hide();+ if (!shouldOpenOnClick(lastBlurHideAt, Date.now())) return undefined;+ return show();+ }++ // ── IPC ─────────────────────────────────────────────────────────────────++ function handle(channel, fn) {+ ipcMain.handle(channel, async (event, ...args) => {+ if (!win || win.isDestroyed() || event.sender !== win.webContents) return { ok: false, error: { message: 'Not allowed from this window', code: 'forbidden' } };+ try {+ return { ok: true, data: await fn(...args) };+ } catch (err) {+ return { ok: false, error: { message: err?.message || String(err), code: err?.code || null } };+ }+ });+ }++ function register() {+ handle('panel:state', () => snapshot());+ handle('panel:refresh', async () => {+ await sync();+ return snapshot();+ });+ handle('panel:select', async (agentId) => {+ if (!agents.some((a) => a.id === String(agentId))) throw new Error('That agent is not in your account');+ writeSettings({ panelAgent: String(agentId) });+ wallet = null;+ walletFor = null;+ await sync();+ return snapshot();+ });+ handle('panel:setAgentRunning', async (agentId, running) => {+ const updated = await api.setAgentStatus(String(agentId), Boolean(running));+ agents = agents.map((a) => (a.id === updated.id ? { ...a, ...updated } : a));+ push();+ return snapshot();+ });+ handle('panel:toggleLocal', () => {+ const { action } = localSummary(runtime.listAgents());+ for (const a of runtime.listAgents()) {+ if (a.status === 'killed') continue;+ if (action === 'resume' && a.status === 'paused') runtime.resume(a.id);+ if (action === 'pause' && a.status !== 'paused') runtime.pause(a.id);+ }+ push();+ return snapshot();+ });+ handle('panel:review', async (approvalId) => {+ // The native dialog is modal over the whole app; the panel hides first+ // so it is not left floating behind it.+ hide();+ const result = await companionReview(String(approvalId));+ push();+ return result;+ });+ handle('panel:ask', (message) => {+ const text = String(message || '').trim().slice(0, 2000);+ const agent = selectedAgent();+ if (!text) throw new Error('Type a message first.');+ if (!agent) throw new Error('Pick an agent first.');+ const requestId = randomUUID();+ const controller = new AbortController();+ asks.set(requestId, controller);+ api.sendChat({ agentId: agent.id, message: text, history: [], signal: controller.signal }, (evt) => send('panel:chat', { requestId, ...evt }))+ .catch((err) => {+ if (controller.signal.aborted) send('panel:chat', { requestId, type: 'aborted' });+ else send('panel:chat', { requestId, type: 'error', message: err.message, code: err.code || null });+ })+ .finally(() => {+ asks.delete(requestId);+ send('panel:chat', { requestId, type: 'end' });+ });+ return { requestId };+ });+ handle('panel:abortAsk', (requestId) => {+ asks.get(String(requestId))?.abort();+ return true;+ });+ handle('panel:setCompanion', (enabled) => {+ setCompanionMode(Boolean(enabled));+ push();+ return snapshot();+ });+ handle('panel:open', (view) => {+ hide();+ openConsole(view ? String(view) : undefined);+ return true;+ });+ handle('panel:openExternal', (url) => openExternal(url));+ handle('panel:hide', () => {+ hide();+ return true;+ });+ }++ let companionReview = async () => ({ status: 'unavailable' });++ return {+ register,+ attachTray(t) {+ tray = t;+ },+ setReview(fn) {+ companionReview = fn;+ },+ toggle,+ show,+ hide,+ /** Cheap: called whenever a cache elsewhere changed. */+ touch: push,+ sync,+ stop() {+ clearTimeout(timer);+ for (const c of asks.values()) c.abort();+ asks.clear();+ if (win && !win.isDestroyed()) win.destroy();+ },+ pendingCount: () => runtime.listApprovals({ status: 'pending' }).length,+ };+}diff --git a/apps/desktop/src/panel-preload.cjs b/apps/desktop/src/panel-preload.cjsnew file mode 100644index 000000000..267b7d31d--- /dev/null+++ b/apps/desktop/src/panel-preload.cjs@@ -0,0 +1,38 @@+// The only bridge between the menu bar panel and the machine. Sandboxed and+// context-isolated: typed calls into the main process and nothing else. There+// is no approve call. Approving a trade opens a native dialog built in the main+// process from the stored approval, so the panel can only ask for a review.++const { contextBridge, ipcRenderer } = require('electron');++async function call(channel, ...args) {+ const res = await ipcRenderer.invoke(channel, ...args);+ if (res && res.ok) return res.data;+ const err = new Error(res?.error?.message || 'Something went wrong');+ err.code = res?.error?.code || null;+ throw err;+}++function on(channel, handler) {+ const listener = (_event, payload) => handler(payload);+ ipcRenderer.on(channel, listener);+ return () => ipcRenderer.removeListener(channel, listener);+}++contextBridge.exposeInMainWorld('panel', {+ state: () => call('panel:state'),+ refresh: () => call('panel:refresh'),+ select: (agentId) => call('panel:select', agentId),+ setAgentRunning: (agentId, running) => call('panel:setAgentRunning', agentId, running),+ toggleLocal: () => call('panel:toggleLocal'),+ review: (approvalId) => call('panel:review', approvalId),+ ask: (message) => call('panel:ask', message),+ abortAsk: (requestId) => call('panel:abortAsk', requestId),+ setCompanion: (enabled) => call('panel:setCompanion', enabled),+ open: (view) => call('panel:open', view),+ openExternal: (url) => call('panel:openExternal', url),+ hide: () => call('panel:hide'),+ onState: (fn) => on('panel:state', fn),+ onChat: (fn) => on('panel:chat', fn),+ onShow: (fn) => on('panel:show', fn),+});diff --git a/apps/desktop/src/panel/index.html b/apps/desktop/src/panel/index.htmlnew file mode 100644index 000000000..3a21ef232--- /dev/null+++ b/apps/desktop/src/panel/index.html@@ -0,0 +1,69 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <!-- No network from this page: every request goes through the main+ process. The one outside surface is the published walk embed. -->+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' https: data:; connect-src 'none'; base-uri 'none'; form-action 'none'; frame-src https: http://127.0.0.1:* http://localhost:*" />+ <title>three.ws</title>+ <link rel="stylesheet" href="panel.css" />+ </head>+ <body>+ <main class="panel" id="panel" aria-busy="true">+ <header class="top">+ <label class="picker" id="picker-wrap">+ <span class="sr">Agent</span>+ <select id="picker" aria-label="Agent"></select>+ </label>+ <span class="pill" id="power-label" data-tone="muted"></span>+ <button class="power" id="power" type="button" aria-label="Start or stop agent" aria-pressed="false" hidden>+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3v9M6.3 6.8a8 8 0 1 0 11.4 0" /></svg>+ </button>+ </header>++ <section class="stage" aria-label="Your agent">+ <iframe id="body" title="Agent avatar" tabindex="-1" allow="autoplay" referrerpolicy="no-referrer"></iframe>+ <p class="face" id="face" role="status" data-tone="muted"></p>+ </section>++ <section class="numbers">+ <div class="balance" id="balance" aria-live="polite">+ <span class="num" id="sol"></span><span class="unit" id="sol-unit">SOL</span>+ <button class="addr" id="addr" type="button" title="Copy wallet address"></button>+ </div>+ <label class="switch-card" id="companion-card">+ <span class="switch-label">Companion</span>+ <input type="checkbox" id="companion" role="switch" />+ <span class="track" aria-hidden="true"><span class="knob"></span></span>+ </label>+ </section>++ <section class="approval" id="approval" hidden aria-live="polite"></section>++ <section class="tiles" id="tiles" aria-label="Status"></section>++ <form class="ask" id="ask" autocomplete="off">+ <label class="sr" for="ask-input">Ask your agent</label>+ <input id="ask-input" type="text" maxlength="2000" placeholder="Ask your agent" />+ <button type="submit" id="ask-send" aria-label="Send">+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6" /></svg>+ </button>+ </form>+ <section class="reply" id="reply" hidden aria-live="polite"></section>++ <footer class="foot">+ <span class="sync" id="sync" role="status"></span>+ <button class="link" id="open-console" type="button">Open console</button>+ </footer>+ </main>++ <section class="signin" id="signin" hidden>+ <div class="signin-mark" aria-hidden="true"></div>+ <h1>Sign in to three.ws</h1>+ <p>See your agent, its wallet and anything waiting on you, right from the menu bar.</p>+ <button class="primary" id="signin-btn" type="button">Sign in</button>+ </section>+ <script type="module" src="panel.js"></script>+ </body>+</html>diff --git a/apps/desktop/src/panel/model.js b/apps/desktop/src/panel/model.jsnew file mode 100644index 000000000..8d9a5a964--- /dev/null+++ b/apps/desktop/src/panel/model.js@@ -0,0 +1,126 @@+// Pure logic for the menu bar panel: where the popover goes, what the avatar+// should be doing, and what the menu bar shows. No Electron, no DOM, so the+// main process, the renderer and the tests all import the same functions.++export const PANEL_WIDTH = 372;+export const PANEL_HEIGHT = 560;+const EDGE_GAP = 8;++/**+ * Where to put the popover. `anchor` is the tray icon's rectangle (or a 1px+ * rectangle at the cursor where the OS reports no tray bounds, as Linux does).+ * The panel is centered on the anchor, clamped inside the work area, and sits+ * below the anchor when the anchor is in the top half of the display (a menu+ * bar) and above it otherwise (a taskbar).+ */+export function placePanel(anchor, size, workArea) {+ const w = Math.min(size.width, workArea.width - EDGE_GAP * 2);+ const h = Math.min(size.height, workArea.height - EDGE_GAP * 2);+ const centerX = anchor.x + anchor.width / 2;+ const minX = workArea.x + EDGE_GAP;+ const maxX = workArea.x + workArea.width - w - EDGE_GAP;+ const x = Math.round(Math.min(Math.max(centerX - w / 2, minX), Math.max(minX, maxX)));+ const anchorMid = anchor.y + anchor.height / 2;+ const topHalf = anchorMid < workArea.y + workArea.height / 2;+ const rawY = topHalf ? anchor.y + anchor.height + EDGE_GAP : anchor.y - h - EDGE_GAP;+ const minY = workArea.y + EDGE_GAP;+ const maxY = workArea.y + workArea.height - h - EDGE_GAP;+ const y = Math.round(Math.min(Math.max(rawY, minY), Math.max(minY, maxY)));+ return { x, y, width: w, height: h };+}++/** An anchor rectangle: the tray icon's bounds when the OS gives them, else the cursor. */+export function anchorFor(trayBounds, cursor) {+ if (trayBounds && trayBounds.width > 0 && trayBounds.height > 0) return trayBounds;+ return { x: cursor.x, y: cursor.y, width: 1, height: 1 };+}++/**+ * Clicking the tray icon while the panel is open first blurs it (which hides+ * it) and then delivers the click. Without this the panel would flicker shut+ * and straight back open instead of staying closed.+ */+export function shouldOpenOnClick(lastBlurHideAt, now, windowMs = 250) {+ return !(lastBlurHideAt && now - lastBlurHideAt < windowMs);+}++const FACE = {+ none: { key: 'none', label: 'No local agents yet', gesture: 'idle', tone: 'muted' },+ idle: { key: 'idle', label: 'Idle, watching', gesture: 'idle', tone: 'ok' },+ working: { key: 'working', label: 'Working', gesture: 'walk', tone: 'ok' },+ waiting_approval: { key: 'waiting_approval', label: 'Needs your approval', gesture: 'wave', tone: 'warn' },+ error: { key: 'error', label: 'Needs attention', gesture: 'idle', tone: 'bad' },+ paused: { key: 'paused', label: 'Paused', gesture: 'idle', tone: 'muted' },+ killed: { key: 'killed', label: 'Stopped', gesture: 'idle', tone: 'muted' },+};++/** What the avatar does and says for the local runtime's most urgent state. */+export function faceView(face) {+ return FACE[face?.state] || FACE.none;+}++/** Text shown next to the icon in the macOS menu bar. Approvals outrank unread. */+export function trayTitle({ pendingApprovals = 0, unread = 0 } = {}) {+ if (pendingApprovals > 0) return `${pendingApprovals} to approve`;+ if (unread > 0) return String(unread > 99 ? '99+' : unread);+ return '';+}++/** One tooltip line for the tray icon. */+export function trayTooltip({ signedIn, name, pendingApprovals = 0, unread = 0 }) {+ const who = signedIn ? name || 'Signed in' : 'Not signed in';+ const bits = [];+ if (pendingApprovals) bits.push(`${pendingApprovals} awaiting approval`);+ if (unread) bits.push(`${unread} unread`);+ return `three.ws Desktop: ${who}${bits.length ? `, ${bits.join(', ')}` : ''}`;+}++/** SOL for a balance row: more digits for small balances, none of the noise for large ones. */+export function formatSol(sol) {+ if (sol == null || !Number.isFinite(Number(sol))) return null;+ const n = Number(sol);+ if (n === 0) return '0';+ if (n >= 1000) return n.toLocaleString('en-US', { maximumFractionDigits: 0 });+ if (n >= 1) return n.toLocaleString('en-US', { maximumFractionDigits: 3 });+ return n.toLocaleString('en-US', { maximumSignificantDigits: 3 });+}++export function shortAddress(address) {+ const a = String(address || '');+ return a.length > 12 ? `${a.slice(0, 4)}...${a.slice(-4)}` : a;+}++/** "just now", "42s ago", "5m ago" for the sync footer. */+export function ago(ms, now = Date.now()) {+ if (!ms) return null;+ const s = Math.max(0, Math.round((now - ms) / 1000));+ if (s < 5) return 'just now';+ if (s < 60) return `${s}s ago`;+ const m = Math.round(s / 60);+ if (m < 60) return `${m}m ago`;+ return `${Math.round(m / 60)}h ago`;+}++/** Cloud agent lifecycle to a label and whether the power button reads as on. */+export function agentPower(agent) {+ if (!agent) return { on: false, known: false, label: 'No agent' };+ if (agent.status === 'running') return { on: true, known: true, label: 'Running' };+ if (agent.status === 'stopped') return { on: false, known: true, label: 'Stopped' };+ if (agent.status === 'draft') return { on: false, known: false, label: 'Draft' };+ return { on: Boolean(agent.isPublished), known: false, label: agent.isPublished ? 'Live' : 'Unpublished' };+}++/**+ * The local runtime in one tile: how many agents, how many are running, and+ * whether the tile's button should pause everything or resume it.+ */+export function localSummary(agents = []) {+ const alive = agents.filter((a) => a.status !== 'killed');+ const paused = alive.filter((a) => a.status === 'paused');+ return {+ total: alive.length,+ paused: paused.length,+ allPaused: alive.length > 0 && paused.length === alive.length,+ action: alive.length > 0 && paused.length === alive.length ? 'resume' : 'pause',+ };+}diff --git a/apps/desktop/src/panel/panel.css b/apps/desktop/src/panel/panel.cssnew file mode 100644index 000000000..e567493b2--- /dev/null+++ b/apps/desktop/src/panel/panel.css@@ -0,0 +1,136 @@+/* Menu bar panel. Same tokens as the console so the app reads as one product. */+:root {+ --bg: #0d0d10;+ --card: rgba(255, 255, 255, 0.045);+ --card-hover: rgba(255, 255, 255, 0.08);+ --line: rgba(255, 255, 255, 0.08);+ --text: #e7e9ee;+ --muted: rgba(231, 233, 238, 0.62);+ --dim: rgba(231, 233, 238, 0.4);+ --blue: #3b82f6;+ --green: #22c55e;+ --amber: #f59e0b;+ --red: #ef4444;+ --font: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, system-ui, sans-serif;+ --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ color-scheme: dark;+}+@media (prefers-color-scheme: light) {+ :root {+ --bg: #f5f5f7;+ --card: rgba(0, 0, 0, 0.04);+ --card-hover: rgba(0, 0, 0, 0.075);+ --line: rgba(0, 0, 0, 0.09);+ --text: #17171c;+ --muted: rgba(23, 23, 28, 0.62);+ --dim: rgba(23, 23, 28, 0.42);+ color-scheme: light;+ }+}+* { box-sizing: border-box; }+html, body { margin: 0; height: 100%; background: transparent; color: var(--text); font: 13px/1.4 var(--font); -webkit-font-smoothing: antialiased; overflow: hidden; user-select: none; }+.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }+button, select, input { font: inherit; color: inherit; }+:focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; }++.panel { display: flex; flex-direction: column; gap: 10px; height: 100%; padding: 14px; background: color-mix(in srgb, var(--bg) 82%, transparent); }+.panel[hidden], [hidden] { display: none !important; }++/* header */+.top { display: flex; align-items: center; gap: 8px; }+.picker { flex: 1; min-width: 0; }+.picker select { width: 100%; appearance: none; background: var(--card); border: 1px solid var(--line); border-radius: 10px; padding: 7px 28px 7px 10px; font-weight: 600; text-overflow: ellipsis; cursor: pointer; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12'%3E%3Cpath d='M3 4.5 6 7.5 9 4.5' fill='none' stroke='%23999' stroke-width='1.4' stroke-linecap='round'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 9px center; background-size: 12px; }+.picker select:hover { background-color: var(--card-hover); }+.pill { font-size: 11px; font-weight: 600; padding: 3px 9px; border-radius: 99px; background: var(--card); color: var(--muted); white-space: nowrap; }+.pill[data-tone='ok'] { color: var(--green); background: rgba(34, 197, 94, 0.14); }+.pill[data-tone='warn'] { color: var(--amber); background: rgba(245, 158, 11, 0.14); }+.pill[data-tone='bad'] { color: var(--red); background: rgba(239, 68, 68, 0.12); }+.power { width: 34px; height: 34px; flex: none; display: grid; place-items: center; border-radius: 50%; border: 1px solid var(--line); background: var(--card); cursor: pointer; transition: background 0.15s, transform 0.1s; }+.power svg { width: 18px; height: 18px; fill: none; stroke: var(--muted); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }+.power:hover { background: var(--card-hover); }+.power:active { transform: scale(0.94); }+.power[aria-pressed='true'] svg { stroke: var(--green); }+.power[aria-pressed='true'] { border-color: rgba(34, 197, 94, 0.4); }+.power:disabled { opacity: 0.5; cursor: progress; }++/* stage */+.stage { position: relative; flex: none; height: 188px; border-radius: 14px; background: radial-gradient(120% 90% at 50% 100%, rgba(59, 130, 246, 0.16), transparent 70%), var(--card); border: 1px solid var(--line); overflow: hidden; }+.stage iframe { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; background: transparent; pointer-events: none; color-scheme: normal; }+.face { position: absolute; left: 12px; bottom: 10px; margin: 0; display: inline-flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 600; color: var(--muted); }+.face::before { content: ''; width: 7px; height: 7px; border-radius: 50%; background: var(--dim); }+.face[data-tone='ok']::before { background: var(--green); }+.face[data-tone='warn']::before { background: var(--amber); animation: pulse 1.4s ease-in-out infinite; }+.face[data-tone='bad']::before { background: var(--red); }+@keyframes pulse { 50% { opacity: 0.35; } }+@media (prefers-reduced-motion: reduce) { .face::before, .sk { animation: none !important; } }++/* numbers */+.numbers { display: flex; align-items: stretch; gap: 10px; }+.balance { flex: 1; min-width: 0; display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 6px; }+.num { font-size: 38px; line-height: 1; font-weight: 600; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }+.unit { font-size: 15px; color: var(--muted); font-weight: 600; }+.addr { flex-basis: 100%; text-align: left; background: none; border: 0; padding: 2px 0; font: 11px var(--mono); color: var(--dim); cursor: pointer; border-radius: 4px; }+.addr:hover { color: var(--text); }+.sk { display: inline-block; border-radius: 8px; background: linear-gradient(90deg, var(--card), var(--card-hover), var(--card)); background-size: 200% 100%; animation: sheen 1.3s linear infinite; }+@keyframes sheen { to { background-position: -200% 0; } }++.switch-card { flex: none; display: flex; align-items: center; gap: 10px; padding: 0 12px; border-radius: 12px; background: var(--card); border: 1px solid var(--line); cursor: pointer; align-self: center; height: 44px; }+.switch-card:hover { background: var(--card-hover); }+.switch-label { font-weight: 600; font-size: 12px; }+.switch-card input { position: absolute; opacity: 0; width: 1px; height: 1px; }+.track { width: 40px; height: 22px; border-radius: 99px; background: rgba(255, 255, 255, 0.16); position: relative; transition: background 0.15s; }+.knob { position: absolute; top: 2px; left: 2px; width: 18px; height: 18px; border-radius: 50%; background: #fff; transition: transform 0.15s; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.35); }+.switch-card input:checked + .track { background: var(--green); }+.switch-card input:checked + .track .knob { transform: translateX(18px); }+.switch-card input:focus-visible + .track { outline: 2px solid var(--blue); outline-offset: 2px; }++/* approvals */+.approval { border-radius: 12px; border: 1px solid rgba(245, 158, 11, 0.4); background: rgba(245, 158, 11, 0.1); padding: 10px 12px; display: grid; gap: 8px; }+.approval .row { display: flex; gap: 10px; align-items: center; justify-content: space-between; }+.approval b { font-size: 12px; display: block; }+.approval p { margin: 2px 0 0; color: var(--muted); font-size: 12px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }+.approval button { flex: none; }++/* tiles */+.tiles { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }+.tile { display: grid; gap: 2px; text-align: left; padding: 10px 11px; border-radius: 12px; background: var(--card); border: 1px solid var(--line); cursor: pointer; min-width: 0; transition: background 0.15s, transform 0.1s; }+.tile:hover { background: var(--card-hover); }+.tile:active { transform: scale(0.98); }+.tile:disabled { opacity: 0.5; cursor: default; }+.tile .k { font-size: 11px; color: var(--muted); }+.tile .v { font-weight: 600; font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.tile[data-tone='warn'] .v { color: var(--amber); }+.tile[data-tone='bad'] .v { color: var(--red); }+.tile[data-tone='ok'] .v { color: var(--green); }++/* ask */+.ask { display: flex; gap: 6px; margin-top: auto; }+.ask input { flex: 1; min-width: 0; user-select: text; background: var(--card); border: 1px solid var(--line); border-radius: 10px; padding: 9px 12px; }+.ask input::placeholder { color: var(--dim); }+.ask input:focus { border-color: var(--blue); outline: none; }+.ask button { width: 38px; display: grid; place-items: center; border-radius: 10px; border: 0; background: var(--blue); cursor: pointer; }+.ask button svg { width: 18px; height: 18px; fill: none; stroke: #fff; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }+.ask button:hover { filter: brightness(1.12); }+.ask button:disabled { opacity: 0.45; cursor: default; }+.reply { max-height: 92px; overflow: auto; padding: 9px 12px; border-radius: 10px; background: var(--card); border: 1px solid var(--line); font-size: 12.5px; user-select: text; white-space: pre-wrap; overflow-wrap: anywhere; }+.reply[data-state='error'] { border-color: rgba(239, 68, 68, 0.4); color: var(--red); }+.reply .who { display: block; font-size: 11px; color: var(--muted); margin-bottom: 2px; }++/* footer */+.foot { display: flex; justify-content: space-between; align-items: center; color: var(--dim); font-size: 11.5px; }+.sync { display: inline-flex; align-items: center; gap: 6px; }+.sync[data-busy='true']::before { content: ''; width: 10px; height: 10px; border-radius: 50%; border: 2px solid var(--dim); border-top-color: transparent; animation: spin 0.8s linear infinite; }+.sync[data-error='true'] { color: var(--red); }+@keyframes spin { to { transform: rotate(360deg); } }+.link { background: none; border: 0; color: var(--muted); cursor: pointer; padding: 3px 6px; border-radius: 6px; font-size: 11.5px; }+.link:hover { color: var(--text); background: var(--card); }++.btn, .primary { border: 0; border-radius: 8px; padding: 6px 12px; font-weight: 600; cursor: pointer; background: var(--amber); color: #1a1205; }+.btn:hover, .primary:hover { filter: brightness(1.08); }+.primary { background: var(--blue); color: #fff; padding: 9px 22px; border-radius: 10px; }++/* signed out */+.signin { display: grid; place-content: center; justify-items: center; gap: 10px; height: 100%; padding: 28px; text-align: center; background: color-mix(in srgb, var(--bg) 82%, transparent); }+.signin h1 { margin: 0; font-size: 18px; }+.signin p { margin: 0; color: var(--muted); max-width: 250px; }+.signin-mark { width: 52px; height: 52px; border-radius: 14px; background: linear-gradient(135deg, var(--blue), #7c3aed); }diff --git a/apps/desktop/src/panel/panel.js b/apps/desktop/src/panel/panel.jsnew file mode 100644index 000000000..159bf4440--- /dev/null+++ b/apps/desktop/src/panel/panel.js@@ -0,0 +1,280 @@+// Menu bar panel renderer. Draws the snapshot the main process pushes and sends+// typed actions back. It holds no data of its own beyond what is on screen.+// The 3D body is the published walk embed driven over its postMessage contract+// (the same one the desktop companion uses), so the panel owns no 3D code.++import { formatSol, shortAddress, ago, agentPower } from './model.js';++const $ = (id) => document.getElementById(id);+const el = (tag, props = {}, ...kids) => {+ const node = Object.assign(document.createElement(tag), props);+ for (const k of kids) node.append(k);+ return node;+};++const els = {+ panel: $('panel'), signin: $('signin'), picker: $('picker'), pill: $('power-label'), power: $('power'),+ body: $('body'), face: $('face'), sol: $('sol'), unit: $('sol-unit'), addr: $('addr'), balance: $('balance'),+ companion: $('companion'), companionCard: $('companion-card'), approval: $('approval'), tiles: $('tiles'),+ ask: $('ask'), askInput: $('ask-input'), askSend: $('ask-send'), reply: $('reply'), sync: $('sync'),+};++let state = null;+let embedFor = null;+let embedReady = false;+let embedOrigin = null;+let lastGesture = null;+let activeAsk = null;+let busyPower = false;++// ── 3D body ─────────────────────────────────────────────────────────────────++function toEmbed(type, payload = {}) {+ if (!embedReady || !embedOrigin) return;+ els.body.contentWindow?.postMessage({ channel: 'three-walk', v: 1, type, ...payload }, embedOrigin);+}++function mountEmbed(apiBase, agentId) {+ const key = `${apiBase}|${agentId || ''}`;+ if (embedFor === key) return;+ embedFor = key;+ embedReady = false;+ lastGesture = null;+ embedOrigin = new URL(apiBase).origin;+ const params = new URLSearchParams({ bg: 'transparent', ground: 'false', controls: 'none', badge: 'false', orbit: 'false', click: 'false', env: 'studio' });+ if (agentId) params.set('agent', agentId);+ els.body.src = `${apiBase}/walk-embed?${params}`;+}++els.body.addEventListener('load', () => {+ if (embedOrigin) els.body.contentWindow?.postMessage({ channel: 'three-walk', v: 1, type: 'walk:ping' }, embedOrigin);+});++window.addEventListener('message', (event) => {+ if (!embedOrigin || event.origin !== embedOrigin || event.source !== els.body.contentWindow) return;+ if (event.data?.type === 'walk:ready') {+ embedReady = true;+ applyGesture();+ }+});++function applyGesture() {+ const gesture = state?.face?.gesture;+ if (!gesture || gesture === lastGesture) return;+ lastGesture = gesture;+ toEmbed('walk:gesture', { gesture });+}++// ── Render ──────────────────────────────────────────────────────────────────++function tile(key, value, { tone = '', onClick = null, disabled = false, title = '' } = {}) {+ const b = el('button', { type: 'button', className: 'tile', disabled, title }, el('span', { className: 'k', textContent: key }), el('span', { className: 'v', textContent: value }));+ if (tone) b.dataset.tone = tone;+ if (onClick) b.addEventListener('click', onClick);+ return b;+}++function renderPicker(s) {+ els.picker.replaceChildren(...s.agents.map((a) => el('option', { value: a.id, textContent: a.name, selected: a.id === s.selected?.id })));+ els.picker.disabled = s.agents.length < 2;+ els.picker.title = s.agents.length < 2 ? 'Create more agents on three.ws to switch between them' : '';+}++function renderHeader(s) {+ const power = agentPower(s.selected);+ els.pill.textContent = s.selected ? power.label : s.syncedAt || s.syncError ? 'No agents' : 'Loading';+ els.pill.dataset.tone = power.on ? 'ok' : 'muted';+ els.power.hidden = !s.selected || !power.known;+ els.power.setAttribute('aria-pressed', String(power.on));+ els.power.setAttribute('aria-label', power.on ? `Stop ${s.selected?.name}` : `Start ${s.selected?.name}`);+ els.power.disabled = busyPower;+}++function renderBalance(s) {+ const w = s.wallet;+ els.sol.className = 'num';+ if (!s.selected) {+ els.sol.textContent = s.syncedAt ? 'No agent' : '';+ els.unit.hidden = true;+ els.addr.hidden = true;+ return;+ }+ els.unit.hidden = false;+ if (!w) {+ els.sol.className = 'num sk';+ els.sol.textContent = '0.000';+ els.sol.style.color = 'transparent';+ els.addr.hidden = true;+ return;+ }+ els.sol.style.color = '';+ const sol = formatSol(w.sol);+ els.sol.textContent = sol ?? '--';+ els.unit.textContent = sol == null ? '' : 'SOL';+ const address = w.address || s.selected.solanaAddress;+ els.addr.hidden = !address;+ if (address) {+ els.addr.textContent = w.error ? `${shortAddress(address)} · balance unavailable` : shortAddress(address);+ els.addr.dataset.address = address;+ }+}++function renderApproval(s) {+ const first = s.pending[0];+ els.approval.hidden = !first;+ if (!first) return;+ const more = s.pending.length - 1;+ els.approval.replaceChildren(+ el('div', { className: 'row' },+ el('div', {}, el('b', { textContent: `${first.agentName} needs your approval${more ? ` (+${more} more)` : ''}` }), el('p', { textContent: first.text || `Hash ${first.hash}` })),+ Object.assign(el('button', { type: 'button', className: 'btn', textContent: 'Review' }), { onclick: () => window.panel.review(first.id).catch(showError) }),+ ),+ );+}++function renderTiles(s) {+ const local = s.local.summary;+ const tiles = [];+ tiles.push(tile('Local agents', local.total ? (local.allPaused ? 'Paused' : `${local.total - local.paused} running`) : 'None', {+ tone: local.total && !local.allPaused ? 'ok' : '',+ disabled: !local.total,+ title: local.total ? (local.action === 'resume' ? 'Resume all local agents' : 'Pause all local agents') : 'Create a local agent in the console',+ onClick: () => window.panel.toggleLocal().catch(showError),+ }));+ tiles.push(tile('Approvals', s.pending.length ? `${s.pending.length} waiting` : 'All clear', {+ tone: s.pending.length ? 'warn' : '',+ onClick: () => (s.pending.length ? window.panel.review(s.pending[0].id) : window.panel.open('wallet')).catch(showError),+ }));+ tiles.push(tile('Alerts', s.unread ? `${s.unread} unread` : 'None', { tone: s.unread ? 'warn' : '', onClick: () => window.panel.open('notifications').catch(showError) }));+ els.tiles.replaceChildren(...tiles);+}++function renderFooter(s) {+ els.sync.dataset.busy = String(Boolean(s.syncing));+ els.sync.dataset.error = String(Boolean(s.syncError));+ els.sync.textContent = s.syncing ? 'Syncing...' : s.syncError ? `Offline: ${s.syncError}` : s.syncedAt ? `Synced ${ago(s.syncedAt)}` : '';+ els.sync.title = s.syncError ? 'Click refresh by reopening the panel' : '';+}++function render(next) {+ state = next;+ els.panel.hidden = !next.signedIn;+ els.signin.hidden = next.signedIn;+ els.panel.setAttribute('aria-busy', String(next.syncing && !next.syncedAt));+ if (!next.signedIn) return;+ mountEmbed(next.apiBase, next.selected?.id);+ renderPicker(next);+ renderHeader(next);+ els.face.textContent = next.face.label;+ els.face.dataset.tone = next.face.tone;+ renderBalance(next);+ els.companion.checked = next.companion.enabled;+ renderApproval(next);+ renderTiles(next);+ els.askInput.placeholder = next.selected ? `Ask ${next.selected.name}` : 'Ask your agent';+ els.askInput.disabled = !next.selected;+ els.askSend.disabled = !next.selected || Boolean(activeAsk);+ renderFooter(next);+ applyGesture();+}++// ── Actions ─────────────────────────────────────────────────────────────────++function showReply(text, kind = '', who = '') {+ els.reply.hidden = !text;+ els.reply.dataset.state = kind;+ els.reply.replaceChildren(...(who ? [el('span', { className: 'who', textContent: who })] : []), document.createTextNode(text));+ els.reply.scrollTop = els.reply.scrollHeight;+}++function showError(err) {+ showReply(err?.message || 'Something went wrong', 'error');+}++els.picker.addEventListener('change', () => window.panel.select(els.picker.value).catch(showError));++els.power.addEventListener('click', async () => {+ const s = state?.selected;+ if (!s || busyPower) return;+ busyPower = true;+ els.power.disabled = true;+ try {+ await window.panel.setAgentRunning(s.id, !agentPower(s).on);+ } catch (err) {+ showError(err);+ } finally {+ busyPower = false;+ if (state) renderHeader(state);+ }+});++els.companion.addEventListener('change', () => window.panel.setCompanion(els.companion.checked).catch((err) => {+ els.companion.checked = !els.companion.checked;+ showError(err);+}));++els.addr.addEventListener('click', async () => {+ const address = els.addr.dataset.address;+ if (!address) return;+ try {+ await navigator.clipboard.writeText(address);+ const prev = els.addr.textContent;+ els.addr.textContent = 'Copied';+ setTimeout(() => {+ els.addr.textContent = prev;+ }, 1200);+ } catch {+ showReply(address, '', 'Wallet address');+ }+});++els.ask.addEventListener('submit', async (e) => {+ e.preventDefault();+ const message = els.askInput.value.trim();+ if (!message || activeAsk) return;+ els.askSend.disabled = true;+ showReply('Thinking...', '', state?.selected?.name || '');+ try {+ const { requestId } = await window.panel.ask(message);+ activeAsk = { requestId, text: '' };+ els.askInput.value = '';+ } catch (err) {+ els.askSend.disabled = false;+ showError(err);+ }+});++window.panel.onChat((evt) => {+ if (!activeAsk || evt.requestId !== activeAsk.requestId) return;+ const who = state?.selected?.name || '';+ if (evt.type === 'chunk') {+ activeAsk.text += evt.text;+ showReply(activeAsk.text, '', who);+ } else if (evt.type === 'done' && evt.reply) {+ activeAsk.text = evt.reply;+ showReply(evt.reply, '', who);+ } else if (evt.type === 'error') {+ showReply(evt.message || 'The agent could not answer. Try again.', 'error');+ } else if (evt.type === 'end') {+ activeAsk = null;+ if (state) els.askSend.disabled = !state.selected;+ }+});++$('open-console').addEventListener('click', () => window.panel.open().catch(showError));+$('signin-btn').addEventListener('click', () => window.panel.open().catch(showError));++window.addEventListener('keydown', (e) => {+ if (e.key === 'Escape') window.panel.hide();+});++setInterval(() => {+ if (state?.signedIn) renderFooter(state);+}, 15_000);++window.panel.onState(render);+window.panel.onShow((s) => {+ render(s);+ if (!els.askInput.disabled) els.askInput.focus();+});+window.panel.state().then(render).catch(showError);diff --git a/docs/desktop-menu-bar-panel.md b/docs/desktop-menu-bar-panel.mdnew file mode 100644index 000000000..25f93f2f0--- /dev/null+++ b/docs/desktop-menu-bar-panel.md@@ -0,0 +1,52 @@+# Menu bar panel (three.ws desktop app)++Click the three.ws icon in the macOS menu bar (or the Windows tray) and a small+panel drops down with your agent alive in 3D and the numbers you would+otherwise open the console for. Right-click the icon for the full menu.++## What it shows++- **Your agent, in 3D.** The published walk embed, loaded for the selected+ agent and driven over its documented postMessage contract (the same one the+ desktop companion uses), so the panel carries no 3D code. The avatar reacts+ to the local runtime: it waves when something needs your approval, walks while+ agents work, and stands idle otherwise.+- **Wallet balance.** SOL in the selected agent's Solana wallet, with a+ click-to-copy address. If the balance cannot be read the address stays and the+ panel says so.+- **Start and stop.** The power button starts or stops the selected cloud agent+ (`POST /api/v1/agents/:id/start|stop`).+- **Local agents.** One tile pauses or resumes every local agent.+- **Approvals.** A card appears when a local agent is waiting on you. Review+ opens the same native confirmation dialog the tray uses. The panel has no+ approve call: the dialog is built in the main process from the stored+ approval and its hash, so what you approve is what you were shown.+- **Alerts.** Unread notification count, one click to the inbox.+- **Companion.** A switch for the on-screen companion character.+- **Ask.** A one-line box that sends a message to the selected agent and shows+ the reply, using the same chat endpoint as the console.++On macOS the menu bar title shows how many approvals are waiting (or the unread+count) next to the icon, and nothing when there is nothing to do. The balance is+deliberately not shown in the menu bar, so a shared screen never leaks it.++## How it works++| Piece | File |+| --- | --- |+| Pure logic (placement, avatar state, formatting) | `apps/desktop/src/panel/model.js` |+| Window, data aggregation, IPC | `apps/desktop/src/main/panel.js` |+| Sandboxed bridge | `apps/desktop/src/panel-preload.cjs` |+| Renderer | `apps/desktop/src/panel/{index.html,panel.css,panel.js}` |++The main process builds one snapshot from caches (cloud agents, wallet, local+runtime, unread, companion) and pushes it on every change. The network-backed+parts refresh when the panel opens, every 45 seconds while it is open and every+five minutes while it is closed. The panel hides on blur and positions itself+under the icon (above a taskbar), clamped to the display's work area. On Linux,+where the OS reports no icon bounds, it anchors at the cursor and the tray menu+stays attached to the icon.++Signed out, the panel shows a sign-in prompt that opens the console.++Tests: `tests/desktop-panel.test.js`.diff --git a/tests/desktop-panel.test.js b/tests/desktop-panel.test.jsnew file mode 100644index 000000000..9823a2690--- /dev/null+++ b/tests/desktop-panel.test.js@@ -0,0 +1,131 @@+import { describe, it, expect } from 'vitest';+import {+ placePanel,+ anchorFor,+ shouldOpenOnClick,+ faceView,+ trayTitle,+ trayTooltip,+ formatSol,+ shortAddress,+ ago,+ agentPower,+ localSummary,+ PANEL_WIDTH,+ PANEL_HEIGHT,+} from '../apps/desktop/src/panel/model.js';++const size = { width: PANEL_WIDTH, height: PANEL_HEIGHT };+const screen = { x: 0, y: 25, width: 1440, height: 875 };++describe('menu bar panel placement', () => {+ it('drops below a menu bar icon, centered on it', () => {+ const r = placePanel({ x: 1000, y: 0, width: 24, height: 24 }, size, screen);+ expect(r.y).toBe(33);+ expect(r.x + r.width / 2).toBeCloseTo(1012, -1);+ });++ it('opens above a taskbar icon', () => {+ const r = placePanel({ x: 1300, y: 876, width: 24, height: 24 }, size, { x: 0, y: 0, width: 1440, height: 870 });+ expect(r.y + r.height).toBeLessThanOrEqual(870 - 8);+ expect(r.y).toBeLessThan(876);+ });++ it('stays inside the work area at the right edge', () => {+ const r = placePanel({ x: 1430, y: 0, width: 10, height: 24 }, size, screen);+ expect(r.x + r.width).toBeLessThanOrEqual(1440 - 8);+ });++ it('stays inside the work area at the left edge', () => {+ expect(placePanel({ x: 0, y: 0, width: 10, height: 24 }, size, screen).x).toBe(8);+ });++ it('shrinks to fit a short display', () => {+ const r = placePanel({ x: 500, y: 0, width: 24, height: 24 }, size, { x: 0, y: 25, width: 1280, height: 400 });+ expect(r.height).toBe(384);+ expect(r.y + r.height).toBeLessThanOrEqual(425);+ });++ it('falls back to the cursor when the OS reports no tray bounds (Linux)', () => {+ expect(anchorFor({ x: 0, y: 0, width: 0, height: 0 }, { x: 900, y: 10 })).toEqual({ x: 900, y: 10, width: 1, height: 1 });+ expect(anchorFor(undefined, { x: 5, y: 6 })).toEqual({ x: 5, y: 6, width: 1, height: 1 });+ const bounds = { x: 1, y: 2, width: 3, height: 4 };+ expect(anchorFor(bounds, { x: 9, y: 9 })).toBe(bounds);+ });++ it('does not reopen on the click that just closed it', () => {+ expect(shouldOpenOnClick(1000, 1100)).toBe(false);+ expect(shouldOpenOnClick(1000, 1400)).toBe(true);+ expect(shouldOpenOnClick(0, 5)).toBe(true);+ });+});++describe('menu bar panel avatar and tray state', () => {+ it('waves when something needs approval and walks while working', () => {+ expect(faceView({ state: 'waiting_approval' }).gesture).toBe('wave');+ expect(faceView({ state: 'working' }).gesture).toBe('walk');+ expect(faceView({ state: 'error' }).tone).toBe('bad');+ });++ it('has a view for no local agents and for an unknown state', () => {+ expect(faceView({ state: 'none' }).key).toBe('none');+ expect(faceView(undefined).key).toBe('none');+ expect(faceView({ state: 'mystery' }).key).toBe('none');+ });++ it('puts approvals ahead of unread in the menu bar title', () => {+ expect(trayTitle({ pendingApprovals: 2, unread: 9 })).toBe('2 to approve');+ expect(trayTitle({ unread: 4 })).toBe('4');+ expect(trayTitle({ unread: 250 })).toBe('99+');+ expect(trayTitle({})).toBe('');+ });++ it('writes a tooltip for every signed-in state', () => {+ expect(trayTooltip({ signedIn: false })).toBe('three.ws Desktop: Not signed in');+ expect(trayTooltip({ signedIn: true, name: 'Ada', pendingApprovals: 1, unread: 3 })).toBe('three.ws Desktop: Ada, 1 awaiting approval, 3 unread');+ });+});++describe('menu bar panel formatting', () => {+ it('formats balances at every scale', () => {+ expect(formatSol(0)).toBe('0');+ expect(formatSol(0.0123456)).toBe('0.0123');+ expect(formatSol(1.23456)).toBe('1.235');+ expect(formatSol(12345.6)).toBe('12,346');+ expect(formatSol(null)).toBeNull();+ expect(formatSol(undefined)).toBeNull();+ expect(formatSol('abc')).toBeNull();+ });++ it('shortens addresses and leaves short strings alone', () => {+ expect(shortAddress('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump')).toBe('FeMb...pump');+ expect(shortAddress('abc')).toBe('abc');+ expect(shortAddress(null)).toBe('');+ });++ it('words elapsed time', () => {+ const now = 1_000_000;+ expect(ago(now - 2000, now)).toBe('just now');+ expect(ago(now - 42_000, now)).toBe('42s ago');+ expect(ago(now - 5 * 60_000, now)).toBe('5m ago');+ expect(ago(now - 3 * 3_600_000, now)).toBe('3h ago');+ expect(ago(null, now)).toBeNull();+ });+});++describe('menu bar panel agent controls', () => {+ it('reads the cloud lifecycle', () => {+ expect(agentPower({ status: 'running' })).toMatchObject({ on: true, known: true });+ expect(agentPower({ status: 'stopped' })).toMatchObject({ on: false, known: true });+ expect(agentPower({ status: 'draft' }).known).toBe(false);+ expect(agentPower({ status: null, isPublished: true })).toMatchObject({ on: true, known: false, label: 'Live' });+ expect(agentPower(null).label).toBe('No agent');+ });++ it('decides whether the local tile pauses or resumes', () => {+ expect(localSummary([])).toMatchObject({ total: 0, action: 'pause', allPaused: false });+ expect(localSummary([{ status: 'idle' }, { status: 'paused' }])).toMatchObject({ total: 2, paused: 1, action: 'pause' });+ expect(localSummary([{ status: 'paused' }, { status: 'paused' }])).toMatchObject({ allPaused: true, action: 'resume' });+ expect(localSummary([{ status: 'paused' }, { status: 'killed' }])).toMatchObject({ total: 1, allPaused: true });+ });+});