Spaces:
Running
Running
update
Browse filesFiles changed (3)
- README.md+39-10
- index.html+192-392
- style.css+2-90
6 unmodified lines7891011121 unmodified line141516171819202122232425262728293031323334356 unmodified linespinned: falsehf_oauth: truehf_oauth_expiration_minutes: 480tags:- reachy_mini- reachy_mini_js_app1 unmodified line# Reachy Mini WebRTC DemoWebRTC dashboard to connect to your Reachy Mini robot via the central signaling server.## Features- Video streaming from robot camera- Head control via data channel- HuggingFace OAuth authentication## How it works1. Sign in with your HuggingFace account2. Connect to the central signaling server3. Select your robot from the list4. Start the video stream## Requirements- Robot must be running with WebRTC enabled and connected to the central signaling server- Robot must have a valid HuggingFace token configured6 unmodified lines789101112131 unmodified line15161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646 unmodified linespinned: falsehf_oauth: truehf_oauth_expiration_minutes: 480short_description: Single-file WebRTC demo — sign in with HF, drive the robot.tags:- reachy_mini- reachy_mini_js_app1 unmodified line# Reachy Mini WebRTC DemoSingle-file (`index.html` + `style.css`) WebRTC demo for Reachy Mini.No build step, no bundler — drop it on a Hugging Face Space with`sdk: static` and you're done.Boots on the modern **host-shell** pattern documented in[`ts/APP_CREATION_GUIDE.md`](https://github.com/pollen-robotics/reachy_mini/blob/main/ts/APP_CREATION_GUIDE.md):- The host shell (loaded from jsDelivr on a standalone visit) ownsHF OAuth + robot picker + the connect / leave button. No morehand-rolled login screen here.- The post-connect UI (sliders, audio, sound, animations, torque,volume, daemon logs) lives in this page's markup and runs insidethe host's iframe via `connectToHost()`. Same features as before.## Features- Video streaming from the robot's camera- Head RPY sliders, body yaw (tank-coupled), antennas- Wake up / go to sleep / torque toggle- Sound playback (free-text + presets)- Speaker volume sync- Mic + speaker mute toggles- Live latency badge (RTT / buffer / jitter, colour-coded)- Daemon `journalctl` stream over the WebRTC data channel## How it works1. Visit the Space — the host shell renders sign-in.2. Sign in with Hugging Face (OAuth).3. The shell lists your reachable robots; pick one.4. The shell wakes the robot and iframes this page at`?embedded=1`.5. All the controls below light up.## Requirements- Robot online on the central signaling server.- Robot daemon recent enough to expose `subscribeLogs`, `getVolume`,`wakeUp`, `gotoSleep`, `setMotorMode` over the data channel(anything ≥ 1.8 should be fine).## SDK pin`@pollen-robotics/reachy-mini-sdk@1.8.0-rc1-main.fd4354c`, loadedfrom `cdn.jsdelivr.net`. Same exact pin as the three Pollenreference apps — mixing versions across the SDK, host shell, anddaemon causes silent protocol drift (see APP_CREATION_GUIDE §10).
8 unmodified lines910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273742 unmodified lines777879808182838485868716 unmodified lines10410510610710810911011111211311411511611711811927 unmodified lines147148149150151152153154155156157158159160161113 unmodified lines2752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713 unmodified lines37537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950011 unmodified lines512513514515516517518519520521522523168 unmodified lines69269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982057 unmodified lines8788798808818828838848858868878888898908918928 unmodified lines<link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet"><link rel="stylesheet" href="style.css"><!-- Kick off both JS modules during HTML parse so they're in flightbefore the bottom-of-body <script> executes. The embed entrypulls two hashed chunks of its own which we can't preload(the hashes drift across SDK releases), but front-loading thetwo top-level modules still shaves ~hundreds of ms off a coldCDN edge. --><link rel="modulepreload" href="https://cdn.jsdelivr.net/npm/@pollen-robotics/reachy-mini-sdk@1.7.3-main.7654ffe/+esm" crossorigin><link rel="modulepreload" href="https://cdn.jsdelivr.net/npm/@pollen-robotics/reachy-mini-sdk@1.7.3-main.7654ffe/host/dist/entry/embed.js" crossorigin><!-- Inline pre-paint script: if we're loaded as an iframe embed,flip the DOM directly to the connected-shell view + a"Connecting…" status pill BEFORE the JS module startsrunning. Skips the visual flash of the Sign-in button whileconnectToHost is busy doing its OAuth round-trip + WebRTChandshake (which can be 3-8 s on a cold network). The scriptruns after </head> only because the elements it touches arein <body>; the cost of moving this script to a `defer="false"`block at the start of <body> is one DOM-ready paint that wealready pay for. --><script>(function () {try {const params = new URLSearchParams(window.location.search);if (params.get('embedded') !== '1') return;// Defer the DOM mutations until after the elements// exist (we're parsed before <body>). DOMContentLoaded// fires once the body is done parsing — cheap, no UX// cost vs. the seconds-long connectToHost.document.addEventListener('DOMContentLoaded', function () {const login = document.getElementById('loginView');const main = document.getElementById('mainApp');const statusText = document.getElementById('statusText');const statusIndicator = document.getElementById('statusIndicator');if (login) login.classList.add('hidden');if (main) main.classList.remove('hidden');if (statusIndicator) statusIndicator.className = 'status-indicator connecting';if (statusText) statusText.textContent = 'Connecting…';});} catch (e) {// Best-effort UX polish — never block boot.}})();</script></head><body><!-- Login View --><div id="loginView" class="login-view"><div class="login-card"><img class="login-logo" src="https://raw.githubusercontent.com/pollen-robotics/reachy-mini-desktop-app/develop/src-tauri/icons/128x128.png" alt="Reachy Mini"><h2>Reachy Mini</h2><p>Sign in with your HuggingFace account to connect and control your robot remotely.</p><button class="btn-hf" onclick="loginToHuggingFace()"><svg width="18" height="18" viewBox="0 0 95 88" fill="currentColor"><path d="M47.5 0C26.3 0 9.1 17.2 9.1 38.4v2.9c0 4.5 1.1 9 3.2 13L0 88h95L82.7 54.3c2.1-4 3.2-8.5 3.2-13v-2.9C85.9 17.2 68.7 0 47.5 0z"/></svg>Sign in with Hugging Face</button></div></div><!-- Main App --><div id="mainApp" class="hidden"><header class="header"><div class="logo">2 unmodified lines</div><div class="user-section"><!-- Daemon version is filled in once the WebRTC data channelis open (via robot.getVersion()). Hidden until then sowe don't show a stale/empty badge during connect. --><div id="daemonVersion" class="user-badge hidden" title="Daemon version"></div><div class="user-badge"><span id="username">@user</span></div><button class="btn-logout" onclick="logout()">Sign out</button></div></header>16 unmodified lines<div class="video-overlay-bottom"><div class="video-controls"><!--Connect button drives the all-in-one autoConnect()flow: SSE → robot selection (auto-pick if one free,else pickRobot callback opens the panel) →startSession → ensureAwake. The legacy two-stepConnect+Start split is gone; Start is kept hiddenfor any consumer still wiring against #startBtn.--><button class="btn btn-primary" id="connectBtn" onclick="connectAndStream()">Connect</button><button class="btn btn-primary hidden" id="startBtn" onclick="startStream()" disabled>Start</button><button class="btn btn-danger" id="stopBtn" onclick="stopStream()" disabled>Stop</button><button class="btn btn-mute muted" id="muteBtn" onclick="toggleMute()" disabled><svg id="speakerOffIcon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon>27 unmodified lines</div><!-- Robot Selector --><div id="robotSelector" class="panel hidden"><div class="panel-header">Available Robots</div><div class="panel-content"><div id="robotList" class="robot-list"><div style="color: var(--text-muted); font-size: 0.85em;">Searching...</div></div></div></div><!-- Head Control - RPY Sliders --><div class="panel">113 unmodified lines</div><script type="module">// Both imports below pull from the same npm package version:// @pollen-robotics/reachy-mini-sdk@1.7.3-main.7654ffe.//// The package exports:// - `.` (root) → reachy-mini-sdk.js (the SDK runtime:// ReachyMini class,// matrix/RPY helpers,// autoConnect, etc.)// - `./host/embed` → host/dist/entry/embed.js (the embed-// side helper that// decodes `#creds=`// and runs auth +// startSession +// ensureAwake)//// The 1.7.3 stable tag publishes ONLY the root (no `host/` subpath// yet), so we use the `1.7.3-main.<sha>` prerelease auto-published// by CI on every push to main. Pin to a specific `<sha>` (the// mobile app pins the same in lockstep). Bump when a stable that// ships `host/` lands on npm.//// SDK URL ends with `/+esm` (a jsdelivr-specific endpoint) rather// than the literal `dist/reachy-mini-sdk.js`. `/+esm` runs a Rollup// + Terser pass on jsdelivr's edge that inlines the SDK's bare// npm dependencies (currently `@huggingface/hub` for OAuth) into a// single self-contained ESM bundle. Without it, the browser fails// on `import "@huggingface/hub"` (bare specifiers don't resolve in// browser-direct ESM without a bundler or import map). The host// bundle is already Vite-built and self-contained, so it points// at the raw `host/dist/entry/embed.js` path directly.//// jsdelivr serves npm versions directly — no manual purge needed// when bumping the pin (npm tarballs are immutable, the CDN edge// refreshes naturally for each new version string).import { ReachyMini, matrixToRpy, radToDeg, rpyToMatrix, degToRad } from "https://cdn.jsdelivr.net/npm/@pollen-robotics/reachy-mini-sdk@1.7.3-main.7654ffe/+esm";// Host-embed entry. Loading this module side-effect-installs// `window.ReachyMini` (if unset) and exposes `connectToHost`,// which decodes the `#creds=<base64>` bundle the mobile shell// writes into the URL hash, instantiates the SDK against those// creds, and runs auth + startSession + ensureAwake before// resolving. Standalone visits never touch it — the dispatcher// below branches on `?embedded=1`.import { connectToHost } from "https://cdn.jsdelivr.net/npm/@pollen-robotics/reachy-mini-sdk@1.7.3-main.7654ffe/host/dist/entry/embed.js";// `let` (not `const`) because the embed path below replaces this// module-level SDK with the live instance returned by// connectToHost(). The pre-constructed object is harmless: its// ctor doesn't open sockets, so dropping it on the floor in// embed mode is fine.let robot = new ReachyMini({appName: "Reachy Mini WebRTC Demo",// Pin the org-owned canonical central. The SDK default// still tracks an older instance, so we keep this// explicit for self-documentation.signalingUrl: 'https://pollen-robotics-reachy-mini-central.hf.space',// NB: `autoStartFromUrl: true` is intentionally NOT set.// We use `autoConnect()` for embed bring-up; both running// at once raced two `startSession()` calls against the// same preselected robot, with central rejecting the// second one as "Robot is busy: <our own appName>". The// SDK now defensively suppresses `autoStartFromUrl` while// `autoConnect()` is in-flight, so this is just docs and// belt-and-suspenders.});let selectedRobotId = null;let headSlidersActive = false;let bodyYawSliderActive = false;// Last body yaw the user committed via the slider, in degrees.// Used to compute the delta we need to subtract from the head yaw// command so the head visually fixates a point in world frame// while the base rotates.let lastBodyYawDeg = 0;let detachVideo = null;let latencyIntervalId = null;// Returned by robot.subscribeLogs(); call to stop the daemon-side// journalctl stream. Reset on every sessionStopped.let logsUnsub = null;// Cap the logs panel so a long session doesn't grow without bound.const LOGS_MAX_LINES = 500;// Export functions for inline onclick handlerswindow.loginToHuggingFace = () => robot.login();window.logout = logout;window.connectAndStream = connectAndStream;// Kept exported for any deep-link / debugger script that still// pokes them by name — the in-app buttons now route through// connectAndStream() instead.window.connectSignaling = connectAndStream;window.startStream = connectAndStream;window.stopStream = stopStream;window.playSound = playSound;window.playSoundPreset = playSoundPreset;window.playWakeUp = playWakeUp;3 unmodified lineswindow.toggleMic = toggleMic;window.clearLogs = clearLogs;document.addEventListener('DOMContentLoaded', async () => {// Dispatcher: `?embedded=1` means we're loaded inside the// mobile-app shell's iframe. The shell passes credentials// in the URL hash as a base64 `creds=` bundle (token +// username + robotPeerId + signalingUrl + theme + config).// We hand control to `connectToHost`, which decodes that// bundle and brings the WebRTC session up before resolving.// Standalone visits fall through to the existing// authenticate() → user-driven Connect flow.const isEmbed =new URLSearchParams(window.location.search).get('embedded') === '1';if (isEmbed) {try {const handle = await connectToHost();// Swap the module-level SDK for the live instance// the host handed back. All closures below that// call `robot.*` resolve `robot` at call time, so// they pick up the new value automatically.robot = handle.reachy;// The host attached the inbound track on the// handle's media surface; replay it into our <video>.handle.media.attachVideo(document.getElementById('remoteVideo'));initSliders();initRobotEvents();showMainApp();// The session is already up. Flip the UI directly// to the "connected" visual state — same set of// toggles the `streaming` event handler runs in// the standalone flow.document.getElementById('robotSelector').classList.add('hidden');updateStatus('connected', 'Connected');enableControls(true);document.getElementById('connectBtn').disabled = true;document.getElementById('stopBtn').disabled = false;startLatencyDisplay();fetchDaemonVersionOnce();syncVolumeSlider();startLogsStream();} catch (err) {console.error('[embed] connectToHost failed:', err);updateStatus('','Embed connect failed: ' + (err?.message || err),);}return;}// Standalone path — unchanged behaviour. Bind the <video>// sink eagerly (attachVideo is lazy: it remembers the// element and wires the inbound track when it arrives),// then run authenticate(). Falls through to the login// screen when no cached token is found.initSliders();initRobotEvents();detachVideo = robot.attachVideo(document.getElementById('remoteVideo'));if (await robot.authenticate()) {showMainApp();} else {showLogin();}});// ===================== Auth =====================function logout() {if (detachVideo) { detachVideo(); detachVideo = null; }robot.logout();showLogin();}function showLogin() {document.getElementById('loginView').classList.remove('hidden');document.getElementById('mainApp').classList.add('hidden');}function showMainApp() {document.getElementById('loginView').classList.add('hidden');document.getElementById('mainApp').classList.remove('hidden');document.getElementById('username').textContent = '@' + robot.username;}// ===================== Robot Events =====================function initRobotEvents() {// The SSE `list` push fires on every producer come-and-go.// We don't drive selection from it any more — autoConnect's// pickRobot callback owns the picker render — but we still// dim cards whose robot dropped off while the panel is open.robot.addEventListener('robotsChanged', (e) => refreshPickerOnList(e.detail.robots));robot.addEventListener('streaming', () => {updateStatus('connected', 'Connected');enableControls(true);document.getElementById('connectBtn').disabled = true;document.getElementById('stopBtn').disabled = false;document.getElementById('robotSelector').classList.add('hidden');startLatencyDisplay();// Data channel is open — fetch daemon version (one-shot) and// sync the volume slider to the robot's current level. Both// swallow failures so a missing command handler or an// unsupported audio platform doesn't break the UI.// Wake/torque is already handled inside autoConnect() —// no ensureAwakeOnce() call needed here.fetchDaemonVersionOnce();syncVolumeSlider();startLogsStream();});robot.addEventListener('sessionStopped', (e) => {document.getElementById('connectBtn').disabled = false;document.getElementById('stopBtn').disabled = true;document.getElementById('robotSelector').classList.remove('hidden');enableControls(false);// e.detail.message is set when the stop was server-initiated (e.g.// a local Python app took over the robot). null for user-initiated.updateStatus('connected', e.detail?.message || 'Connected');updateMicButton();stopLatencyDisplay();// Disable the volume slider and clear the version pill — they// only make sense while the data channel is open.document.getElementById('volumeSlider').disabled = true;document.getElementById('volumeValue').textContent = '--';document.getElementById('daemonVersion').classList.add('hidden');11 unmodified linesenableControls(robot.state === 'streaming');});robot.addEventListener('disconnected', () => {updateStatus('', 'Disconnected');document.getElementById('connectBtn').disabled = false;document.getElementById('robotSelector').classList.add('hidden');});robot.addEventListener('error', (e) => {console.error(`[${e.detail.source}]`, e.detail.error);if (e.detail.source === 'webrtc') {168 unmodified lines});})();// All-in-one: auth (cached) → SSE → robot selection → session →// wake. Replaces the previous "Connect → pick robot → Start"// three-step flow with a single button.//// In standalone mode autoConnect() invokes our `pickRobot`// callback when there is more than one free robot; we render// the panel and resolve the Promise on user click.//// In embed mode autoConnect detects `isEmbedded` and skips the// picker entirely — the preselected robot id is used directly.async function connectAndStream() {if (!robot.isAuthenticated) return;if (typeof robot.autoConnect !== 'function') {console.error('robot.autoConnect is not a function — the reachy-mini.js ' +'lib loaded from CDN predates the autoConnect feature. ' +'Purge jsdelivr and hard-refresh the page.');updateStatus('', 'SDK too old — purge jsdelivr cache');return;}updateStatus('connecting', 'Connecting...');document.getElementById('connectBtn').disabled = true;// Re-bind the <video> sink if a previous logout() tore it// down. attachVideo() is lazy — the SDK remembers the// element and wires the inbound track when it arrives, so// calling it before autoConnect() works for both first// session and post-logout reconnects.if (!detachVideo) {detachVideo = robot.attachVideo(document.getElementById('remoteVideo'));}try {const { robotName } = await robot.autoConnect({pickRobot: presentRobotPicker,});if (robotName) {document.getElementById('robotName').textContent = robotName;}// The `streaming` event handler does the rest (status// pill, latency display, daemon version, volume sync,// logs subscription). autoConnect already called// ensureAwake() before resolving.} catch (e) {console.error('autoConnect failed:', e);// Same error taxonomy as the old startStream():// "robot_busy" → central refused: another remote JS app is connected.// "robot_busy_local_app" → relay refused: a local Python app holds the robot.// "local_app_started" → a local Python app evicted a streaming session.// "robot_busy_local" → relay safety net; another session slipped in.let msg;if (e.reason === 'robot_busy') {msg = `Robot busy — "${e.activeApp}" is already connected`;} else if ((e.reason && e.reason.startsWith('robot_busy')) || e.reason === 'local_app_started') {msg = e.message;} else {msg = e.message || String(e);}updateStatus('', msg);document.getElementById('connectBtn').disabled = false;document.getElementById('robotSelector').classList.add('hidden');}}// pickRobot callback for autoConnect(). Renders the existing// robot-selector panel and resolves with the id the user// clicks. Receives the SDK-shaped robot objects (id, name,// busy, activeApp, meta, lastSeenAgeSeconds) already filtered// to "free" and deduped by install_id.function presentRobotPicker(robots) {return new Promise((resolve) => {const panel = document.getElementById('robotSelector');const list = document.getElementById('robotList');panel.classList.remove('hidden');list.innerHTML = '';if (!robots?.length) {list.innerHTML = '<div style="color: var(--text-muted);">No robots online</div>';resolve(null);return;}for (const r of robots) {const div = document.createElement('div');div.className = 'robot-card';const subtitle = r.busy? `busy — ${r.activeApp ?? 'unknown app'}`: `${r.id.slice(0, 12)}...`;div.innerHTML = `<div class="name">${r.name || 'Reachy Mini'}</div><div class="id">${subtitle}</div>`;div.onclick = () => {if (r.busy) return; // selecting busy is a no-opdocument.querySelectorAll('.robot-card').forEach(e => e.classList.remove('selected'));div.classList.add('selected');selectedRobotId = r.id;document.getElementById('robotName').textContent = r.name || 'Reachy Mini';resolve(r.id);};list.appendChild(div);}});}// Live SSE list updates: we still refresh the in-panel list as// robots come and go, but only while the panel is visible (i.e.// we're inside an active pickRobot prompt).function refreshPickerOnList(robots) {const panel = document.getElementById('robotSelector');if (panel.classList.contains('hidden')) return;// The picker promise already resolved once — re-rendering// here would replace the click handlers with stale ones// that try to resolve an already-settled Promise. Just// visually mark the cards.const list = document.getElementById('robotList');const presentIds = new Set((robots || []).map((r) => r.id));for (const card of list.querySelectorAll('.robot-card')) {// The id snippet is in the second child — best-effort// dim cards whose robot dropped off the list.const stillPresent = Array.from(presentIds).some((id) =>card.textContent.includes(id.slice(0, 12)),);card.style.opacity = stillPresent ? '' : '0.4';}}// ===================== Latency =====================function startLatencyDisplay() {57 unmodified lines}// ===================== Session =====================// The old two-step "Connect → Start" flow is collapsed into// connectAndStream() above. Anything that used to call// startStream() now routes through connectAndStream() via the// window.startStream alias.async function stopStream() {if (detachVideo) { detachVideo(); detachVideo = null; }await robot.stopSession();}// ===================== Audio =====================function toggleMute() {8 unmodified lines9101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990912 unmodified lines94959697989910010110210310416 unmodified lines12112212312412512612712812913013113213327 unmodified lines161162163164165166167168169113 unmodified lines2832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333 unmodified lines33733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943011 unmodified lines442443444445446447168 unmodified lines61661761861962062162262362462557 unmodified lines6836846856866876886896906916928 unmodified lines<link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet"><link rel="stylesheet" href="style.css"><link rel="icon" href="https://raw.githubusercontent.com/pollen-robotics/reachy-mini-desktop-app/develop/src-tauri/icons/128x128.png" /><!-- Modern host-shell SDK entries. The standalone path loads`host/auto` (exports `mountHost`); the embed path loads`host/embed` (`connectToHost`). Same package, two entries,picked at runtime by the dispatcher at the bottom of <body>.Pinned to the exact tarball the three Pollen reference appsship against — see APP_CREATION_GUIDE §10 (mixing SDK / host /daemon versions causes silent protocol drift). --><link rel="modulepreload" href="https://cdn.jsdelivr.net/npm/@pollen-robotics/reachy-mini-sdk@1.8.0-rc1-main.fd4354c/host/dist/entry/auto.js" crossorigin><link rel="modulepreload" href="https://cdn.jsdelivr.net/npm/@pollen-robotics/reachy-mini-sdk@1.8.0-rc1-main.fd4354c/host/dist/entry/embed.js" crossorigin><!-- HF Spaces helper variables. In production (sdk: static +hf_oauth: true), HF substitutes these placeholders at file-serve time and the SDK reads them off `window.huggingface.variables`.Locally the placeholders stay raw (the leading `__` gives themaway) — we drop the global so `mountHost()` falls back to adevToken or a manually-passed clientId. --><script>(function () {var clientId = "__OAUTH_CLIENT_ID__";var scopes = "__OAUTH_SCOPES__";var spaceHost = "__SPACE_HOST__";var spaceId = "__SPACE_ID__";var looksSubstituted = clientId && clientId.indexOf("__") !== 0;if (looksSubstituted) {window.huggingface = window.huggingface || {};window.huggingface.variables = {OAUTH_CLIENT_ID: clientId,OAUTH_SCOPES: scopes && scopes.indexOf("__") !== 0 ? scopes : "openid profile",SPACE_HOST: spaceHost && spaceHost.indexOf("__") !== 0 ? spaceHost : "",SPACE_ID: spaceId && spaceId.indexOf("__") !== 0 ? spaceId : "",};}})();</script><!-- Pre-paint visibility gate. Both paths start with #mainApp hidden:- Standalone: mountHost() owns the page; #mainApp stays hidden.- Embed: #mainApp is revealed by the embed handler onceconnectToHost() resolves. While the handshake is in flightwe seed a "Connecting…" status pill so the eventual paintreads as "almost there" rather than "broken". --><script>(function () {try {document.addEventListener('DOMContentLoaded', function () {var main = document.getElementById('mainApp');if (main) main.classList.add('hidden');var params = new URLSearchParams(window.location.search);if (params.get('embedded') === '1' || params.get('embed') === '1') {var statusText = document.getElementById('statusText');var statusIndicator = document.getElementById('statusIndicator');if (statusIndicator) statusIndicator.className = 'status-indicator connecting';if (statusText) statusText.textContent = 'Connecting…';}});} catch (e) { /* best-effort polish */ }})();</script></head><body><!--Host shell mount point. On a standalone visit, `mountHost()` fromthe SDK's `host/auto` entry renders the full host UI (sign-in,robot picker, top bar, leave button) into this div, owns OAuth+ connection lifecycle, and iframes back into THIS page with`?embedded=1` once a robot is awake. We no longer hand-roll thesign-in screen, picker, or Stop button — the host owns them.--><div id="root"></div><!-- Main App — the post-connect surface. Hidden until either thehost shell shows us (standalone path, in-iframe) or the embeddispatcher resolves connectToHost() (embed path). Everythingbelow this point is unchanged feature-wise vs the originalsingle-file demo. --><div id="mainApp" class="hidden"><header class="header"><div class="logo">2 unmodified lines</div><div class="user-section"><!-- Daemon version is filled in once the WebRTC data channelis open (via reachy.getVersion()). Hidden until then sowe don't show a stale/empty badge during connect. Thehost shell's top bar shows the signed-in user + sign-outmenu, so we no longer duplicate them here. --><div id="daemonVersion" class="user-badge hidden" title="Daemon version"></div></div></header>16 unmodified lines<div class="video-overlay-bottom"><div class="video-controls"><!--Connect / Stop are gone — the host shell's topbar owns "leave session", and the iframe bootsalready-connected via connectToHost(). Only theper-direction audio toggles remain on the video,since they're local-mute settings, not sessionlifecycle.--><button class="btn btn-mute muted" id="muteBtn" onclick="toggleMute()" disabled><svg id="speakerOffIcon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon>27 unmodified lines</div><!-- Robot Selector removed — the host shell owns robotpicking. By the time the embed handler runs, thesession is already up against the chosen robot. --><!-- Head Control - RPY Sliders --><div class="panel">113 unmodified lines</div><script type="module">// ===== SDK imports (modern host-shell pattern) =====//// Three entry points from the same npm pin// (@pollen-robotics/reachy-mini-sdk@1.8.0-rc1-main.fd4354c — the// exact tarball the three Pollen reference apps ship against;// see APP_CREATION_GUIDE §10 on version drift)://// - host/dist/entry/auto.js → `mountHost` (standalone path)// - host/dist/entry/embed.js → `connectToHost` (embed path)// - root (/+esm bundled by jsdelivr) math helpers//// jsdelivr's `/+esm` endpoint inlines the SDK's bare npm deps// (notably `@huggingface/hub`) into a single self-contained// ESM bundle so the browser doesn't choke on the bare specifier.// The host bundles are already Vite-built and self-contained, so// they load straight from `host/dist/entry/*.js`.import { mountHost } from "https://cdn.jsdelivr.net/npm/@pollen-robotics/reachy-mini-sdk@1.8.0-rc1-main.fd4354c/host/dist/entry/auto.js";import { connectToHost } from "https://cdn.jsdelivr.net/npm/@pollen-robotics/reachy-mini-sdk@1.8.0-rc1-main.fd4354c/host/dist/entry/embed.js";import { matrixToRpy, radToDeg, rpyToMatrix, degToRad } from "https://cdn.jsdelivr.net/npm/@pollen-robotics/reachy-mini-sdk@1.8.0-rc1-main.fd4354c/+esm";// Live SDK instance for the running session. Set on the embed// path by `connectToHost().reachy`. All callbacks below read// `robot` at call time, so the late assignment is invisible to// them.let robot = null;// ===== Module-scope state (unchanged from the legacy demo) =====let headSlidersActive = false;let bodyYawSliderActive = false;// Last body yaw the user *committed* via the slider, in degrees.// The baseline for the tank-coupled head counter-rotation must// be the last COMMANDED value (this variable), never telemetry —// telemetry lags one WebRTC RTT, so cumulative deltas computed// against it stall under rapid drags.let lastBodyYawDeg = 0;let detachVideo = null;let latencyIntervalId = null;// Returned by reachy.subscribeLogs(); call to stop the daemon-side// journalctl stream. Reset on every leave.let logsUnsub = null;// Cap the logs panel so a long session doesn't grow without bound.const LOGS_MAX_LINES = 500;// Inline-onclick handlers. Sign-in / sign-out / connect / stop// are gone — the host shell owns them now.window.playSound = playSound;window.playSoundPreset = playSoundPreset;window.playWakeUp = playWakeUp;3 unmodified lineswindow.toggleMic = toggleMic;window.clearLogs = clearLogs;// ===== Dispatcher =====//// Standalone visit (no `?embedded=1`): mountHost() renders the// full host shell into #root. The shell handles HF OAuth + robot// picker + the leave button, and once a robot is awake it iframes// THIS page at `?embedded=1`. No further JS in this module runs// in the outer document.//// Embed visit: connectToHost() decodes the hash creds, brings// the WebRTC session up, wakes the robot, and resolves with a// typed handle. We replay its video+audio into our <video>, then// wire the legacy slider / sound / log / latency UI exactly as// before.document.addEventListener('DOMContentLoaded', async () => {const params = new URLSearchParams(window.location.search);const isEmbed = params.get('embedded') === '1' || params.get('embed') === '1';if (!isEmbed) {mountHost({appName: 'Reachy Mini WebRTC Demo',appIconUrl: 'https://raw.githubusercontent.com/pollen-robotics/reachy-mini-desktop-app/develop/src-tauri/icons/128x128.png',appEmoji: '🤖',// We use the robot's mic in the audio toggles; the host// needs to know so it negotiates an inbound audio track.enableMicrophone: true,});return;}try {const handle = await connectToHost();robot = handle.reachy;// The host bridge captured the inbound video+audio tracks// during boot; replay them into our <video>. attachVideo// returns a cleanup we hold for the onLeave teardown.detachVideo = handle.media.attachVideo(document.getElementById('remoteVideo'));// Wire all the post-connect UI. Order matters: bind the// event listeners FIRST so we don't miss the `state` /// `micSupported` ticks that fire right after the session// is already up.initRobotEvents();initSliders();showMainApp();updateStatus('connected', 'Connected');enableControls(true);startLatencyDisplay();fetchDaemonVersionOnce();syncVolumeSlider();startLogsStream();// Host-requested leave (user clicks the top-bar leave// button, or page lifecycle tears down). Best-effort// cleanup — the iframe is about to be unmounted anyway.handle.onLeave(() => {try { if (detachVideo) detachVideo(); } catch (_) {}detachVideo = null;stopLatencyDisplay();stopLogsStream();});} catch (err) {console.error('[embed] connectToHost failed:', err);updateStatus('', 'Embed connect failed: ' + (err?.message || err));}});function showMainApp() {document.getElementById('mainApp').classList.remove('hidden');}// ===================== Robot Events =====================//// We only bind the events that drive *in-iframe* UI (state echo,// mic-support gate, telemetry-driven slider sync, server-initiated// session-stop messages). Sign-in / picker / connect-button state// events are gone — the host shell handles them outside the iframe.function initRobotEvents() {robot.addEventListener('sessionStopped', (e) => {enableControls(false);// e.detail.message is set when the stop was server-initiated// (e.g. a local Python app took over the robot). Surfaced in// the in-iframe status pill so the user has a reason for the// sudden silence.updateStatus('connected', e.detail?.message || 'Session ended');updateMicButton();stopLatencyDisplay();// Disable the volume slider and clear the version pill —// they only make sense while the data channel is open.document.getElementById('volumeSlider').disabled = true;document.getElementById('volumeValue').textContent = '--';document.getElementById('daemonVersion').classList.add('hidden');11 unmodified linesenableControls(robot.state === 'streaming');});robot.addEventListener('error', (e) => {console.error(`[${e.detail.source}]`, e.detail.error);if (e.detail.source === 'webrtc') {168 unmodified lines});})();// Connection bring-up (auth, picker, session start, wake) is// owned by the host shell now — see `mountHost()` in the// dispatcher above. The legacy `connectAndStream` /// `presentRobotPicker` / `refreshPickerOnList` helpers are gone.// ===================== Latency =====================function startLatencyDisplay() {57 unmodified lines}// ===================== Session =====================// Session lifecycle (start / stop / wake / sleep on leave) lives// in the host shell. The iframe receives an already-connected,// already-awake handle via connectToHost(). The `handle.onLeave()`// wired in the dispatcher above is our only teardown hook.// ===================== Audio =====================function toggleMute() {
341 unmodified lines34234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938010 unmodified lines39139239339439539639739839940040110 unmodified lines412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467341 unmodified linescolor: var(--pollen-coral);}/* Robot Selector */.robot-list {display: flex;flex-direction: column;gap: 8px;}.robot-card {padding: 10px 14px;background: var(--pollen-darker);border: 2px solid transparent;border-radius: 8px;cursor: pointer;}.robot-card:hover {background: var(--pollen-card-light);}.robot-card.selected {border-color: var(--pollen-coral);}.robot-card .name {font-weight: 600;font-size: 0.9em;}.robot-card .id {font-size: 0.75em;color: var(--text-muted);font-family: monospace;}/* Desktop Layout - Side by Side */@media (min-width: 900px) {10 unmodified linesgrid-row: 1 / 3;}#robotSelector {grid-column: 1;grid-row: 3;}.panel:nth-of-type(1) { /* Head Control */grid-column: 2;grid-row: 1;10 unmodified lines}}/* Login View */.login-view {min-height: 100vh;min-height: 100dvh;display: flex;align-items: center;justify-content: center;padding: 20px;}.login-card {background: var(--pollen-card);padding: 40px;border-radius: 16px;text-align: center;max-width: 380px;}.login-logo {width: 72px;height: 72px;margin-bottom: 20px;border-radius: 12px;}.login-card h2 {color: var(--pollen-coral);margin-bottom: 10px;font-size: 1.5em;}.login-card p {color: var(--text-secondary);margin-bottom: 24px;font-size: 0.9em;line-height: 1.5;}.btn-hf {background: #FFD21E;color: #000;border: none;padding: 12px 28px;border-radius: 8px;font-size: 0.95em;font-weight: 700;cursor: pointer;display: inline-flex;align-items: center;gap: 8px;}.hidden { display: none !important; }341 unmodified lines34234334434534634734834910 unmodified lines36036136236336436510 unmodified lines376377378379341 unmodified linescolor: var(--pollen-coral);}/* Robot picker + login view styles dropped — both are owned by the* host shell now (mountHost renders them outside this page). *//* Desktop Layout - Side by Side */@media (min-width: 900px) {10 unmodified linesgrid-row: 1 / 3;}.panel:nth-of-type(1) { /* Head Control */grid-column: 2;grid-row: 1;10 unmodified lines}}.hidden { display: none !important; }
README.md+39-10
index.html+192-392
style.css+2-90