Skip to content

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.

Harden sniper live feed and IRL floor-anchor persistence

nirholas29de8bbd4898
diff --git a/src/dashboard-next/pages/sniper.js b/src/dashboard-next/pages/sniper.js
index ca6601633..0b9d19801 100644
--- a/src/dashboard-next/pages/sniper.js
+++ b/src/dashboard-next/pages/sniper.js
@@ -42,7 +42,6 @@ function fmtDelayMs(ms) {
}
function pumpUrl(mint) { return `https://pump.fun/coin/${encodeURIComponent(mint)}`; }
-function solscanTx(sig) { return `https://solscan.io/tx/${sig}`; }
// ── Styles ───────────────────────────────────────────────────────────────────
@@ -224,7 +223,7 @@ async function refresh(root) {
root.innerHTML = render();
wireEvents(root);
- startSse(root);
+ startSse();
loadTradeHistory(root);
// Auto-open arm modal when arriving from Strategy Lab with a preset
@@ -752,6 +751,12 @@ async function loadTradeHistory(root, append = false) {
}
const totalPnl = running;
const pnlClass = totalPnl > 0 ? 'sn-pos' : totalPnl < 0 ? 'sn-neg' : '';
+ const pnls = trades.map((t) => t.pnl_sol).filter((v) => v != null);
+ const best = pnls.length ? Math.max(...pnls) : null;
+ const worst = pnls.length ? Math.min(...pnls) : null;
+ const bestWorst = pnls.length
+ ? `<span class="sn-pos">Best +${fmtSol(best).trim()}</span> · <span class="${worst < 0 ? 'sn-neg' : ''}">Worst ${worst >= 0 ? '+' : ''}${fmtSol(worst).trim()}</span>`
+ : '';
const chartHtml = cumPoints.length >= 2
? `<div class="sn-chart-wrap">
<div class="sn-chart-head">
@@ -764,7 +769,7 @@ async function loadTradeHistory(root, append = false) {
<div class="sn-hist">
<div class="sn-hist-head">
<h3>Trade History</h3>
- <span style="font-size:12px;color:var(--nxt-ink-faint)">${trades.length} closed trade${trades.length !== 1 ? 's' : ''}</span>
+ <span style="font-size:12px;color:var(--nxt-ink-faint)">${trades.length} closed trade${trades.length !== 1 ? 's' : ''}${bestWorst ? ` · ${bestWorst}` : ''}</span>
</div>
${chartHtml}
<div style="overflow-x:auto">
@@ -1019,61 +1024,124 @@ function openArmModal(root) {
// ── SSE live positions ────────────────────────────────────────────────────────
-function startSse(root) {
- if (_sseSource) { _sseSource.close(); _sseSource = null; }
- if (!_strategies.length) {
- renderPositions([]);
- return;
- }
+// The /api/sniper/stream SSE is network-global and capped at 90s per connection,
+// and the worker is a separate process — so we (a) seed the owner's open positions
+// from the leaderboard snapshot on load, (b) filter the live stream down to the
+// caller's own agents, and (c) drive an explicit backoff reconnect with a visible
+// connection state instead of relying on the browser's silent auto-retry.
- const src = new EventSource('/api/sniper/stream?network=mainnet');
- _sseSource = src;
+function ownedAgentIds() {
+ return new Set(_strategies.map((s) => s.agent_id));
+}
- // Build initial snapshot from 'open' event, then update on 'buy'/'update'/'sell'.
- const positions = new Map();
+function setConn(state, label) {
+ const dot = document.querySelector('.sn-live-dot');
+ const txt = document.getElementById('sn-conn-status');
+ if (dot) dot.className = `sn-live-dot ${state}`;
+ if (txt) txt.textContent = label;
+}
- src.addEventListener('open', (e) => {
- try {
- const data = JSON.parse(e.data);
- if (Array.isArray(data)) {
- for (const p of data) positions.set(p.id, p);
- renderPositions([...positions.values()].filter((p) => ['opening', 'open'].includes(p.status)));
- }
- } catch {}
- });
+// Normalize the SSE event shape and the leaderboard snapshot shape into one
+// render shape. SSE gives entry_sol/current_sol/pnl_sol/pnl_pct/buy_url/at;
+// leaderboard gives entry_sol/current_sol/unrealized_pct/buy_url/at.
+function normPos(p) {
+ const entry = p.entry_sol != null ? Number(p.entry_sol) : null;
+ const current = p.current_sol != null ? Number(p.current_sol) : entry;
+ const pnlSol = entry != null && current != null
+ ? current - entry
+ : (p.pnl_sol != null ? Number(p.pnl_sol) : null);
+ const pnlPct = p.pnl_pct != null ? Number(p.pnl_pct)
+ : p.unrealized_pct != null ? Number(p.unrealized_pct)
+ : (entry ? ((current - entry) / entry) * 100 : null);
+ return {
+ id: p.id,
+ agent_id: p.agent_id,
+ agent_name: p.agent_name,
+ mint: p.mint,
+ symbol: p.symbol || p.name,
+ status: p.status || 'open',
+ entry_sol: entry,
+ current_sol: current,
+ unrealized_pnl_sol: pnlSol,
+ unrealized_pct: pnlPct,
+ buy_url: p.buy_url || null,
+ opened_at: p.at || p.opened_at || null,
+ };
+}
- src.addEventListener('buy', (e) => {
- try {
- const p = JSON.parse(e.data);
- positions.set(p.id, p);
- renderPositions([...positions.values()].filter((p) => ['opening', 'open'].includes(p.status)));
- } catch {}
- });
+function renderOwnedPositions() {
+ const owned = ownedAgentIds();
+ const list = [..._positionsMap.values()]
+ .filter((p) => owned.has(p.agent_id) && ['opening', 'open'].includes(p.status))
+ .sort((a, b) => new Date(b.opened_at || 0) - new Date(a.opened_at || 0));
+ renderPositions(list);
+}
- src.addEventListener('update', (e) => {
- try {
- const p = JSON.parse(e.data);
- positions.set(p.id, { ...(positions.get(p.id) || {}), ...p });
- renderPositions([...positions.values()].filter((p) => ['opening', 'open'].includes(p.status)));
- } catch {}
- });
+async function seedPositions() {
+ try {
+ const data = await get('/api/sniper/leaderboard?network=mainnet');
+ const owned = ownedAgentIds();
+ for (const p of (data.positions || [])) {
+ if (owned.has(p.agent_id)) _positionsMap.set(p.id, normPos(p));
+ }
+ } catch { /* non-fatal — the live stream will populate */ }
+ renderOwnedPositions();
+}
- src.addEventListener('sell', (e) => {
+function stopSse() {
+ if (_sseSource) { try { _sseSource.close(); } catch {} _sseSource = null; }
+ if (_sseTimer) { clearTimeout(_sseTimer); _sseTimer = null; }
+}
+
+function startSse() {
+ stopSse();
+ _positionsMap = new Map();
+ if (!_strategies.length) { renderPositions([]); return; }
+ setConn('connecting', 'Connecting…');
+ seedPositions();
+ connectSse();
+}
+
+function connectSse() {
+ const src = new EventSource('/api/sniper/stream?network=mainnet');
+ _sseSource = src;
+
+ const ingest = (e) => {
try {
- const p = JSON.parse(e.data);
- positions.set(p.id, p);
- renderPositions([...positions.values()].filter((pos) => ['opening', 'open'].includes(pos.status)));
+ const p = normPos(JSON.parse(e.data));
+ _positionsMap.set(p.id, { ...(_positionsMap.get(p.id) || {}), ...p });
+ renderOwnedPositions();
} catch {}
- });
+ };
+
+ src.addEventListener('open', () => { _sseRetry = 0; setConn('live', 'Live'); });
+ src.addEventListener('buy', ingest);
+ src.addEventListener('update', ingest);
+ src.addEventListener('sell', ingest);
+ // Server signals end-of-stream (90s duration cap) with a 'close' event; reconnect.
+ src.addEventListener('close', () => { try { src.close(); } catch {} scheduleReconnect(); });
src.onerror = () => {
- const el = document.getElementById('sn-positions');
- if (el && !el.querySelector('.sn-pos-row')) {
- el.innerHTML = '<p class="sn-empty">Live feed offline — positions update on next refresh.</p>';
- }
+ // Take control of retry ourselves (close → backoff) so the state is visible
+ // and the server's duration cap doesn't read as a permanent outage.
+ try { src.close(); } catch {}
+ if (_sseSource === src) _sseSource = null;
+ scheduleReconnect();
};
}
+function scheduleReconnect() {
+ if (!_strategies.length || _sseTimer) return;
+ if (!document.getElementById('sn-positions')) return; // page navigated away
+ _sseRetry = Math.min(_sseRetry + 1, 6);
+ const delay = Math.min(1000 * 2 ** (_sseRetry - 1), 30000);
+ setConn('reconnecting', `Reconnecting in ${Math.round(delay / 1000)}s…`);
+ _sseTimer = setTimeout(() => {
+ _sseTimer = null;
+ if (document.getElementById('sn-positions')) connectSse();
+ }, delay);
+}
+
// ── Toast ─────────────────────────────────────────────────────────────────────
function toast(msg) {
diff --git a/src/irl.js b/src/irl.js
index 8b9ace1fc..59239e052 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -43,6 +43,7 @@ import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import nipplejs from 'nipplejs';
import { AnimationManager } from './animation-manager.js';
import { WebXRSession } from './ar/webxr.js';
+import { createPersistGate, placementHint } from './ar/anchor-lifecycle.js';
import { IrlNet } from './irl-net.js';
import { wireShareButton } from './irl/share-frame.js';
import { log } from './shared/log.js';
@@ -1321,12 +1322,9 @@ function onGPSPosition(pos) {
// A WebXR floor anchor was placed before this first fix — persist its pin now.
// The XRAnchor already holds the agent in the room; this lands the durable,
- // shareable record it couldn't save without coordinates.
- if (_pendingXrAnchorPose) {
- const pose = _pendingXrAnchorPose;
- _pendingXrAnchorPose = null;
- persistFloorAnchor(pose);
- }
+ // shareable record it couldn't save without coordinates. gpsState.ready is true
+ // by here, so the gate drains its held pose exactly once (a no-op otherwise).
+ floorPersist.onFix(gpsState.ready);
// Move pinned avatar to its GPS-anchored world position. anchor_height_m (A2)
// keeps the feet on the ground plane on slopes / indoors — 0 today, but read
@@ -1592,11 +1590,40 @@ function startTick() {
}
let xrSession = null;
-// A floor anchor placed before the first GPS fix — held here and persisted the
+// A floor anchor placed before the first GPS fix is held here and persisted the
// instant onGPSPosition() lands real coordinates (mirrors _pendingGpsLock for the
// gyro path). The in-session XRAnchor already glues the agent; this rescues its
-// durable, shareable pin from a quick tap during GPS warm-up.
-let _pendingXrAnchorPose = null;
+// durable, shareable pin from a quick tap during GPS warm-up. The gate owns the
+// "save exactly once" guarantee: place() holds or saves, onFix() drains a held
+// pose a single time, drop() discards one abandoned on exit — so no code path can
+// double-save, skip the save, or persist a placement the user walked away from.
+const floorPersist = createPersistGate((payload) => persistFloorAnchor(payload.pose, payload.degraded));
+
+// Coordinated XR hint priority so transient lifecycle states (backgrounding,
+// tracking loss) never clobber — or get clobbered by — the placement copy.
+// Highest active state wins: paused > tracking-lost > the latest resting message
+// (searching → tap-to-place → anchored/saved). Every callback funnels through
+// here instead of calling setXrHint directly, so the displayed line is always the
+// single most important thing the user needs to know right now.
+const SEARCHING_HINT = 'Point at the floor and move your phone slowly';
+const xrHintState = { paused: false, trackingLost: false, resting: SEARCHING_HINT };
+
+function renderXrHint() {
+ if (xrHintState.paused) setXrHint('Paused — bring the app forward to keep placing');
+ else if (xrHintState.trackingLost) setXrHint('Tracking lost — move to a brighter, more textured spot');
+ else setXrHint(xrHintState.resting);
+}
+
+// Update the resting (placement-progress) line and re-render under current priority.
+function setXrResting(text) { xrHintState.resting = text; renderXrHint(); }
+
+// Reset the priority machine for a fresh session entry.
+function resetXrHint() {
+ xrHintState.paused = false;
+ xrHintState.trackingLost = false;
+ xrHintState.resting = SEARCHING_HINT;
+ renderXrHint();
+}
async function detectFloorAnchorSupport() {
try {
@@ -1647,32 +1674,42 @@ async function enterFloorAnchor() {
if (xrSession) { await xrSession.end(); return; }
// immersive-ar owns the rear camera and the full screen; release the
// getUserMedia passthrough first so the two don't contend for the camera.
+ // Remember whether the user was in camera-AR so we can put them back there on
+ // exit — returning to a black/gradient view would feel like a crash.
+ const resumeAR = arActive;
if (arActive) disableAR();
clearXrError();
if (anchorBtn) anchorBtn.classList.add('is-active');
if (xrOverlay) xrOverlay.hidden = false;
- setXrHint('Point at the floor and move your phone slowly');
+ resetXrHint();
try {
xrSession = new WebXRSession(xrViewer, {
domOverlayRoot: xrOverlay,
- onHit: (has) => setXrHint(has
- ? 'Tap to place your agent on the floor'
- : 'Point at the floor and move your phone slowly'),
- onAnchored: (pose) => onFloorAnchored(pose),
+ onHit: (has) => setXrResting(has ? 'Tap to place your agent on the floor' : SEARCHING_HINT),
+ // Tracking loss / recovery is a transient, higher-priority overlay on the
+ // resting hint — recoverable, self-clearing, never a dead reticle.
+ onTracking: (ok) => { xrHintState.trackingLost = !ok; renderXrHint(); },
+ // Backgrounding (lock, call, app switch) pauses the session; show a
+ // resume hint and restore the resting line when foregrounded again.
+ onVisibility: (visible) => { xrHintState.paused = !visible; renderXrHint(); },
+ onAnchored: (pose, meta) => onFloorAnchored(pose, meta),
onEnd: () => {
xrSession = null;
// Drop any anchor still waiting on a GPS fix — the user left this
// placement, so don't surprise them with a pin saved after they walk
// away (parity with the gyro path's arActive gate).
- _pendingXrAnchorPose = null;
+ floorPersist.drop();
// WebXRSession restores an opaque clear color on exit; IRL renders
// over the page gradient with a transparent canvas — put that back.
renderer.setClearColor(0x000000, 0);
if (!arActive) scene.background = null;
if (anchorBtn) anchorBtn.classList.remove('is-active');
if (xrOverlay) xrOverlay.hidden = true;
+ // Return the user to camera-AR if that's where they came from — same
+ // path whether they tapped Exit or the OS ended the session.
+ if (resumeAR && !arActive) enableAR();
},
});
await xrSession.start();
@@ -1681,6 +1718,9 @@ async function enterFloorAnchor() {
log.error('[irl] WebXR start failed:', err);
xrSession = null;
if (anchorBtn) anchorBtn.classList.remove('is-active');
+ // The start failed before any session existed, so onEnd never runs — restore
+ // the camera-AR the user was in directly so the entry attempt isn't one-way.
+ if (resumeAR && !arActive) enableAR();
showXrError(err);
}
}
@@ -1695,18 +1735,21 @@ function yawFromQuat(q) {
// Entry point for a placed floor anchor: persist it now if we have a GPS fix,
// otherwise hold the pose until the first fix lands. The in-session XRAnchor
-// already glues the agent either way — this only governs the durable pin.
-function onFloorAnchored(pose) {
- if (!gpsState.ready) {
+// already glues the agent either way — this only governs the durable pin. `meta`
+// carries the degraded flag (no real XRAnchor) so we tell the user the truth.
+function onFloorAnchored(pose, meta = {}) {
+ const degraded = meta.degraded === true;
+ // The gate decides: with a live fix it persists now; during GPS warm-up it
+ // holds the pose (degraded flag rides along) and onGPSPosition drains it once.
+ const outcome = floorPersist.place({ pose, degraded }, gpsState.ready);
+ if (outcome === 'held') {
// The anchor still glues the agent in-session; we just can't convert it to a
- // GPS pin yet. Hold the pose and finish the save the moment the first fix
- // lands (onGPSPosition) rather than dropping it — a quick tap during GPS
- // warm-up should still persist, not vanish.
- _pendingXrAnchorPose = pose;
- setXrHint('Anchored here — saving this spot once your location locks in');
- return;
+ // GPS pin yet. A quick tap during GPS warm-up should still persist, not vanish.
+ setXrResting(degraded
+ ? 'Placed — saving this spot once your location locks in (may drift on this device)'
+ : 'Anchored here — saving this spot once your location locks in');
}
- persistFloorAnchor(pose);
+ // outcome === 'persisted' → persistFloorAnchor set the resting hint already.
}
// Convert the anchored local-space pose to a GPS pin and persist it (A2) — the
@@ -1714,7 +1757,9 @@ function onFloorAnchored(pose) {
// lat/lng uses the same metre-per-degree math as the gyro Pin path (local −Z =
// north, +X = east); height + yaw + GPS-fit trust ride along in the anchor object.
// Split out so onGPSPosition() can replay a pose captured before the first fix.
-function persistFloorAnchor(pose) {
+// `degraded` (no real XRAnchor) only changes the in-session honesty copy — the
+// durable GPS pin is just coordinates, so it saves the same either way.
+function persistFloorAnchor(pose, degraded = false) {
const { position, quaternion } = pose;
const mLat = 110540;
const mLng = 111320 * Math.cos(gpsState.lat * (Math.PI / 180));
@@ -1724,7 +1769,7 @@ function persistFloorAnchor(pose) {
gpsPin = { lat: pinLat, lng: pinLng };
gpsModeActive = true;
- setXrHint('Anchored — walk around, it stays put');
+ setXrResting(placementHint(degraded));
savePin(pinLat, pinLng, heading, '', {
heightM: position.y, // floor height relative to the eye-level session origin (negative = below)
yawDeg: heading,
@@ -1734,12 +1779,12 @@ function persistFloorAnchor(pose) {
if (result?.ok && gpsPin) {
gpsPin.id = result.id;
revealMyPinsBtn();
- setXrHint(result.permanent
+ setXrResting(result.permanent
? 'Anchored & saved — permanently visible to nearby users'
: 'Anchored & saved — nearby users can see you for 7 days');
} else {
// Surface the moderation/cap/rate reason; the in-session anchor still holds.
- setXrHint(result?.message || 'Anchored here — couldn’t save the pin, retry on exit');
+ setXrResting(result?.message || 'Anchored here — couldn’t save the pin, retry on exit');
}
});
}
@@ -4781,4 +4826,14 @@ if (import.meta.env.DEV) {
} catch (e) {
log.warn('[irl] mockLoc parse failed:', e?.message || e);
}
+
+ // ── Arrival-signal harness (task 04 → task 03 handoff) ────────────────────
+ // Record every "newly stable in-range" emission so the hysteresis no-double-fire
+ // guarantee is verifiable in a real browser: drive a GPS wobble around a pin at
+ // the boundary (the Verify recipe) and confirm __irlStableArrivals() lists each
+ // agent exactly once — never a flicker storm. Returns the recorded arrivals.
+ const _stableArrivals = [];
+ onPinStable((pin) => { _stableArrivals.push({ id: pin.id, name: pin.avatar_name, at: Date.now() }); });
+ window.__irlStableArrivals = () => _stableArrivals.slice();
+ window.__irlResetStableArrivals = () => { _stableArrivals.length = 0; return 'reset'; };
}