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.

feat: assorted src module updates

nirholasa6e776896a63
diff --git a/src/a-me.js b/src/a-me.js
index bfbe45f6e..034fcb59c 100644
--- a/src/a-me.js
+++ b/src/a-me.js
@@ -249,7 +249,7 @@ function renderAgentCards(host, agents, avatars) {
<div class="ame-agent-actions">
<div class="ame-actions-row">
- ${avatarId ? `<a class="ame-btn primary small" href="/agent-next?id=${encodeURIComponent(avatarId)}" target="_blank">View Live</a>` : ''}
+ ${avatarId ? `<a class="ame-btn primary small" href="/agents/${encodeURIComponent(avatarId)}" target="_blank">View Live</a>` : ''}
${avatarId ? `<button class="ame-btn small" data-action="share" data-avatar-id="${esc(avatarId)}" data-name="${name}">Share</button>` : ''}
${avatarId ? `<button class="ame-btn small" data-action="embed" data-avatar-id="${esc(avatarId)}">Embed</button>` : ''}
<a class="ame-btn small" href="/dashboard/monetize">Monetize</a>
@@ -303,7 +303,7 @@ function renderAvatarCards(host, avatars, agents) {
return `
<div class="ame-avatar-card">
- <a class="ame-avatar-preview" href="/agent-next?id=${encodeURIComponent(av.id)}">
+ <a class="ame-avatar-preview" href="/agents/${encodeURIComponent(av.id)}">
${thumb
? `<img src="${esc(thumb)}" alt="${name}" loading="lazy" />`
: `<div class="ame-avatar-placeholder">
@@ -321,7 +321,7 @@ function renderAvatarCards(host, avatars, agents) {
${created ? `<span class="ame-meta-text">${esc(created)}</span>` : ''}
</div>
<div class="ame-avatar-footer-right">
- <a class="ame-btn ghost tiny" href="/agent-next?id=${encodeURIComponent(av.id)}" title="View">View</a>
+ <a class="ame-btn ghost tiny" href="/agents/${encodeURIComponent(av.id)}" title="View">View</a>
<button class="ame-btn ghost tiny" data-action="selfie" data-avatar-id="${esc(av.id)}" title="Update from selfie">Selfie</button>
<button class="ame-btn ghost tiny" data-action="share" data-avatar-id="${esc(av.id)}" data-name="${name}" title="Share">Share</button>
<a class="ame-btn ghost tiny" href="/walk?avatar=${encodeURIComponent(av.id)}" title="Walk">Walk</a>
@@ -452,7 +452,7 @@ function renderPanel(panel, type, data, agentId) {
}).join('')}
${memories.length > 10 ? `<div class="ame-panel-item" style="color:var(--text-soft)">+ ${memories.length - 10} more entries</div>` : ''}
</div>
- <div class="ame-panel-footer"><a href="/dashboard/memory">View all memory</a></div>
+ <div class="ame-panel-footer"><a href="/dashboard/agents">View all memory</a></div>
`;
} else if (type === 'actions') {
const actions = data?.actions || data?.items || [];
@@ -478,7 +478,7 @@ function renderPanel(panel, type, data, agentId) {
`;
}).join('')}
</div>
- <div class="ame-panel-footer"><a href="/dashboard/actions">View all activity</a></div>
+ <div class="ame-panel-footer"><a href="/dashboard/account">View all activity</a></div>
`;
}
}
@@ -486,7 +486,7 @@ function renderPanel(panel, type, data, agentId) {
// ── Share / Embed actions ────────────────────────────────────────────────────
function handleShare(avatarId, name) {
- const link = `${location.origin}/agent-next?id=${encodeURIComponent(avatarId)}`;
+ const link = `${location.origin}/agents/${encodeURIComponent(avatarId)}`;
navigator.clipboard.writeText(link).then(() => {
toast(`Link copied for ${name || 'agent'}`);
}).catch(() => {
@@ -524,7 +524,7 @@ function injectStyles() {
--accent: #ffffff;
--pump: #888888;
--danger: #f87171;
- --font-sans: "Inter Tight", -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, sans-serif;
+ --font-sans: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
--font-mono: ${MONO};
}
* { box-sizing: border-box; }
diff --git a/src/account.js b/src/account.js
index 9b137727c..816e52964 100644
--- a/src/account.js
+++ b/src/account.js
@@ -3,6 +3,7 @@
import { identifyUser, resetIdentity } from './analytics.js';
import { apiFetch, consumeCsrfToken } from './api.js';
+import { log } from './shared/log.js';
// Re-export for back-compat — many modules still `import { apiFetch } from
// './account.js'`. New code should import from './api.js' directly.
@@ -97,7 +98,7 @@ export async function saveRemoteGlbToAccount(source, meta = {}, opts = {}) {
try {
me = await getMe();
} catch (err) {
- console.warn('[account] getMe probe failed, proceeding optimistically:', err?.message);
+ log.warn('[account] getMe probe failed, proceeding optimistically:', err?.message);
me = { id: null, optimistic: true };
}
if (me === null) throw stageError('auth', 'Not signed in', { code: 'not_signed_in' });
@@ -130,7 +131,7 @@ export async function saveRemoteGlbToAccount(source, meta = {}, opts = {}) {
retargetedBoneCount = result.renamed;
}
} catch (err) {
- console.warn('[account] canonicalize failed; uploading original', err);
+ log.warn('[account] canonicalize failed; uploading original', err);
}
const size = blob.size;
@@ -172,7 +173,7 @@ export async function saveRemoteGlbToAccount(source, meta = {}, opts = {}) {
err.stage = err.stage || 'upload';
throw err;
}
- console.warn('[account] direct R2 PUT blocked; retrying via server proxy');
+ log.warn('[account] direct R2 PUT blocked; retrying via server proxy');
// Reset progress so the proxy attempt restarts visibly at 0% rather than
// looking stuck at whatever the direct PUT reached before failing.
onProgress?.(0);
@@ -221,7 +222,7 @@ export async function saveRemoteGlbToAccount(source, meta = {}, opts = {}) {
// Uses a hidden off-screen model-viewer to render the GLB, captures a JPEG
// poster, uploads to R2, and calls Claude Haiku for tags + description.
captureAndTagAvatar(avatar.id, storageKey).catch((err) => {
- console.warn('[account] thumbnail/auto-tag pipeline failed silently', err?.message);
+ log.warn('[account] thumbnail/auto-tag pipeline failed silently', err?.message);
});
// USDZ + half-body companion generation is opt-in (the demo page at
@@ -230,7 +231,7 @@ export async function saveRemoteGlbToAccount(source, meta = {}, opts = {}) {
// seconds of CPU on every save, so they don't ship to all users yet.
if (meta.generateCompanions) {
generateAndSaveCompanions(avatar.id, blob).catch((err) => {
- console.warn('[account] usdz/halfbody pipeline failed silently', err?.message);
+ log.warn('[account] usdz/halfbody pipeline failed silently', err?.message);
});
}
@@ -251,10 +252,10 @@ export async function generateAndSaveCompanions(avatarId, glbBlob) {
try {
report = await glbBlobToArkitReport(glbBlob);
} catch (err) {
- console.warn('[account] arkit report failed:', err?.message);
+ log.warn('[account] arkit report failed:', err?.message);
return;
}
- console.info(
+ log.info(
`[account] avatar ${avatarId} ARKit-52 coverage: ${Math.round(report.coverage * 100)}% (${report.implemented.length}/52)`,
);
try {
@@ -273,7 +274,7 @@ export async function generateAndSaveCompanions(avatarId, glbBlob) {
try {
usdzBlob = await glbBlobToUsdzBlob(glbBlob);
} catch (err) {
- console.warn('[account] usdz export failed:', err?.message);
+ log.warn('[account] usdz export failed:', err?.message);
return;
}
try {
@@ -293,7 +294,7 @@ export async function generateAndSaveCompanions(avatarId, glbBlob) {
body: JSON.stringify({ usdz_key: pre.usdz_key }),
});
} catch (err) {
- console.warn('[account] usdz upload/patch failed:', err?.message);
+ log.warn('[account] usdz upload/patch failed:', err?.message);
}
})();
@@ -325,7 +326,7 @@ export async function generateAndSaveCompanions(avatarId, glbBlob) {
body: JSON.stringify({ halfbody_key: pre.halfbody_key }),
});
} catch (err) {
- console.warn('[account] halfbody upload/patch failed:', err?.message);
+ log.warn('[account] halfbody upload/patch failed:', err?.message);
}
})();
}
diff --git a/src/agent-accessories.js b/src/agent-accessories.js
index 0154aa3a2..a78499416 100644
--- a/src/agent-accessories.js
+++ b/src/agent-accessories.js
@@ -11,6 +11,7 @@
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { resolveURI } from './ipfs.js';
import { collectSlotTargets } from './avatar-wardrobe.js';
+import { log } from './shared/log.js';
const SINGLE_SLOT_KINDS = new Set(['outfit', 'hat', 'glasses']);
@@ -100,7 +101,7 @@ export class AccessoryManager {
if (preset) {
await this.applyPreset(preset);
} else {
- console.warn(`[accessories] unknown preset id on boot: ${id}`);
+ log.warn(`[accessories] unknown preset id on boot: ${id}`);
}
}
}
@@ -164,13 +165,13 @@ export class AccessoryManager {
try {
gltf = await _loadGLB(this._loader, preset.glbUrl);
} catch (err) {
- console.warn(`[accessories] failed to load ${preset.glbUrl}:`, err);
+ log.warn(`[accessories] failed to load ${preset.glbUrl}:`, err);
return;
}
const bone = _findBone(this.viewer?.content, preset.attachBone);
if (!bone) {
- console.warn(
+ log.warn(
`[accessories] bone not found: ${preset.attachBone} (preset: ${preset.id})`,
);
// Still record as applied so list() and removePreset() work correctly
@@ -186,7 +187,7 @@ export class AccessoryManager {
_applyMorphBinding(preset) {
if (!this.viewer?.content) {
- console.warn(`[accessories] no model loaded yet for preset ${preset.id}`);
+ log.warn(`[accessories] no model loaded yet for preset ${preset.id}`);
return;
}
diff --git a/src/agent-avatar.js b/src/agent-avatar.js
index 427972e51..78a26f0b7 100644
--- a/src/agent-avatar.js
+++ b/src/agent-avatar.js
@@ -28,6 +28,7 @@ import { resolveMorphTargets, MORPH_ALIASES, ARKIT_VISEMES } from './runtime/ark
import { AnimationStateMachine } from './animation-state-machine.js';
// BEGIN:IDLE_LOOP_IMPORT
import { IdleAnimation } from './idle-animation.js';
+import { log } from './shared/log.js';
// END:IDLE_LOOP_IMPORT
const DEG2RAD = Math.PI / 180;
@@ -434,7 +435,7 @@ export class AgentAvatar {
}
// Clip not in library — warn once, try default slot fallback
if (!this._warnedSlots.has(clipName)) {
- console.warn(
+ log.warn(
`[AgentAvatar] slot "${slot}" → "${clipName}" not in animation library`,
);
this._warnedSlots.add(clipName);
diff --git a/src/agent-detail.css b/src/agent-detail.css
index 1aacd1db8..a1f5e2615 100644
--- a/src/agent-detail.css
+++ b/src/agent-detail.css
@@ -7,10 +7,20 @@
--ad-text: #e7e9ee;
--ad-muted: rgba(231, 233, 238, 0.55);
--ad-dim: rgba(231, 233, 238, 0.35);
- --ad-violet: #8b7cff;
+ --ad-violet: #888888;
--ad-green: #4ade80;
--ad-amber: #f5a524;
--ad-cyan: #57c7ff;
+
+ /* Shared B04 surface vocabulary — this page is standalone (no style.css),
+ so mirror the canonical card radius / elevation / skeleton tokens here
+ to keep cards and loading states consistent with the rest of the site. */
+ --radius-card: 14px;
+ --shadow-1: 0 1px 3px rgba(0, 0, 0, 0.30);
+ --shadow-2: 0 4px 24px rgba(0, 0, 0, 0.40), 0 1px 4px rgba(0, 0, 0, 0.20);
+ --skeleton-base: rgba(255, 255, 255, 0.04);
+ --skeleton-sheen: rgba(255, 255, 255, 0.08);
+ --skeleton-radius: 5px;
}
* { box-sizing: border-box; }
@@ -126,9 +136,10 @@ a { color: inherit; text-decoration: none; }
.ad-card {
background: var(--ad-card);
border: 1px solid var(--ad-line);
- border-radius: 14px;
+ border-radius: var(--radius-card);
padding: 18px 20px;
margin: 12px 24px;
+ box-shadow: var(--shadow-1);
}
.ad-card-head { display: flex; align-items: center; gap: 10px; margin-bottom: 14px; }
.ad-card-head h2, .ad-card-title {
@@ -162,7 +173,7 @@ a { color: inherit; text-decoration: none; }
.ad-bullet { width: 8px; height: 8px; border-radius: 50%; background: var(--ad-cyan); }
.ad-bullet-amber { background: var(--ad-amber); }
.ad-bullet-green { background: var(--ad-green); }
-.ad-bullet-violet { background: var(--ad-violet); }
+.ad-bullet-dim { background: var(--ad-dim); }
.ad-bullet-muted { background: var(--ad-dim); }
.ad-pill {
@@ -174,7 +185,7 @@ a { color: inherit; text-decoration: none; }
}
.ad-pill-muted { margin-left: auto; }
.ad-pill-amber { color: var(--ad-amber); border-color: rgba(245,165,36,0.3); background: rgba(245,165,36,0.08); }
-.ad-pill-violet { color: var(--ad-violet); border-color: rgba(139,124,255,0.3); background: rgba(139,124,255,0.08); }
+.ad-pill-violet { color: var(--ad-violet); border-color: rgba(255,255,255,0.15); background: rgba(255,255,255,0.04); }
.ad-pill-green { color: var(--ad-green); border-color: rgba(74,222,128,0.3); background: rgba(74,222,128,0.08); }
.ad-pill-cyan { color: var(--ad-cyan); border-color: rgba(87,199,255,0.3); background: rgba(87,199,255,0.08); }
@@ -282,9 +293,9 @@ a { color: inherit; text-decoration: none; }
.ad-sidebar { display: none; }
}
-.ad-bullet-red { background: #f87171; }
+.ad-bullet-red { background: var(--danger); }
.ad-pill-live {
- color: #f87171;
+ color: var(--danger);
border-color: rgba(248, 113, 113, 0.3);
background: rgba(248, 113, 113, 0.08);
margin-left: auto;
@@ -302,64 +313,10 @@ a { color: inherit; text-decoration: none; }
border: 0;
}
-/* Modal Styles */
-.ad-modal-overlay {
- position: fixed;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- background: rgba(0, 0, 0, 0.7);
- display: flex;
- align-items: center;
- justify-content: center;
- z-index: 1000;
-}
-
.hidden {
display: none;
}
-.ad-modal {
- background: var(--ad-card);
- border: 1px solid var(--ad-line);
- border-radius: 14px;
- width: 90%;
- max-width: 420px;
- box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
-}
-
-.ad-modal-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: 16px 20px;
- border-bottom: 1px solid var(--ad-line);
-}
-
-.ad-modal-header h3 {
- margin: 0;
- font-size: 16px;
- font-weight: 500;
-}
-
-.ad-modal-close {
- background: none;
- border: none;
- font-size: 24px;
- color: var(--ad-muted);
- cursor: pointer;
- line-height: 1;
-}
-
-.ad-modal-close:hover {
- color: var(--ad-text);
-}
-
-.ad-modal-body {
- padding: 20px;
-}
-
.ad-form-group {
margin-bottom: 16px;
}
@@ -691,13 +648,3 @@ a { color: inherit; text-decoration: none; }
.ad-review-skel-line.med { width: 70%; }
.ad-review-skel-line.long { width: 90%; }
-.ad-modal-footer {
- display: flex;
- justify-content: flex-end;
- gap: 10px;
- padding: 16px 20px;
- border-top: 1px solid var(--ad-line);
- background: var(--ad-bg-2);
- border-bottom-left-radius: 14px;
- border-bottom-right-radius: 14px;
-}
diff --git a/src/agent-detail.js b/src/agent-detail.js
index 88f195e64..4c736dc74 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -26,7 +26,11 @@ const solanaWeb3 = {
};
import { openSwapModal } from './swap-jupiter.js';
import { onchainBadgeEl } from './shared/onchain-badge.js';
+import { renderError as renderAsyncError } from './shared/async-state.js';
import { openCoinLaunch } from './shared/agent-coin.js';
+import { Modal } from './shared/modal.js';
+import { showSharePanel } from './shared/share.js';
+import { log } from './shared/log.js';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -46,7 +50,7 @@ const TRUST_ACCENT = {
};
const GRADIENTS = [
- ['#7c3aed', '#4f46e5'],
+ ['#555577', '#4f46e5'],
['#0ea5e9', '#ffffff'],
['#10b981', '#0ea5e9'],
['#f59e0b', '#ef4444'],
@@ -307,6 +311,7 @@ function render(agent) {
document.querySelector('.ad-main').classList.remove('loading');
bindWalletActions();
+ wireShareButton(agent);
loadExtraSections(agent.id, agent.rawMetadata);
}
@@ -762,7 +767,7 @@ function renderActions(actions, agentId) {
el('div', { style: 'text-align:center;padding-top:10px' }, [
el('a', {
class: 'ad-cta',
- href: `/dashboard/actions?agent=${encodeURIComponent(agentId)}`,
+ href: `/dashboard/account?agent=${encodeURIComponent(agentId)}`,
text: 'See full action log →',
}),
]),
@@ -974,6 +979,30 @@ function makeSnsResolver(inputEl, statusEl) {
return { resolveForSubmit, reset };
}
+function wireShareButton(agent) {
+ const btn = document.getElementById('ad-share-btn');
+ if (!btn) return;
+
+ const origin = location.origin;
+ const shareUrl = `${origin}/agents/${agent.id}`;
+ const remixUrl = `${origin}/create`;
+
+ btn.style.display = '';
+ btn.addEventListener('click', () => {
+ showSharePanel(
+ {
+ kind: 'agent',
+ id: agent.id,
+ title: agent.name || 'Agent',
+ description: agent.description || '',
+ shareUrl,
+ remixUrl,
+ },
+ btn,
+ );
+ });
+}
+
function bindWalletActions() {
const receiveBtn = document.getElementById('receive-btn');
const withdrawBtn = document.getElementById('withdraw-btn');
@@ -981,14 +1010,6 @@ function bindWalletActions() {
const qrCodeContainer = document.getElementById('qr-code-container');
const qrCodeCanvas = document.getElementById('qr-code');
const walletAddressSpan = document.getElementById('ad-holdings-addr');
- const modal = document.getElementById('withdraw-modal');
- const closeModalBtn = document.getElementById('close-modal-btn');
- const cancelWithdrawBtn = document.getElementById('cancel-withdraw-btn');
- const confirmWithdrawBtn = document.getElementById('confirm-withdraw-btn');
- const withdrawAmountInput = document.getElementById('withdraw-amount');
- const recipientAddressInput = document.getElementById('recipient-address');
- const recipientResolvedEl = document.getElementById('recipient-resolved');
- const snsResolver = makeSnsResolver(recipientAddressInput, recipientResolvedEl);
receiveBtn.addEventListener('click', () => {
const walletAddress = walletAddressSpan.dataset.full;
@@ -1004,16 +1025,46 @@ function bindWalletActions() {
}
});
- withdrawBtn.addEventListener('click', () => {
- modal.classList.remove('hidden');
+ // Build the withdraw modal using the shared Modal primitive
+ const bodyEl = document.createElement('div');
+ bodyEl.innerHTML = `
+ <div class="ad-form-group">
+ <label for="withdraw-amount">Amount (SOL)</label>
+ <input type="number" id="withdraw-amount" class="ad-input" placeholder="0.0">
+ </div>
+ <div class="ad-form-group">
+ <label for="recipient-address">Recipient address or .sol name</label>
+ <input type="text" id="recipient-address" class="ad-input"
+ placeholder="Wallet address or yourname.sol" autocomplete="off" spellcheck="false">
+ <div id="recipient-resolved" class="ad-resolved" hidden></div>
+ </div>
+ `;
+
+ const actionsEl = document.createElement('div');
+ actionsEl.innerHTML = `
+ <button id="cancel-withdraw-btn" class="ad-btn" type="button">Cancel</button>
+ <button id="confirm-withdraw-btn" class="ad-btn ad-btn-primary" type="button">Confirm Withdraw</button>
+ `;
+
+ const withdrawModal = new Modal({
+ title: 'Withdraw SOL',
+ body: bodyEl,
+ actions: actionsEl,
});
- closeModalBtn.addEventListener('click', () => {
- modal.classList.add('hidden');
+ const withdrawAmountInput = withdrawModal.bodyEl.querySelector('#withdraw-amount');
+ const recipientAddressInput = withdrawModal.bodyEl.querySelector('#recipient-address');
+ const recipientResolvedEl = withdrawModal.bodyEl.querySelector('#recipient-resolved');
+ const cancelWithdrawBtn = withdrawModal.actionsEl.querySelector('#cancel-withdraw-btn');
+ const confirmWithdrawBtn = withdrawModal.actionsEl.querySelector('#confirm-withdraw-btn');
+ const snsResolver = makeSnsResolver(recipientAddressInput, recipientResolvedEl);
+
+ withdrawBtn.addEventListener('click', () => {
+ withdrawModal.open(withdrawBtn);
});
cancelWithdrawBtn.addEventListener('click', () => {
- modal.classList.add('hidden');
+ withdrawModal.close();
});
confirmWithdrawBtn.addEventListener('click', async () => {
@@ -1067,12 +1118,12 @@ function bindWalletActions() {
: `${typedRecipient} (${recipientAddress})`;
alert(`Withdrawal of ${amount} SOL to ${displayTarget} successful!`);
- modal.classList.add('hidden');
+ withdrawModal.close();
withdrawAmountInput.value = '';
recipientAddressInput.value = '';
snsResolver.reset();
} catch (error) {
- console.error('Withdrawal failed:', error);
+ log.error('Withdrawal failed:', error);
alert(`Withdrawal failed: ${error.message}`);
} finally {
confirmWithdrawBtn.disabled = false;
@@ -1099,13 +1150,36 @@ function renderNotFound(id, reason) {
`;
}
+/**
+ * Transient load failure (offline, 5xx) — distinct from a genuine 404. Shows the
+ * shared retryable error shell so a network blip never leaves a blank page.
+ */
+function renderLoadError(err) {
+ document.title = 'Couldn’t load agent — three.ws';
+ const main = document.querySelector('.ad-main');
+ if (!main) return;
+ main.innerHTML = '<div class="ad-load-error"></div>';
+ renderAsyncError(
+ main.querySelector('.ad-load-error'),
+ err,
+ {
+ error: {
+ title: 'Couldn’t load this agent',
+ body: 'We hit a problem reaching the registry. Check your connection and try again.',
+ },
+ context: 'agent-detail:load',
+ },
+ runLoad,
+ );
+}
+
document.addEventListener('click', (e) => {
const btn = e.target.closest('.ad-copy[data-copy-target]');
if (!btn) return;
const id = btn.getAttribute('data-copy-target');
const node = document.getElementById(id);
const value = node?.dataset?.full || node?.textContent || '';
- if (value && value !== '—') navigator.clipboard?.writeText(value);
+ if (value && value !== '—') navigator.clipboard?.writeText(value)?.catch(() => {});
});
async function fetchJson(url) {
@@ -1208,20 +1282,25 @@ function normalize(rec, avatar) {
}
async function loadAgent(id) {
- if (!id) return { error: 'missing id', agent: null };
- if (!UUID_RE.test(id)) return { error: 'invalid id (expected UUID)', agent: null };
+ if (!id) return { error: 'missing id', agent: null, notFound: true };
+ if (!UUID_RE.test(id))
+ return { error: 'invalid id (expected UUID)', agent: null, notFound: true };
let rec;
try {
const json = await fetchJson(`/api/agents/${encodeURIComponent(id)}`);
rec = json.agent;
} catch (e) {
+ // A 404 is genuinely "no such agent"; anything else (offline, 5xx) is a
+ // transient load failure the user should be able to retry.
+ const notFound = e.status === 404;
return {
- error: e.status === 404 ? 'No agent with id' : `Fetch failed: ${e.message}`,
+ error: notFound ? 'No agent with id' : e,
agent: null,
+ notFound,
};
}
- if (!rec) return { error: 'No agent with id', agent: null };
+ if (!rec) return { error: 'No agent with id', agent: null, notFound: true };
let avatar = null;
if (rec.avatar_id) {
@@ -1229,7 +1308,7 @@ async function loadAgent(id) {
const json = await fetchJson(`/api/avatars/${encodeURIComponent(rec.avatar_id)}`);
avatar = json.avatar || null;
} catch (e) {
- console.warn('[agent-detail] avatar fetch failed:', e.message);
+ log.warn('[agent-detail] avatar fetch failed:', e.message);
}
}
@@ -1268,7 +1347,7 @@ connectWalletBtn.addEventListener('click', async () => {
connectWalletBtn.textContent = `${wallet.toString().slice(0, 4)}...${wallet.toString().slice(-4)}`;
} catch (err) {
- console.error('Failed to connect to wallet:', err);
+ log.error('Failed to connect to wallet:', err);
}
}
});
@@ -1276,12 +1355,16 @@ connectWalletBtn.addEventListener('click', async () => {
const id =
new URLSearchParams(location.search).get('id') ||
location.pathname.match(/\/agents\/([^/]+)/)?.[1];
-loadAgent(id)
- .then(({ agent, error }) => {
- if (!agent) return renderNotFound(id, error);
- render(agent);
- })
- .catch((e) => {
- console.error('[agent-detail] load failed', e);
- renderNotFound(id, 'Unexpected error loading');
- });
+
+function runLoad() {
+ loadAgent(id)
+ .then(({ agent, error, notFound }) => {
+ if (agent) return render(agent);
+ if (notFound) return renderNotFound(id, typeof error === 'string' ? error : '');
+ renderLoadError(error);
+ })
+ .catch((e) => {
+ renderLoadError(e);
+ });
+}
+runLoad();
diff --git a/src/agent-economy.js b/src/agent-economy.js
index 225436e75..bde48b295 100644
--- a/src/agent-economy.js
+++ b/src/agent-economy.js
@@ -14,10 +14,17 @@
// - /api/agent-economy/status polled on load to show live wallet balances.
// - The tx feed in the center column is pure DOM — no framework.
+import { buildReceiptHTML, buildReceiptText } from './shared/payment-receipt.js';
+import { showAddFunds } from './shared/add-funds.js';
+import { log } from './shared/log.js';
+
const $ = (id) => document.getElementById(id);
// ── Wallet status ─────────────────────────────────────────────────────────────
// Fetched on load; re-fetched after each trade to show updated balances.
+// Kept in module scope so the "Add funds" handler can read the agent address.
+let currentWalletStatus = null;
+
async function fetchWalletStatus() {
try {
const res = await fetch('/api/agent-economy/status');
@@ -55,19 +62,29 @@ function renderFundAlert(status) {
if (aOk) { el.classList.remove('visible'); return; }
let html = '';
if (!aCfg) {
- html = '<strong>Nova\'s wallet not configured.</strong> Set <code>AVATAR_WALLET_SECRET</code> in Vercel env to enable live transactions.';
+ // Technical detail (env var name) goes to console only
+ log.info('[three.ws] agent-economy: AVATAR_WALLET_SECRET not configured');
+ html = '<strong>Live transactions are paused.</strong> This feature is temporarily unavailable — check back shortly.';
} else {
const addr = status.agentA.address;
const exp = status.agentA.explorer || `https://solscan.io/account/${addr}`;
- html = `<strong>Nova needs SOL to transact.</strong> Fund her wallet with a small amount of SOL:<span class="fund-addr">${addr} <a href="${exp}" target="_blank" rel="noopener">↗ Solscan</a></span>`;
+ html = `<strong>Nova needs a small amount of SOL to transact.</strong> Fund her wallet to get started:
+ <span class="fund-addr">${addr} <a href="${exp}" target="_blank" rel="noopener">↗ Solscan</a></span>
+ <button class="fund-alert-btn" data-addr="${escHtml(addr)}">Add funds →</button>`;
}
el.innerHTML = html;
el.classList.add('visible');
+
+ el.querySelector('.fund-alert-btn')?.addEventListener('click', (e) => {
+ const addr = e.currentTarget.dataset.addr;
+ if (addr) showAddFunds({ walletAddress: addr }).then(() => refreshWalletStatus());
+ });
}
async function refreshWalletStatus() {
const status = await fetchWalletStatus();
if (!status) return;
+ currentWalletStatus = status;
renderBal('buyer-bal', status.agentA);
renderBal('seller-bal', status.agentB);
renderFundAlert(status);
@@ -196,6 +213,7 @@ function addFeedItem({ icon, type, title, sub, time }) {
<div class="tx-time">${escHtml(now)}</div>`;
const feed = $('feed');
feed.prepend(item);
+ return item;
}
function escHtml(s) {
@@ -262,6 +280,7 @@ async function purchase(service) {
sub: topic ? `Topic: ${escHtml(topic)}` : 'Service request initiated',
});
+ const txStartTime = Date.now();
let data;
try {
const res = await fetch('/api/agent-economy/transact', {
@@ -306,31 +325,63 @@ async function purchase(service) {
const usdStr = tx.usdAmount ? `$${tx.usdAmount.toFixed(4)} USD` : '';
const amountStr = [solStr, usdStr].filter(Boolean).join(' · ');
+ const receiptHtml = buildReceiptHTML({
+ usdAmount: tx.usdAmount || null,
+ recipientLabel: 'Oracle',
+ elapsedMs: Date.now() - txStartTime,
+ explorerUrl: tx.explorerUrl,
+ signature: tx.signature,
+ });
addFeedItem({
icon: '💸',
type: 'pay',
title: `Payment sent · ${amountStr}`,
- sub: `<a href="${escHtml(tx.explorerUrl)}" target="_blank" rel="noopener" class="tx-mono">
- ${escHtml(tx.signature.slice(0, 8))}…${escHtml(tx.signature.slice(-8))} ↗
- </a><br>${escHtml(tx.network === 'devnet' ? 'Solana devnet' : 'Solana mainnet')}`,
+ sub: receiptHtml,
});
- setStatus(`Payment confirmed · ${amountStr}`);
+ setStatus(buildReceiptText({
+ usdAmount: tx.usdAmount || null,
+ recipientLabel: 'Oracle',
+ elapsedMs: Date.now() - txStartTime,
+ }));
} else if (tx?.error === 'wallet_unconfigured') {
+ // Log technical detail privately; never surface env-var names to users
+ log.info('[three.ws] agent-economy: wallet_unconfigured —', tx.message);
addFeedItem({
- icon: '🔑',
+ icon: '⏸️',
type: 'pay',
- title: 'Wallet not configured',
- sub: escHtml(tx.message),
+ title: 'Live transactions paused',
+ sub: 'This feature is temporarily unavailable. Check back shortly.',
});
- setStatus('Set AVATAR_WALLET_SECRET to enable live transactions');
+ setStatus('Live transactions are temporarily unavailable');
} else if (tx?.error === 'insufficient_balance') {
- addFeedItem({ icon: '💰', type: 'pay', title: 'Fund Nova\'s wallet', sub: escHtml(tx.message) });
- setStatus('Fund Nova\'s wallet to transact');
+ const agentAddr = currentWalletStatus?.agentA?.address;
+ const fundBtn = agentAddr
+ ? `<button class="tx-add-funds-btn" data-addr="${escHtml(agentAddr)}">Add funds →</button>`
+ : '';
+ const feedEl = addFeedItem({
+ icon: '💰',
+ type: 'pay',
+ title: 'Not enough funds',
+ sub: `Nova's wallet needs a small top-up to cover this transaction. ${fundBtn}`,
+ });
+ feedEl?.querySelector('.tx-add-funds-btn')?.addEventListener('click', (e) => {
+ const addr = e.currentTarget.dataset.addr;
+ if (addr) showAddFunds({ walletAddress: addr }).then(() => refreshWalletStatus());
+ });
+ setStatus('Nova\'s wallet needs funds — use "Add funds" above');
} else if (tx?.error === 'no_recipient') {
- addFeedItem({ icon: '📭', type: 'pay', title: 'Set Agent B address', sub: escHtml(tx.message) });
- setStatus('Set AGENT_B_ADDRESS to Oracle\'s wallet');
+ // Log technical detail privately; never surface env-var names to users
+ log.info('[three.ws] agent-economy: no_recipient —', tx.message);
+ addFeedItem({
+ icon: '⏸️',
+ type: 'pay',
+ title: 'Live transactions paused',
+ sub: 'This feature is temporarily unavailable. Check back shortly.',
+ });
+ setStatus('Live transactions are temporarily unavailable');
} else if (tx?.error) {
- addFeedItem({ icon: '⚠️', type: 'pay', title: 'Transaction error', sub: escHtml(tx.message || tx.error) });
+ log.warn('[three.ws] agent-economy tx error:', tx.error, tx.message);
+ addFeedItem({ icon: '⚠️', type: 'pay', title: 'Transaction didn\'t go through', sub: 'The network rejected this transaction — try again in a moment.' });
}
// Oracle delivers the service
diff --git a/src/agent-edit.js b/src/agent-edit.js
index 689034f05..dd104a54d 100644
--- a/src/agent-edit.js
+++ b/src/agent-edit.js
@@ -2,6 +2,7 @@ import { AvatarCreator } from './avatar-creator.js';
import { saveRemoteGlbToAccount } from './account.js';
import { apiFetch } from './api.js';
import { openAvatarPicker } from './avatar-gallery-picker.js';
+import { log } from './shared/log.js';
const API_BASE = '/api';
const params = new URLSearchParams(location.search);
@@ -87,7 +88,7 @@ async function createDraftAgent() {
body: JSON.stringify({ avatar_id: initAvatarId }),
});
if (!patchRes.ok) {
- console.warn('[agent-edit] avatar attach failed', patchRes.status);
+ log.warn('[agent-edit] avatar attach failed', patchRes.status);
}
}
diff --git a/src/agent-eth-vanity-card.js b/src/agent-eth-vanity-card.js
index d46ea9b13..bda91a6d6 100644
--- a/src/agent-eth-vanity-card.js
+++ b/src/agent-eth-vanity-card.js
@@ -48,7 +48,7 @@ const STYLE = `
.agent-eth-vanity-details[open] .agent-eth-vanity-summary::before { content: '▾ '; }
.agent-eth-vanity { border: 1px solid rgba(255,255,255,0.08); border-radius: 10px; padding: .85rem 1rem; margin: .4rem 0 0; font: 13px/1.4 system-ui, sans-serif; background: rgba(255,255,255,0.03); color: #e6e6ea; }
.agent-eth-vanity h3 { margin: 0 0 .2rem; font-size: .85rem; font-weight: 600; color: #f2f2f5; display:flex; align-items:center; gap:.4rem; }
-.agent-eth-vanity h3 .badge { font-size: .65rem; font-weight: 600; padding: .1rem .45rem; border-radius: 999px; background: linear-gradient(90deg, rgba(167,139,250,0.2), rgba(99,102,241,0.2)); color: #c4b5fd; border: 1px solid rgba(167,139,250,0.25); letter-spacing: .03em; }
+.agent-eth-vanity h3 .badge { font-size: .65rem; font-weight: 600; padding: .1rem .45rem; border-radius: 999px; background: rgba(255,255,255,0.07); color: #888888; border: 1px solid rgba(255,255,255,0.14); letter-spacing: .03em; }
.agent-eth-vanity h3 .badge.case { background: linear-gradient(90deg, rgba(251,191,36,0.18), rgba(239,68,68,0.18)); color: #fbbf24; border-color: rgba(251,191,36,0.25); }
.agent-eth-vanity .sub { color: rgba(230,230,234,0.6); font-size: .78rem; margin: 0 0 .55rem; }
.agent-eth-vanity .row { display: flex; gap: .5rem; align-items: center; margin-top: .35rem; flex-wrap: wrap; }
@@ -67,7 +67,7 @@ const STYLE = `
.agent-eth-vanity button:disabled { opacity: .45; cursor: not-allowed; }
.agent-eth-vanity .preset-row { display: flex; gap: .3rem; flex-wrap: wrap; margin-top: .3rem; }
.agent-eth-vanity .preset { padding: .2rem .55rem; border-radius: 999px; background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.1); font-size: .7rem; cursor: pointer; }
-.agent-eth-vanity .preset.active { background: linear-gradient(90deg, rgba(167,139,250,0.18), rgba(99,102,241,0.18)); border-color: rgba(167,139,250,0.35); color: #c4b5fd; }
+.agent-eth-vanity .preset.active { background: rgba(255,255,255,0.09); border-color: rgba(255,255,255,0.18); color: #e8e8e8; }
.agent-eth-vanity .progress { font-size: .72rem; color: rgba(230,230,234,0.7); margin-top: .55rem; font-family: ui-monospace, monospace; }
.agent-eth-vanity .err { color: #ff8a80; font-size: .72rem; margin-top: .4rem; }
.agent-eth-vanity .ok { color: #4ade80; font-size: .72rem; margin-top: .4rem; }
@@ -194,7 +194,7 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {
to <strong>every EVM chain</strong> that has your factory — same address everywhere.
No keys. Mixed-case patterns enable EIP-55 checksum matching.
</p>
- ${suggestedFromName ? `<p class="sub" style="color:#c4b5fd">Suggested prefix from agent name: <code style="font-family:ui-monospace,monospace">${_esc(suggestedFromName)}</code></p>` : ''}
+ ${suggestedFromName ? `<p class="sub" style="color:#888888">Suggested prefix from agent name: <code style="font-family:ui-monospace,monospace">${_esc(suggestedFromName)}</code></p>` : ''}
<div class="row">
<button class="primary" data-act="new">Set up CREATE2 vanity</button>
<a href="/eth-vanity" target="_blank" rel="noopener" style="font-size:.72rem">open full grinder ↗</a>
diff --git a/src/agent-exchange.js b/src/agent-exchange.js
index bbeed4f0f..88fde92f7 100644
--- a/src/agent-exchange.js
+++ b/src/agent-exchange.js
@@ -2,7 +2,7 @@
// Two 3D AI avatars buying and selling live crypto intel for real USDC via x402.
// Agent A (seller) hosts /api/x402/crypto-intel. Agent B (buyer) pays $0.01 per
// call through the server-side x402 payer at /api/x402-pay, which handles the
-// challenge → sign → verify → settle → confirm flow and streams SSE stages.
+// challenge → sign → verify → settle → confirm flow and streams SSE events.
//
// Every on-chain confirmation is real: real USDC on Solana mainnet, real Solscan
// link. The avatars are iframed into the page and driven via postMessage.
@@ -10,6 +10,8 @@
// No mock data. When /api/x402-pay is unconfigured (no funded agent wallet) the
// page shows an honest error state.
+import { formatUsdcEq } from './shared/usd-price.js';
+
// ── Topics ────────────────────────────────────────────────────────────────────
const TOPICS = [
{ id: 'sol', label: '◎ SOL' },
@@ -20,12 +22,14 @@ const TOPICS = [
];
// Stage config matches the SSE event names /api/x402-pay emits.
+// narration: plain-language line shown to the viewer as each stage arrives.
const STAGE_DEFS = [
- { id: 'challenge', label: '402 Challenge' },
- { id: 'built', label: 'Sign tx' },
- { id: 'verified', label: 'Verify' },
- { id: 'settled', label: 'Settle' },
- { id: 'done', label: 'Confirmed' },
+ { id: 'challenge', label: '402 Challenge', narration: 'The seller issued a $0.01 USDC payment challenge — the buyer is building a Solana transaction.' },
+ { id: 'built', label: 'Build tx', narration: 'Transaction signed. Submitting to the x402 facilitator for verification…' },
+ { id: 'verified', label: 'Verify', narration: 'Payment verified by the facilitator. Dispatching the intel request…' },
+ { id: 'dispatched', label: 'Dispatch', narration: 'Request dispatched — the intel agent is preparing the market signal.' },
+ { id: 'settled', label: 'Settle', narration: 'Settling USDC on Solana mainnet — a real on-chain transfer is confirming.' },
+ { id: 'done', label: 'Confirmed', narration: 'Confirmed on-chain. Intel delivered.' },
];
// Agent scripts — lines spoken at each stage of the exchange.
@@ -66,9 +70,11 @@ const els = {
topics: $('topics'),
payBtn: $('payBtn'),
payLabel: null, // set in init()
- stages: $('stages'),
- receipt: $('receipt'),
- totalUsdc: $('totalUsdc'),
+ stages: $('stages'),
+ receipt: $('receipt'),
+ totalUsdc: $('totalUsdc'),
+ narration: $('narration'),
+ walletState: $('walletState'),
};
// ── State ─────────────────────────────────────────────────────────────────────
@@ -148,7 +154,10 @@ function resetStages() {
// ── Receipt renderer ──────────────────────────────────────────────────────────
function renderReceipt(payment, intel) {
- const amount = payment.amount ? `${(Number(payment.amount) / 1e6).toFixed(4)} USDC` : '$0.01 USDC';
+ const humanAmount = payment.amount ? Number(payment.amount) / 1e6 : 0.01;
+ const amountStr = `${humanAmount.toFixed(4)} USDC`;
+ const usdEqStr = formatUsdcEq(humanAmount);
+ const amount = usdEqStr ? `${amountStr} <span style="color:rgba(255,255,255,.45);font-size:0.9em">${usdEqStr}</span>` : amountStr;
const payer = payment.payer ? `${payment.payer.slice(0, 8)}…${payment.payer.slice(-4)}` : '—';
const payTo = payment.payTo ? `${payment.payTo.slice(0, 8)}…${payment.payTo.slice(-4)}` : '—';
const txShort = payment.tx ? `${payment.tx.slice(0, 10)}…${payment.tx.slice(-6)}` : null;
@@ -187,6 +196,83 @@ function renderReceipt(payment, intel) {
els.receipt.classList.add('show');
}
+// ── Narration helpers ─────────────────────────────────────────────────────────
+
+function showEmptyState() {
+ els.narration.innerHTML =
+ `<div class="nr-pre">` +
+ `<span class="nr-kicker">What you'll watch —</span>` +
+ `<span>Intel Agent issues a $0.01 USDC challenge</span>` +
+ `<span class="nr-arrow">→</span>` +
+ `<span>Buyer signs a Solana transaction</span>` +
+ `<span class="nr-arrow">→</span>` +
+ `<span>x402 verifies &amp; settles on-chain</span>` +
+ `<span class="nr-arrow">→</span>` +
+ `<span>Live crypto intel delivered</span>` +
+ `<span class="nr-arrow">·</span>` +
+ `<span>No mocks. Real USDC on Solana mainnet.</span>` +
+ `</div>`;
+}
+
+function narrate(stageId, extra) {
+ const s = STAGE_DEFS.find((d) => d.id === stageId);
+ if (!s) return;
+ const text = extra ? `${s.narration} ${extra}` : s.narration;
+ els.narration.innerHTML =
+ `<div class="nr-live">` +
+ `<span class="nr-dot" aria-hidden="true"></span>` +
+ `<span class="nr-text">${escHtml(text)}</span>` +
+ `</div>`;
+}
+
+function narrateDone(intelObj, paymentObj) {
+ const topic = intelObj?.topic?.toUpperCase() || 'Intel';
+ const amount = paymentObj?.amount ? (Number(paymentObj.amount) / 1e6).toFixed(4) : '0.0100';
+ const txLink = paymentObj?.tx
+ ? ` <a href="https://solscan.io/tx/${escHtml(paymentObj.tx)}" target="_blank" rel="noopener">View on Solscan ↗</a>`
+ : '';
+ els.narration.innerHTML =
+ `<div class="nr-done">` +
+ `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>` +
+ `${escHtml(amount)} USDC settled — ${escHtml(topic)} intelligence delivered.${txLink}` +
+ `</div>`;
+}
+
+async function checkWallet() {
+ try {
+ const r = await fetch('/api/x402-pay?balance=1');
+ if (!r.ok) return;
+ const b = await r.json();
+ if (!b.configured) {
+ els.walletState.className = 'show ws-unconfigured';
+ els.walletState.innerHTML =
+ `<div class="ws-head">` +
+ `<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>` +
+ `Demo wallet not configured` +
+ `</div>` +
+ `<div class="ws-body">` +
+ `This demo settles real USDC on Solana mainnet. The agent wallet isn't configured right now — live settlements are paused. ` +
+ `To enable: set <span class="ws-mono">X402_AGENT_SOLANA_SECRET_BASE58</span> and fund the wallet.` +
+ `</div>`;
+ els.payBtn.disabled = true;
+ } else if (typeof b.usdc === 'number' && b.usdc < 0.01) {
+ const addr = b.address ? `${b.address.slice(0, 8)}…${b.address.slice(-4)}` : '—';
+ els.walletState.className = 'show ws-low';
+ els.walletState.innerHTML =
+ `<div class="ws-head">` +
+ `<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>` +
+ `Agent wallet low on USDC` +
+ `</div>` +
+ `<div class="ws-body">` +
+ `The buyer wallet holds ${b.usdc.toFixed(4)} USDC — below the $0.01 minimum for a live settlement. ` +
+ `Fund <span class="ws-mono">${escHtml(addr)}</span> with USDC on Solana mainnet to run the demo.` +
+ `</div>`;
+ }
+ } catch {
+ // Network failures silently ignored — don't block the page.
+ }
+}
+
// ── Main payment flow ─────────────────────────────────────────────────────────
async function doPurchase() {
if (busy) return;
@@ -196,6 +282,13 @@ async function doPurchase() {
els.payLabel.textContent = 'Paying…';
resetStages();
+ // Show "initiating" in the narration region immediately.
+ els.narration.innerHTML =
+ `<div class="nr-live">` +
+ `<span class="nr-dot" aria-hidden="true"></span>` +
+ `<span class="nr-text">Initiating payment — connecting to the x402 facilitator…</span>` +
+ `</div>`;
+
// Both agents react to the initiation.
const line = LINES.B.idle(activeTopic);
sayB(line);
@@ -203,6 +296,8 @@ async function doPurchase() {
await delay(600);
sayA(LINES.A.idle);
+ // settled tracks the on-chain settlement info; intel is the purchased signal.
+ // Both are populated from SSE events and merged in the 'result' event handler.
let settled = null;
let intel = null;
let activeStage = 'challenge';
@@ -215,8 +310,6 @@ async function doPurchase() {
body: JSON.stringify({
tool: 'crypto_intel',
topic: activeTopic,
- // Tell x402-pay which endpoint to call. The server proxies to
- // /api/x402/crypto-intel with the x402 payment attached.
endpoint: '/api/x402/crypto-intel',
body: { topic: activeTopic },
}),
@@ -225,7 +318,7 @@ async function doPurchase() {
if (!res.ok || !res.body) {
const text = await res.text().catch(() => '');
let msg = 'Payment service unavailable.';
- try { msg = JSON.parse(text).error_description || msg; } catch { /* ignore */ }
+ try { msg = JSON.parse(text).error_description || JSON.parse(text).error || msg; } catch { /* ignore */ }
throw new Error(msg);
}
@@ -234,33 +327,44 @@ async function doPurchase() {
setStage('challenge', 'done', `${(Number(data.amount) / 1e6).toFixed(4)} USDC`);
setStage('built', 'active', 'signing…');
activeStage = 'built';
+ narrate('challenge');
sayB(LINES.B.challenge);
sayA(LINES.A.challenge);
} else if (event === 'built') {
setStage('built', 'done', `${data.build_ms} ms`);
setStage('verified', 'active', 'facilitator…');
activeStage = 'verified';
+ narrate('built', `(${data.build_ms} ms)`);
sayB(LINES.B.built);
sayA(LINES.A.built);
} else if (event === 'verified') {
setStage('verified', 'done', `${data.verify_ms} ms`);
- setStage('settled', 'active', 'on-chain…');
- activeStage = 'settled';
+ setStage('dispatched', 'active', 'dispatching…');
+ activeStage = 'dispatched';
+ narrate('verified', `(${data.verify_ms} ms)`);
sayB(LINES.B.verified);
sayA(LINES.A.verified);
+ } else if (event === 'dispatched') {
+ setStage('dispatched', 'done', `${data.dispatch_ms} ms`);
+ setStage('settled', 'active', 'on-chain…');
+ activeStage = 'settled';
+ narrate('dispatched');
} else if (event === 'settled') {
setStage('settled', 'done', `${data.settle_ms} ms · ${data.tx ? data.tx.slice(0, 8) + '…' : ''}`);
setStage('done', 'active');
activeStage = 'done';
settled = data;
+ narrate('settled');
sayB(LINES.B.settled);
sayA(LINES.A.settled);
} else if (event === 'result') {
- intel = data;
+ // result carries { ok, tool, args, result: <intelObj>, payment: <paymentObj>, durations }
+ intel = data.result ?? data;
+ if (data.payment) settled = { ...settled, ...data.payment };
} else if (event === 'error') {
errored = true;
setStage(activeStage, 'error', data.error || 'failed');
- throw new Error(data.error || 'payment failed');
+ throw new Error(data.error_description || data.error || 'payment failed');
}
}
@@ -268,25 +372,23 @@ async function doPurchase() {
// ── Success choreography ──────────────────────────────
setStage('done', 'done', 'confirmed');
+ narrateDone(intel, settled);
- // Buyer celebrates receiving the intel.
gestureB('celebrate');
await delay(300);
sayB(LINES.B.done(intel.signal));
- // Seller delivers the headline.
await delay(700);
sayA(LINES.A.done(intel.headline));
gestureA('wave');
// Update session total.
- const amount = intel ? 0.01 : Number(settled.amount || 10000) / 1e6;
- sessionTotal += amount;
+ const paidAmount = settled.amount ? Number(settled.amount) / 1e6 : 0.01;
+ sessionTotal += paidAmount;
els.totalUsdc.textContent = `$${sessionTotal.toFixed(2)}`;
els.totalUsdc.classList.add('flash');
setTimeout(() => els.totalUsdc.classList.remove('flash'), 600);
- // Show the receipt.
renderReceipt(settled, intel);
} catch (err) {
@@ -294,13 +396,22 @@ async function doPurchase() {
sayA(LINES.A.error);
sayB(LINES.B.error);
gestureA('idle');
- // Show a user-facing error in the receipt area.
+
+ const msg = escHtml(err.message || 'Payment failed. No funds moved.');
els.receipt.innerHTML =
- `<div style="color:var(--red);font-size:13px;font-weight:600;">` +
- `⚠ ${escHtml(err.message || 'Payment failed. No funds moved.')} ` +
- `<a href="/pay" style="color:var(--usdc-lt);text-decoration:underline;">See the x402 demo →</a>` +
+ `<div style="background:rgba(255,79,106,.06);border:1px solid rgba(255,79,106,.22);border-radius:10px;padding:12px 14px;">` +
+ `<div style="display:flex;align-items:center;gap:7px;font-weight:700;color:var(--red);font-size:13px;margin-bottom:5px;">` +
+ `<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>` +
+ `Payment failed — no funds moved` +
+ `</div>` +
+ `<div style="font-size:12.5px;color:var(--muted);">${msg} ` +
+ `<a href="/pay" style="color:var(--usdc-lt);text-decoration:none;" onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'">Learn about x402 →</a>` +
+ `</div>` +
`</div>`;
els.receipt.classList.add('show');
+
+ // Reset narration to empty state so the viewer knows they can retry.
+ showEmptyState();
} finally {
busy = false;
els.payBtn.classList.remove('busy');
@@ -392,6 +503,8 @@ function init() {
buildTopics();
renderStages();
mountAvatars();
+ showEmptyState();
+ checkWallet();
els.payBtn.addEventListener('click', doPurchase);
diff --git a/src/agent-home-pumpfun.js b/src/agent-home-pumpfun.js
index deb3c8e43..52c62b887 100644
--- a/src/agent-home-pumpfun.js
+++ b/src/agent-home-pumpfun.js
@@ -20,6 +20,7 @@
*/
import { ACTION_TYPES } from './agent-protocol.js';
+import { THREE_WS_MARK } from './solana/vanity/brand.js';
const REFRESH_MS = 30_000;
const QUOTE_DEBOUNCE_MS = 250;
@@ -46,9 +47,12 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
quote: null,
quoting: false,
signer: 'agent', // 'agent' = server-side agent wallet; 'owner' = browser wallet
- // vanity launch
+ // Brand mark: every three.ws coin is stamped `3ws…` on-chain (always
+ // ground). `vanityEnabled` + `vanitySuffix` only let power users append
+ // extra base58 characters *after* the mark — never disable it. No default
+ // suffix: the mark leads, with no extra characters unless the user adds them.
vanityEnabled: false,
- vanitySuffix: 'pump',
+ vanitySuffix: '',
vanityProgress: null,
// 3ws stamp state: null | 'grinding' | 'done'
stampPhase: null,
@@ -107,6 +111,7 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
<span class="pumpfun-card-title">Launch coin on pump.fun</span>
</div>
<p class="pumpfun-card-sub">Mint a token whose metadata is your 3D avatar.</p>
+ <p class="pumpfun-card-sub">Every three.ws coin is stamped <strong>3ws…</strong> on-chain.</p>
<div class="pumpfun-signer" role="tablist" aria-label="Signer">
<button class="pumpfun-signer-tab ${state.signer === 'agent' ? 'is-active' : ''}" data-action="signer-agent" role="tab" aria-selected="${state.signer === 'agent'}" ${isGrinding || isStamped ? 'disabled' : ''}>Agent wallet</button>
<button class="pumpfun-signer-tab ${state.signer === 'owner' ? 'is-active' : ''}" data-action="signer-owner" role="tab" aria-selected="${state.signer === 'owner'}" ${isGrinding || isStamped ? 'disabled' : ''}>Owner wallet</button>
@@ -427,7 +432,16 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
const btnEl = cardBody.querySelector('#pf-launch-btn');
if (btnEl) { btnEl.disabled = true; btnEl.textContent = 'Launching…'; }
} else {
- // Agent wallet: server stamps 3ws mark. Reflect the phase on the button.
+ // Agent wallet: the custodial agent wallet signs server-side, so the
+ // server grinds + holds the mint secret. Always request the 3ws mark
+ // (plus any optional user suffix) so the agent launch is branded too —
+ // this launch endpoint only grinds the mark when we ask for it.
+ const userSuffix = state.vanityEnabled ? (state.vanitySuffix?.trim() || '') : '';
+ extraArgs = {
+ vanityPrefix: THREE_WS_MARK,
+ vanityIgnoreCase: true,
+ ...(userSuffix ? { vanitySuffix: userSuffix } : {}),
+ };
launchBtn.textContent = 'Launching…';
}
@@ -824,7 +838,7 @@ export function mountPumpFunCard({ panel, identity, skills, memory, protocol })
/** Render a mint address with the leading three.ws mark visually emphasized. */
function stampedMintHtml(mint) {
if (!mint) return '';
- const MARK_LEN = 3; // '3ws'
+ const MARK_LEN = THREE_WS_MARK.length;
const mark = escapeHtml(mint.slice(0, MARK_LEN));
const tail = mint.slice(MARK_LEN);
const tailShort = tail.length > 8 ? tail.slice(0, 4) + '…' + tail.slice(-4) : escapeHtml(tail);
diff --git a/src/agent-hub-actions.js b/src/agent-hub-actions.js
index 9a0e72c12..c59200b32 100644
--- a/src/agent-hub-actions.js
+++ b/src/agent-hub-actions.js
@@ -6,6 +6,7 @@
* Only shown to the agent's owner. Non-owners see the unmodified panel.
*/
import { AgentEmbedModal } from './agent-embed-modal.js';
+import { log } from './shared/log.js';
/**
* @param {HTMLElement} panel — .agent-home-panel element
@@ -72,7 +73,7 @@ export function renderHubActions(panel, identity, rawAgent) {
{ initialTab: 'my' },
);
} catch (err) {
- console.error('[hub] register-ui load failed', err);
+ log.error('[hub] register-ui load failed', err);
} finally {
deployBtn.disabled = false;
}
@@ -96,7 +97,7 @@ export function renderHubActions(panel, identity, rawAgent) {
{ initial },
);
} catch (err) {
- console.error('[hub] register-ui load failed', err);
+ log.error('[hub] register-ui load failed', err);
deployBtn.disabled = false;
deployBtn.querySelector('span').textContent = 'Deploy on-chain';
}
@@ -141,7 +142,7 @@ async function _resolveAgentPrefill(rawAgent) {
initial.glbUrl = avatar.url || avatar.model_url || '';
initial.imageUrl = avatar.thumbnail_url || '';
} catch (err) {
- console.warn('[hub] avatar prefill failed; opening wizard without it', err);
+ log.warn('[hub] avatar prefill failed; opening wizard without it', err);
}
return initial;
}
diff --git a/src/agent-protocol.js b/src/agent-protocol.js
index dced4642c..e423ceaba 100644
--- a/src/agent-protocol.js
+++ b/src/agent-protocol.js
@@ -7,6 +7,7 @@
* Actions flow: Skills → Protocol → Avatar (renders) + Identity (logs) + Memory (stores)
*/
+import { log } from './shared/log.js';
export const ACTION_TYPES = {
SPEAK: 'speak', // agent says something (text + sentiment)
THINK: 'think', // agent is processing (internal monologue)
@@ -119,7 +120,7 @@ export class AgentProtocol extends EventTarget {
*/
emit(action) {
if (this.debug) {
- console.log(`[agent-protocol] ${Date.now()} ${action.type}`, action.payload);
+ log.log(`[agent-protocol] ${Date.now()} ${action.type}`, action.payload);
this._doEmit(action);
return;
}
@@ -129,7 +130,7 @@ export class AgentProtocol extends EventTarget {
if (policy.mode === 'passthrough') {
// Passthrough events go through the burst rate-limiter.
if (this._isThrottled(action.type)) {
- console.warn(`[agent-protocol] rate-limited: ${action.type} — too many events`);
+ log.warn(`[agent-protocol] rate-limited: ${action.type} — too many events`);
return;
}
this._doEmit(action);
diff --git a/src/agent-skills-sentiment.js b/src/agent-skills-sentiment.js
index b0b3002a0..8e849b2eb 100644
--- a/src/agent-skills-sentiment.js
+++ b/src/agent-skills-sentiment.js
@@ -1,5 +1,6 @@
import { ACTION_TYPES } from './agent-protocol.js';
+import { log } from './shared/log.js';
export function registerSentimentSkills(agentSkills) {
agentSkills.register({
@@ -54,7 +55,7 @@ export function registerSentimentSkills(agentSkills) {
data: { text, sentiment },
};
} catch (error) {
- console.error('Sentiment analysis failed:', error);
+ log.error('Sentiment analysis failed:', error);
return {
success: false,
output: 'Failed to analyze sentiment.',
diff --git a/src/agents-directory.js b/src/agents-directory.js
index 8301d0bbe..dcf75946a 100644
--- a/src/agents-directory.js
+++ b/src/agents-directory.js
@@ -14,6 +14,7 @@ import {
import { CHAIN_META } from './erc8004/chain-meta.js';
import { REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';
import { onchainBadgeHTML } from './shared/onchain-badge.js';
+import { log } from './shared/log.js';
const CACHE_TTL_MS = 60000;
const ITEMS_PER_PAGE = 24;
@@ -202,14 +203,14 @@ export class AgentsDirectory {
metadata,
};
} catch (err) {
- console.warn(`Failed to fetch agent ${ev.agentId} on ${cid}:`, err);
+ log.warn(`Failed to fetch agent ${ev.agentId} on ${cid}:`, err);
return null;
}
}),
);
return enriched.filter(Boolean);
} catch (err) {
- console.warn(`Failed to fetch chain ${cid}:`, err);
+ log.warn(`Failed to fetch chain ${cid}:`, err);
return [];
}
}),
diff --git a/src/animation-manager.js b/src/animation-manager.js
index bcd7c063b..8f80850d7 100644
--- a/src/animation-manager.js
+++ b/src/animation-manager.js
@@ -1,5 +1,6 @@
import { AnimationClip, AnimationMixer, LoopRepeat, LoopOnce } from 'three';
import { canonicalizeBoneName } from './glb-canonicalize.js';
+import { log } from './shared/log.js';
// Minimum number of canonical bones a skinned model must expose before the
// pre-baked clip library can drive it meaningfully. The clips address tracks by
@@ -177,7 +178,7 @@ export class AnimationManager {
try {
await this.loadAnimation(def.name, def.url, { loop: def.loop !== false });
} catch (err) {
- console.warn(`[AnimationManager] failed to load "${def.name}":`, err.message);
+ log.warn(`[AnimationManager] failed to load "${def.name}":`, err.message);
this._failed.add(def.name);
}
}
@@ -216,7 +217,7 @@ export class AnimationManager {
const ready = await this.ensureLoaded(name);
if (!ready) {
if (this._failed.has(name) || this._animationDefs.some((d) => d.name === name))
- console.warn(`[AnimationManager] "${name}" unavailable`);
+ log.warn(`[AnimationManager] "${name}" unavailable`);
return;
}
const action = this.actions.get(name);
@@ -228,7 +229,7 @@ export class AnimationManager {
action.reset().fadeIn(0.01).play();
this.currentAction = action;
this.currentName = name;
- try { this.onChange?.(name); } catch (e) { console.warn('[AnimationManager] onChange threw:', e); }
+ try { this.onChange?.(name); } catch (e) { log.warn('[AnimationManager] onChange threw:', e); }
}
/**
@@ -243,7 +244,7 @@ export class AnimationManager {
const ready = await this.ensureLoaded(name);
if (!ready) {
if (this._failed.has(name) || this._animationDefs.some((d) => d.name === name))
- console.warn(`[AnimationManager] "${name}" unavailable`);
+ log.warn(`[AnimationManager] "${name}" unavailable`);
return;
}
const next = this.actions.get(name);
@@ -257,7 +258,7 @@ export class AnimationManager {
}
this.currentAction = next;
this.currentName = name;
- try { this.onChange?.(name); } catch (e) { console.warn('[AnimationManager] onChange threw:', e); }
+ try { this.onChange?.(name); } catch (e) { log.warn('[AnimationManager] onChange threw:', e); }
}
/**
@@ -274,7 +275,7 @@ export class AnimationManager {
this.mixer?.stopAllAction();
this.currentAction = null;
this.currentName = null;
- try { this.onChange?.(null); } catch (e) { console.warn('[AnimationManager] onChange threw:', e); }
+ try { this.onChange?.(null); } catch (e) { log.warn('[AnimationManager] onChange threw:', e); }
}
/**
diff --git a/src/animation-state-machine.js b/src/animation-state-machine.js
index 994130f83..01bdccc31 100644
--- a/src/animation-state-machine.js
+++ b/src/animation-state-machine.js
@@ -29,6 +29,7 @@
* already animates the mouth. Agents that have a talking-body clip (e.g. a
* subtle idle-2) override `states.talk.clip` via meta.animationGraph.
*/
+import { log } from './shared/log.js';
const DEFAULT_STATES = Object.freeze({
idle: { clip: 'idle', loop: true, crossfade: 0.5, oneShot: false, returnTo: null },
talk: { clip: 'idle', loop: true, crossfade: 0.35, oneShot: false, returnTo: null },
@@ -140,7 +141,7 @@ export class AnimationStateMachine {
crossfade: def.crossfade,
});
} catch (err) {
- console.warn('[AnimationStateMachine] onTransition threw:', err);
+ log.warn('[AnimationStateMachine] onTransition threw:', err);
}
}
return resolvedTarget;
diff --git a/src/app-next-overlay.js b/src/app-next-overlay.js
index 1b20b0d1a..9f0d9d357 100644
--- a/src/app-next-overlay.js
+++ b/src/app-next-overlay.js
@@ -1,6 +1,7 @@
// UX preview overlay for /app-next — re-skins /src/app.js without touching it.
import { getMe, readAuthHint, saveRemoteGlbToAccount } from './account.js';
+import { log } from './shared/log.js';
const STORAGE_HINT_KEY = 'nxt:first-hint-dismissed';
const CHIP_ROTATE_MS = 9000;
@@ -70,7 +71,7 @@ function boot() {
waitForViewer().then((viewer) => {
if (!viewer) {
- console.warn('[nxt] viewer never appeared — stage polish skipped');
+ log.warn('[nxt] viewer never appeared — stage polish skipped');
return;
}
polishStage(viewer);
@@ -121,7 +122,7 @@ function polishStage(viewer) {
viewer.state.transparentBg = true;
viewer.updateBackground();
} catch (err) {
- console.warn('[nxt] could not set transparent canvas', err);
+ log.warn('[nxt] could not set transparent canvas', err);
}
}
@@ -414,7 +415,7 @@ async function sendChat(text, optionalClip) {
try {
agent._send();
} catch (err) {
- console.warn('[nxt] chat send failed', err);
+ log.warn('[nxt] chat send failed', err);
}
}
}
@@ -552,7 +553,7 @@ function wireAnimationSheet() {
// Chain through any existing onChange so we don't clobber a viewer subscriber.
const prevOnChange = viewer.animationManager.onChange;
viewer.animationManager.onChange = (...args) => {
- try { prevOnChange?.(...args); } catch (e) { console.warn('[nxt] prior onChange threw', e); }
+ try { prevOnChange?.(...args); } catch (e) { log.warn('[nxt] prior onChange threw', e); }
const current = viewer.animationManager.currentName;
grid.querySelectorAll('.nxt-anim-card').forEach((c) => {
c.setAttribute('aria-pressed', c.dataset.name === current ? 'true' : 'false');
@@ -602,7 +603,7 @@ function playClip(viewer, name) {
if (!def) return;
mgr.ensureLoaded(name)
.then(() => mgr.play(name))
- .catch((err) => console.warn('[nxt] clip play failed', name, err));
+ .catch((err) => log.warn('[nxt] clip play failed', name, err));
}
// ── Share / embed popover ─────────────────────────────────────────────────
@@ -907,7 +908,7 @@ function wirePrimaryCTA() {
throw new Error('save failed');
}
} catch (err) {
- console.warn('[nxt] save failed', err);
+ log.warn('[nxt] save failed', err);
if (primaryLabel) primaryLabel.textContent = original;
const code = err.data?.error || err.code || '';
const detail = err.data?.error_description || err.message || '';
diff --git a/src/app.js b/src/app.js
index c8660e1f4..ff6987c2b 100644
--- a/src/app.js
+++ b/src/app.js
@@ -40,6 +40,7 @@ import { SceneController } from './runtime/scene.js';
import { Runtime } from './runtime/index.js';
import { Memory } from './memory/index.js';
import { SkillRegistry } from './skills/index.js';
+import { log } from './shared/log.js';
window.THREE = THREE;
window.VIEWER = {};
@@ -124,9 +125,9 @@ function parseOnchainHash(value) {
}
if (!(window.File && window.FileReader && window.FileList && window.Blob)) {
- console.error('The File APIs are not fully supported in this browser.');
+ log.error('The File APIs are not fully supported in this browser.');
} else if (!WebGL.isWebGL2Available()) {
- console.error('WebGL is not supported in this browser.');
+ log.error('WebGL is not supported in this browser.');
}
class App {
@@ -308,7 +309,7 @@ class App {
// Defensive: _loadAgentForEdit handles its own failures and
// always mounts the viewer up-front, but a truly unexpected
// throw shouldn't leave the user with no UI to act on.
- console.warn('[3d-agent] agent-edit load failed', err);
+ log.warn('[3d-agent] agent-edit load failed', err);
this._showViewerError("Couldn't load this agent.", () => this._retryAgentLoad());
if (!this.viewer) this._maybeResumeOrLoad(this.options);
if (!this._agentSystemBooted) this._initAgentSystem();
@@ -385,7 +386,7 @@ class App {
return;
}
} catch (err) {
- console.warn('[3d-agent] resume failed', err);
+ log.warn('[3d-agent] resume failed', err);
}
}
@@ -548,7 +549,7 @@ class App {
}
});
} catch (err) {
- console.warn('[3d-agent] Agent system init failed:', err.message);
+ log.warn('[3d-agent] Agent system init failed:', err.message);
}
}
@@ -667,16 +668,19 @@ class App {
if (signOutBtn) {
signOutBtn.addEventListener('click', () => {
- fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).finally(
- () => {
+ fetch('/api/auth/logout', { method: 'POST', credentials: 'include' })
+ .finally(() => {
try {
localStorage.removeItem('3dagent:auth-hint');
} catch {
/* ignore */
}
location.href = '/';
- },
- );
+ })
+ // `.finally` re-throws a network rejection; swallow it so a
+ // failed logout request never surfaces as an unhandled
+ // rejection (the user is navigated home regardless).
+ .catch(() => {});
});
}
}
@@ -963,7 +967,7 @@ class App {
}
}
} catch (err) {
- console.warn('[3d-agent] save failed:', err.message);
+ log.warn('[3d-agent] save failed:', err.message);
if (btn) {
btn.removeAttribute('disabled');
btn.querySelector('span').textContent = 'Save to account';
@@ -1383,7 +1387,7 @@ class App {
this._widgetController = ctl;
}
} catch (e) {
- console.warn('[widget] mount failed', type, e?.message);
+ log.warn('[widget] mount failed', type, e?.message);
}
}
@@ -1411,7 +1415,7 @@ class App {
this.viewer.setEnvironment(cfg.envPreset);
}
} catch (e) {
- console.warn('[widget] applyConfig failed', e?.message);
+ log.warn('[widget] applyConfig failed', e?.message);
}
}
@@ -1590,7 +1594,7 @@ class App {
break;
}
} catch (e) {
- console.warn('[widget] command failed', command, e?.message);
+ log.warn('[widget] command failed', command, e?.message);
}
}
@@ -1602,7 +1606,7 @@ class App {
} catch {}
}
if (!this._parentOrigin) {
- console.warn('[widget] parent origin unknown; dropping', msg?.type);
+ log.warn('[widget] parent origin unknown; dropping', msg?.type);
return;
}
window.parent.postMessage(msg, this._parentOrigin);
@@ -1686,7 +1690,7 @@ class App {
this._flashSaved(avatar);
} catch (err) {
if (err.code !== 'not_signed_in') {
- console.warn('[3d-agent] save to account failed:', err.message);
+ log.warn('[3d-agent] save to account failed:', err.message);
}
}
});
@@ -1888,12 +1892,14 @@ class App {
.then((r) => (r.ok ? def : null))
.catch(() => null),
),
- ).then((results) => {
- const available = results.filter(Boolean);
- if (available.length > 0) {
- viewer.setAnimationDefs(available);
- }
- });
+ )
+ .then((results) => {
+ const available = results.filter(Boolean);
+ if (available.length > 0) {
+ viewer.setAnimationDefs(available);
+ }
+ })
+ .catch(() => {});
});
}
@@ -1973,7 +1979,7 @@ class App {
if (this._editingAgentId && this._avatarNeedsThumbnail) {
this._avatarNeedsThumbnail = false;
this._captureAndUploadThumbnail().catch((err) =>
- console.warn('[3d-agent] thumbnail upload failed', err),
+ log.warn('[3d-agent] thumbnail upload failed', err),
);
}
} else {
@@ -2195,7 +2201,7 @@ class App {
// The viewer-status overlay (driven by LOAD_END payload) is the
// user-facing error surface now — see _classifyLoadError above.
// onError is kept as a console-only fallback for diagnostics.
- console.error('[3d-agent] load error:', error);
+ log.error('[3d-agent] load error:', error);
}
/**
@@ -2246,7 +2252,7 @@ class App {
const resolvedGlb = isDecentralizedURI(glbUri) ? resolveURI(glbUri) : glbUri;
await this.view(resolvedGlb, '', new Map());
} catch (err) {
- console.warn('[3d-agent] on-chain load failed:', err);
+ log.warn('[3d-agent] on-chain load failed:', err);
this._showOnChainError(err.message || String(err));
}
}
@@ -2302,7 +2308,7 @@ class App {
const { renderShowcasePage } = await import('./erc8004/showcase.js');
renderShowcasePage(page);
} catch (err) {
- console.error('[3d-agent] showcase page load failed', err);
+ log.error('[3d-agent] showcase page load failed', err);
}
}
@@ -2338,12 +2344,12 @@ class App {
new RegisterUI(
page,
(result) => {
- console.info('[ERC-8004] Agent registered:', result);
+ log.info('[ERC-8004] Agent registered:', result);
},
{ mode: 'page', initial, viewer: this.viewer, avatarId: initial.avatarId },
);
} catch (err) {
- console.error('[3d-agent] deploy page load failed', err);
+ log.error('[3d-agent] deploy page load failed', err);
}
}
@@ -2382,7 +2388,7 @@ class App {
glbUrl: avatar.url || avatar.model_url || '',
};
} catch (err) {
- console.warn('[deploy] avatar prefill failed; falling back to viewer model', err);
+ log.warn('[deploy] avatar prefill failed; falling back to viewer model', err);
}
}
return {
@@ -2466,7 +2472,7 @@ if (!window.__WIDGET_SHELL) {
function _bootApp() {
const app = new App(document.body, location);
window.VIEWER.app = app;
- console.info('[three.ws] Debugging data exported as `window.VIEWER`.');
+ log.info('[three.ws] Debugging data exported as `window.VIEWER`.');
}
// The slim /widget shell injects this script after DOMContentLoaded (the
// reveal state machine dynamically appends it), so a plain
diff --git a/src/ar-page.js b/src/ar-page.js
index c26a95379..99b7dfffc 100644
--- a/src/ar-page.js
+++ b/src/ar-page.js
@@ -8,6 +8,7 @@
*/
import { glbBlobToUsdzBlob } from './usdz-pipeline.js';
+import { log } from './shared/log.js';
const segments = location.pathname.split('/').filter(Boolean);
// /avatars/:id/ar → segments = ['avatars', 'uuid', 'ar']
@@ -72,7 +73,7 @@ function renderPage(avatar, glbUrl) {
viewer.setAttribute('ios-src', avatar.usdz_url);
}
- $('ar-back-link').href = `/agent-next?id=${encodeURIComponent(avatar.id || avatarId)}`;
+ $('ar-back-link').href = `/agents/${encodeURIComponent(avatar.id || avatarId)}`;
$('ar-share-btn').addEventListener('click', () => shareAvatar(avatar));
}
@@ -162,7 +163,7 @@ document.addEventListener('DOMContentLoaded', () => {
});
init().catch((err) => {
- console.error('[ar-page] init error', err);
+ log.error('[ar-page] init error', err);
showError('Something went wrong loading this avatar.');
});
diff --git a/src/artifact/entry.js b/src/artifact/entry.js
index d0d52a7e1..a5ea56687 100644
--- a/src/artifact/entry.js
+++ b/src/artifact/entry.js
@@ -4,6 +4,7 @@
// Usage: <script src="artifact.js"></script>
// <div id="agent3d" data-agent-id="123"></div>
+import { log } from '../shared/log.js';
(async function initArtifact() {
const container = document.getElementById('agent3d');
if (!container) return;
@@ -138,7 +139,7 @@
renderer.setSize(w, h);
});
} catch (err) {
- console.error('[artifact] error:', err);
+ log.error('[artifact] error:', err);
caption.textContent = 'Failed to load viewer';
}
})();
diff --git a/src/auth/email-auth.js b/src/auth/email-auth.js
new file mode 100644
index 000000000..5a0c1bc68
--- /dev/null
+++ b/src/auth/email-auth.js
@@ -0,0 +1,120 @@
+/**
+ * No-crypto auth for the email+password path.
+ *
+ * All calls mint the same session cookie that the rest of the platform
+ * consumes — same createSession() / __Host-sid flow as SIWE/SIWS.
+ *
+ * Primary consumers:
+ * - login.html (already wired — uses /api/auth/login directly)
+ * - C04 onboarding wizard (import signInWithEmail / registerWithEmail)
+ * - Any surface that needs to auth a no-crypto user programmatically
+ */
+
+// ─── Public API ──────────────────────────────────────────────────────────────
+
+/**
+ * Sign in with email (or username) and password.
+ * Returns the user object on success; throws with a human-readable message on failure.
+ *
+ * @param {string} emailOrUsername
+ * @param {string} password
+ * @returns {Promise<{ user: object }>}
+ */
+export async function signInWithEmail(emailOrUsername, password) {
+ const res = await fetch('/api/auth/login', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ email: emailOrUsername, password }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ if (res.status === 429) throw new Error('Too many attempts. Try again in a moment.');
+ throw new Error(data.error_description || data.error || 'Email or password is incorrect.');
+ }
+ _persistAuthHint(data.user);
+ return data;
+}
+
+/**
+ * Register a new account with email and password (no wallet needed).
+ * Creates a session immediately — the user is signed in on success.
+ *
+ * @param {string} email
+ * @param {string} password
+ * @param {{ displayName?: string, referralCode?: string }} [opts]
+ * @returns {Promise<{ user: object }>}
+ */
+export async function registerWithEmail(email, password, opts = {}) {
+ const res = await fetch('/api/auth/register', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ email,
+ password,
+ ...(opts.displayName ? { display_name: opts.displayName } : {}),
+ ...(opts.referralCode ? { referralCode: opts.referralCode } : {}),
+ }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ if (res.status === 409) throw new Error('An account with that email already exists.');
+ if (res.status === 429) throw new Error('Too many sign-up attempts. Try again later.');
+ throw new Error(data.error_description || data.error || 'Registration failed.');
+ }
+ _persistAuthHint(data.user);
+ return data;
+}
+
+/**
+ * Resolve the signed-in user from the current session cookie.
+ * Returns null when unauthenticated (no cookie or expired session).
+ *
+ * @returns {Promise<object|null>}
+ */
+export async function getCurrentUser() {
+ try {
+ const res = await fetch('/api/auth/me', { credentials: 'include' });
+ if (!res.ok) return null;
+ const { user } = await res.json();
+ return user ?? null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Sign out — destroys the server session and clears the session cookie.
+ *
+ * @returns {Promise<void>}
+ */
+export async function signOut() {
+ await fetch('/api/auth/logout', {
+ method: 'POST',
+ credentials: 'include',
+ }).catch(() => {});
+ try { localStorage.removeItem('3dagent:auth-hint'); } catch { /* ignore */ }
+}
+
+/**
+ * Route the current page to the sign-in page, preserving the current URL as
+ * the post-auth redirect target. Call this when a gated action requires auth.
+ */
+export function requireAuth() {
+ try { sessionStorage.setItem('login_redirect', location.href); } catch { /* ignore */ }
+ location.href = '/login';
+}
+
+// ─── Internal ────────────────────────────────────────────────────────────────
+
+function _persistAuthHint(user) {
+ if (!user) return;
+ try {
+ localStorage.setItem('3dagent:auth-hint', JSON.stringify({
+ authed: true,
+ name: user.display_name || '',
+ ts: Date.now(),
+ }));
+ } catch { /* ignore */ }
+}
diff --git a/src/avatar-creator.js b/src/avatar-creator.js
index 922e7168a..33eaa5f87 100644
--- a/src/avatar-creator.js
+++ b/src/avatar-creator.js
@@ -9,8 +9,11 @@
// acquisition; this module no longer references it.
import { AvaturnSDK } from '@avaturn/sdk';
+import { log } from './shared/log.js';
function getStudioUrl() {
+ // Explicit override wins in any environment (e.g. a standalone studio dev
+ // server on :5173 during character-studio development).
try {
if (typeof import.meta !== 'undefined' && import.meta.env?.VITE_CHARACTER_STUDIO_URL) {
return String(import.meta.env.VITE_CHARACTER_STUDIO_URL)
@@ -18,7 +21,17 @@ function getStudioUrl() {
.replace(/\/$/, '');
}
} catch (_) {}
- return 'http://localhost:5173';
+ // Default: the Avatar Studio is served SAME-ORIGIN under /avatar-studio — the
+ // Vite dev middleware serves character-studio/build there in dev, and the
+ // copy-avatar-studio step ships the same build to /avatar-studio in prod
+ // (see vite.config.js). Resolving to the live origin keeps this correct on
+ // every deployment and avoids a dead localhost fallback in production. The
+ // value must stay absolute: it's used as an iframe src and parsed with
+ // `new URL(studioUrl).origin` for postMessage validation.
+ if (typeof location !== 'undefined' && location.origin) {
+ return `${location.origin}/avatar-studio`;
+ }
+ return 'https://three.ws/avatar-studio';
}
export class AvatarCreator {
@@ -99,11 +112,11 @@ export class AvatarCreator {
: new Blob([await blob.arrayBuffer()], { type: 'model/gltf-binary' });
this._fireExport(glbBlob, { sourceUrl: data.urlType === 'dataURL' ? null : glbUrl });
} catch (err) {
- console.error('[three.ws Avatar Creator] failed to fetch selfie GLB:', err);
+ log.error('[three.ws Avatar Creator] failed to fetch selfie GLB:', err);
}
});
} catch (err) {
- console.error('[three.ws Avatar Creator] Failed to initialize selfie SDK:', err);
+ log.error('[three.ws Avatar Creator] Failed to initialize selfie SDK:', err);
this._showError('Failed to load the avatar creator. Please try again.');
}
}
@@ -131,7 +144,7 @@ export class AvatarCreator {
try {
this.onExport(blob, { provider: this._provider, ...meta });
} catch (err) {
- console.error('[three.ws Avatar Creator] onExport handler threw:', err);
+ log.error('[three.ws Avatar Creator] onExport handler threw:', err);
}
}
this.close();
diff --git a/src/avatar-drop.js b/src/avatar-drop.js
index eccc77ce5..55ff582df 100644
--- a/src/avatar-drop.js
+++ b/src/avatar-drop.js
@@ -15,6 +15,7 @@ import {
} from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { reserveWebGLContext } from './webgl-budget.js';
+import { log } from './shared/log.js';
export function initAvatarDrop(sectionEl) {
const canvas = sectionEl.querySelector('#drop-canvas');
@@ -361,7 +362,10 @@ export function initAvatarDrop(sectionEl) {
scene.add(avatar);
mixer = new AnimationMixer(avatar);
- const fetchClip = f => fetch(f).then(r => r.json());
+ const fetchClip = f => fetch(f).then(r => {
+ if (!r.ok) throw new Error(`${f} → HTTP ${r.status}`);
+ return r.json();
+ });
Promise.all([
fetchClip('/animations/clips/sitidle.json'),
fetchClip('/animations/clips/standup.json'),
@@ -398,10 +402,10 @@ export function initAvatarDrop(sectionEl) {
};
startSit();
- });
- });
+ }).catch(e => log.warn('[avatar-drop] animation clips failed to load — skipping interactive sit/stand sequence', e));
+ }, undefined, err => log.warn('[avatar-drop] avatar GLB failed to load', err));
})
- .catch(e => console.warn('[avatar-drop] boot failed', e));
+ .catch(e => log.warn('[avatar-drop] boot failed', e));
// Render loop — paused when the section is offscreen or the tab is hidden.
const clock = new Clock();
diff --git a/src/avatar-edit.js b/src/avatar-edit.js
index e6ecd6a55..88bb78ed8 100644
--- a/src/avatar-edit.js
+++ b/src/avatar-edit.js
@@ -25,6 +25,7 @@ import { IdleAnimation } from './idle-animation.js';
import { renderSculptPanel } from './avatar-sculpt.js';
import { renderWardrobePanel } from './avatar-wardrobe.js';
import { playAs } from './game/play-handoff.js';
+import { log } from './shared/log.js';
// ── Routing ────────────────────────────────────────────────────────────
@@ -71,7 +72,7 @@ let previewToken = 0;
let opQueue = Promise.resolve();
function queueOp(fn) {
const next = opQueue.then(fn).catch((err) => {
- console.warn('[avatar-edit] queued op failed:', err);
+ log.warn('[avatar-edit] queued op failed:', err);
});
opQueue = next;
return next;
@@ -107,7 +108,7 @@ if (!avatarId) {
$('ae-shell').innerHTML = `<div class="ae-error">No avatar specified.</div>`;
} else {
init().catch((err) => {
- console.error('[avatar-edit] init', err);
+ log.error('[avatar-edit] init', err);
$('ae-shell').innerHTML = `<div class="ae-error">${esc(err.message || 'Failed to load')}</div>`;
});
}
@@ -234,7 +235,7 @@ async function saveAppearance() {
try {
await uploadAvatarSnapshot({ avatarId: avatar.id, scene });
} catch (err) {
- console.warn('[avatar-edit] snapshot upload failed:', err?.message);
+ log.warn('[avatar-edit] snapshot upload failed:', err?.message);
}
});
}
diff --git a/src/avatar-embed.js b/src/avatar-embed.js
index 302e4756e..993da27e9 100644
--- a/src/avatar-embed.js
+++ b/src/avatar-embed.js
@@ -70,6 +70,7 @@ import {
MORPH_ALIASES,
conformanceReport,
} from './runtime/arkit52.js';
+import { log } from './shared/log.js';
const BRIDGE_VERSION = '1.0';
const CAPABILITIES = [
@@ -162,7 +163,7 @@ async function main() {
animMgr.loadAll().catch(() => {});
}
} catch (err) {
- console.warn('[avatar-embed] animation manifest load failed', err?.message);
+ log.warn('[avatar-embed] animation manifest load failed', err?.message);
}
const startAnim = params.get('animation') || params.get('pose');
@@ -303,7 +304,7 @@ async function main() {
try {
await startMocap();
} catch (err) {
- console.warn('[avatar-embed] mocap auto-start failed', err);
+ log.warn('[avatar-embed] mocap auto-start failed', err);
}
} else if (!hideChrome) {
pill.style.display = 'inline-flex';
@@ -548,7 +549,7 @@ async function main() {
}
if (params.get('mic') === '1') {
enableMic().catch((err) =>
- console.warn('[avatar-embed] mic auto-start failed', err?.message),
+ log.warn('[avatar-embed] mic auto-start failed', err?.message),
);
}
if (params.get('state') === '1') document.body.classList.add('show-state');
@@ -571,7 +572,7 @@ async function main() {
bc.postMessage({ type: 'v1.avatar.online', channel: channelKey, name: resolved.name, handle: resolved.handle, id: resolved.id });
}
} catch (err) {
- console.warn('[avatar-embed] BroadcastChannel unavailable', err?.message);
+ log.warn('[avatar-embed] BroadcastChannel unavailable', err?.message);
}
function broadcast(msg) {
if (!bc) return;
diff --git a/src/avatar-gallery-picker.css b/src/avatar-gallery-picker.css
index a35376771..e4b00cbdd 100644
--- a/src/avatar-gallery-picker.css
+++ b/src/avatar-gallery-picker.css
@@ -2,7 +2,7 @@
Reusable avatar browser with search, tag filters, grid, 3D preview,
and multiple handoff modes. Works as a modal overlay or inline embed.
- Uses theme.css tokens (--t-*) for consistency with the monochrome system.
+ Uses canonical B01 tokens for consistency with the monochrome system.
─────────────────────────────────────────────────────────────────────── */
/* ── Overlay (modal mode) ───────────────────────────────────────────── */
@@ -28,8 +28,8 @@
width: 100%;
max-width: 1080px;
max-height: calc(100vh - 40px);
- background: var(--t-bg-1, #0a0a0a);
- border: 1px solid var(--t-stroke, #1a1a1a);
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
border-radius: 14px;
display: flex;
flex-direction: column;
@@ -55,13 +55,13 @@
align-items: center;
gap: 12px;
padding: 14px 18px;
- border-bottom: 1px solid var(--t-stroke, #1a1a1a);
+ border-bottom: 1px solid var(--stroke);
flex-shrink: 0;
}
.agp-title {
font-size: 15px;
font-weight: 600;
- color: var(--t-ink, #e8e8e8);
+ color: var(--ink);
flex: 1;
min-width: 0;
white-space: nowrap;
@@ -74,9 +74,9 @@
display: grid;
place-items: center;
background: transparent;
- border: 1px solid var(--t-stroke, #1a1a1a);
+ border: 1px solid var(--stroke);
border-radius: 8px;
- color: var(--t-ink-dim, #888);
+ color: var(--ink-dim);
cursor: pointer;
font-size: 16px;
line-height: 1;
@@ -84,9 +84,9 @@
flex-shrink: 0;
}
.agp-close:hover {
- background: var(--t-glass-strong, rgba(255,255,255,0.08));
- color: var(--t-ink, #e8e8e8);
- border-color: var(--t-stroke-strong, #2a2a2a);
+ background: var(--surface-2);
+ color: var(--ink);
+ border-color: var(--stroke-strong);
}
/* ── Toolbar (search + status) ──────────────────────────────────────── */
@@ -104,44 +104,44 @@
align-items: center;
gap: 8px;
padding: 8px 12px;
- background: var(--t-glass, rgba(255,255,255,0.04));
- border: 1px solid var(--t-stroke, #1a1a1a);
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
border-radius: 10px;
transition: border-color 150ms ease, background 150ms ease;
}
.agp-search:focus-within {
- border-color: var(--t-stroke-strong, #2a2a2a);
- background: var(--t-glass-strong, rgba(255,255,255,0.08));
+ border-color: var(--stroke-strong);
+ background: var(--surface-2);
}
.agp-search svg {
flex-shrink: 0;
- color: var(--t-ink-faint, #555);
+ color: var(--ink-dim);
}
.agp-search input {
flex: 1;
background: transparent;
border: 0;
outline: 0;
- color: var(--t-ink, #e8e8e8);
+ color: var(--ink);
font: inherit;
font-size: 13px;
min-width: 0;
}
-.agp-search input::placeholder { color: var(--t-ink-faint, #555); }
+.agp-search input::placeholder { color: var(--ink-dim); }
.agp-search-clear {
background: transparent;
border: 0;
- color: var(--t-ink-faint, #555);
+ color: var(--ink-dim);
cursor: pointer;
padding: 2px 4px;
font-size: 14px;
line-height: 1;
transition: color 120ms ease;
}
-.agp-search-clear:hover { color: var(--t-ink, #e8e8e8); }
+.agp-search-clear:hover { color: var(--ink); }
.agp-status {
font-size: 12px;
- color: var(--t-ink-faint, #555);
+ color: var(--ink-dim);
flex-shrink: 0;
white-space: nowrap;
}
@@ -157,9 +157,9 @@
min-height: 0;
}
.agp-tag {
- background: var(--t-glass, rgba(255,255,255,0.04));
- color: var(--t-ink-dim, #888);
- border: 1px solid var(--t-stroke, #1a1a1a);
+ background: var(--surface-1);
+ color: var(--ink-dim);
+ border: 1px solid var(--stroke);
border-radius: 999px;
padding: 4px 10px;
font: inherit;
@@ -168,13 +168,13 @@
transition: all 120ms ease;
}
.agp-tag:hover {
- border-color: var(--t-stroke-strong, #2a2a2a);
- color: var(--t-ink, #e8e8e8);
+ border-color: var(--stroke-strong);
+ color: var(--ink);
}
.agp-tag.active {
- background: var(--t-accent, #fff);
- color: var(--t-accent-ink, #000);
- border-color: var(--t-accent, #fff);
+ background: var(--accent);
+ color: #000;
+ border-color: var(--accent);
}
/* ── Body (scrollable area: grid + preview) ─────────────────────────── */
@@ -193,7 +193,7 @@
.agp-grid-col {
overflow-y: auto;
padding: 12px 18px 18px;
- border-right: 1px solid var(--t-stroke, #1a1a1a);
+ border-right: 1px solid var(--stroke);
}
.agp-grid {
display: grid;
@@ -204,9 +204,9 @@
/* ── Card ───────────────────────────────────────────────────────────── */
.agp-card {
- background: var(--t-bg-2, #111);
- border: 1.5px solid var(--t-stroke, #1a1a1a);
- border-radius: 10px;
+ background: var(--surface-2);
+ border: 1.5px solid var(--stroke);
+ border-radius: var(--radius-card, 14px);
overflow: hidden;
cursor: pointer;
display: flex;
@@ -218,17 +218,17 @@
transition: border-color 120ms ease, transform 120ms ease, box-shadow 120ms ease;
}
.agp-card:hover {
- border-color: var(--t-stroke-strong, #2a2a2a);
+ border-color: var(--stroke-strong);
transform: translateY(-1px);
- box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
+ box-shadow: var(--shadow-2, 0 4px 24px rgba(0, 0, 0, 0.4));
}
.agp-card.selected {
- border-color: var(--t-accent, #fff);
- box-shadow: 0 0 0 1px var(--t-accent, #fff) inset, 0 4px 20px rgba(255, 255, 255, 0.06);
+ border-color: var(--accent);
+ box-shadow: 0 0 0 1px var(--accent) inset, 0 4px 20px rgba(255, 255, 255, 0.06);
}
.agp-card-thumb {
aspect-ratio: 1 / 1;
- background: var(--t-bg-3, #1a1a1a);
+ background: var(--surface-3);
position: relative;
display: flex;
align-items: center;
@@ -244,7 +244,7 @@
.agp-card-ph {
width: 100%;
height: 100%;
- background: linear-gradient(135deg, var(--t-bg-3, #1a1a1a) 0%, var(--t-bg-2, #111) 100%);
+ background: linear-gradient(135deg, var(--surface-3) 0%, var(--surface-2) 100%);
display: flex;
align-items: center;
justify-content: center;
@@ -252,7 +252,7 @@
.agp-card-ph svg {
width: 32px;
height: 32px;
- color: var(--t-ink-faint, #555);
+ color: var(--ink-dim);
opacity: 0.5;
}
.agp-card-body {
@@ -261,7 +261,7 @@
.agp-card-name {
font-size: 12.5px;
font-weight: 600;
- color: var(--t-ink, #e8e8e8);
+ color: var(--ink);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
@@ -275,8 +275,8 @@
}
.agp-card-chip {
font-size: 10px;
- color: var(--t-ink-faint, #555);
- background: var(--t-glass, rgba(255,255,255,0.04));
+ color: var(--ink-dim);
+ background: var(--surface-1);
border-radius: 999px;
padding: 1px 6px;
}
@@ -294,8 +294,8 @@
aspect-ratio: 1 / 1;
border-radius: 10px;
overflow: hidden;
- background: var(--t-bg-0, #000);
- border: 1px solid var(--t-stroke, #1a1a1a);
+ background: #000;
+ border: 1px solid var(--stroke);
display: flex;
align-items: center;
justify-content: center;
@@ -305,10 +305,10 @@
width: 100%;
height: 100%;
--poster-color: transparent;
- background: var(--t-bg-0, #000);
+ background: #000;
}
.agp-preview-empty {
- color: var(--t-ink-faint, #555);
+ color: var(--ink-dim);
font-size: 12.5px;
text-align: center;
padding: 0 16px;
@@ -317,14 +317,14 @@
.agp-preview-name {
font-size: 15px;
font-weight: 600;
- color: var(--t-ink, #e8e8e8);
+ color: var(--ink);
margin: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.agp-preview-sub {
- color: var(--t-ink-dim, #888);
+ color: var(--ink-dim);
font-size: 12px;
margin: -4px 0 0;
}
@@ -335,9 +335,9 @@
}
.agp-preview-tag {
font-size: 10.5px;
- color: var(--t-ink-dim, #888);
- background: var(--t-glass, rgba(255,255,255,0.04));
- border: 1px solid var(--t-stroke, #1a1a1a);
+ color: var(--ink-dim);
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
border-radius: 999px;
padding: 2px 8px;
}
@@ -347,8 +347,8 @@
.agp-modes {
display: flex;
gap: 3px;
- background: var(--t-bg-0, #000);
- border: 1px solid var(--t-stroke, #1a1a1a);
+ background: #000;
+ border: 1px solid var(--stroke);
border-radius: 9px;
padding: 3px;
}
@@ -363,19 +363,19 @@
padding: 6px 4px;
border-radius: 7px;
font-size: 11.5px;
- color: var(--t-ink-dim, #888);
+ color: var(--ink-dim);
transition: background 120ms ease, color 120ms ease;
}
.agp-modes input:checked + span {
- background: var(--t-glass-strong, rgba(255,255,255,0.08));
- color: var(--t-ink, #e8e8e8);
+ background: var(--surface-2);
+ color: var(--ink);
}
/* ── CTA button ─────────────────────────────────────────────────────── */
.agp-cta {
- background: var(--t-accent, #fff);
- color: var(--t-accent-ink, #000);
+ background: var(--accent);
+ color: #000;
border: 0;
border-radius: 9px;
padding: 10px 14px;
@@ -388,16 +388,16 @@
transition: opacity 120ms ease;
}
.agp-cta:disabled { opacity: 0.35; cursor: not-allowed; }
-.agp-cta.copied { background: var(--t-success, #4ade80); }
+.agp-cta.copied { background: var(--success); }
/* ── Payload footer ─────────────────────────────────────────────────── */
.agp-payload {
font-family: ui-monospace, 'SF Mono', monospace;
font-size: 11px;
- color: var(--t-ink-dim, #888);
- background: var(--t-bg-0, #000);
- border: 1px solid var(--t-stroke, #1a1a1a);
+ color: var(--ink-dim);
+ background: #000;
+ border: 1px solid var(--stroke);
border-radius: 8px;
padding: 8px 10px;
word-break: break-all;
@@ -419,8 +419,8 @@
.agp-spinner {
width: 24px;
height: 24px;
- border: 2px solid var(--t-stroke, #1a1a1a);
- border-top-color: var(--t-ink-dim, #888);
+ border: 2px solid var(--stroke);
+ border-top-color: var(--ink-dim);
border-radius: 50%;
animation: agp-spin 0.8s linear infinite;
}
@@ -430,13 +430,13 @@
grid-column: 1 / -1;
padding: 36px 16px;
text-align: center;
- color: var(--t-ink-faint, #555);
- border: 1.5px dashed var(--t-stroke, #1a1a1a);
+ color: var(--ink-dim);
+ border: 1.5px dashed var(--stroke);
border-radius: 10px;
font-size: 13px;
line-height: 1.5;
}
-.agp-error { color: var(--t-danger, #f87171); border-color: rgba(248, 113, 113, 0.2); }
+.agp-error { color: var(--danger); border-color: rgba(248, 113, 113, 0.2); }
/* ── Load more ──────────────────────────────────────────────────────── */
@@ -447,9 +447,9 @@
padding: 14px 0 4px;
}
.agp-loadmore-btn {
- background: var(--t-glass, rgba(255,255,255,0.04));
- color: var(--t-ink, #e8e8e8);
- border: 1px solid var(--t-stroke, #1a1a1a);
+ background: var(--surface-1);
+ color: var(--ink);
+ border: 1px solid var(--stroke);
border-radius: 8px;
padding: 8px 18px;
font: inherit;
@@ -458,22 +458,22 @@
transition: border-color 120ms ease, background 120ms ease;
}
.agp-loadmore-btn:hover {
- border-color: var(--t-stroke-strong, #2a2a2a);
- background: var(--t-glass-strong, rgba(255,255,255,0.08));
+ border-color: var(--stroke-strong);
+ background: var(--surface-2);
}
.agp-loadmore-btn:disabled { opacity: 0.5; cursor: not-allowed; }
/* ── Skeleton cards ─────────────────────────────────────────────────── */
.agp-skel {
- background: var(--t-bg-2, #111);
- border: 1.5px solid var(--t-stroke, #1a1a1a);
+ background: var(--surface-2);
+ border: 1.5px solid var(--stroke);
border-radius: 10px;
overflow: hidden;
}
.agp-skel-thumb {
aspect-ratio: 1 / 1;
- background: linear-gradient(110deg, var(--t-bg-3, #1a1a1a) 30%, var(--t-bg-2, #111) 50%, var(--t-bg-3, #1a1a1a) 70%);
+ background: linear-gradient(110deg, var(--surface-3) 30%, var(--surface-2) 50%, var(--surface-3) 70%);
background-size: 200% 100%;
animation: agp-shimmer 1.4s ease-in-out infinite;
}
@@ -481,7 +481,7 @@
height: 10px;
margin: 8px 10px;
border-radius: 4px;
- background: var(--t-bg-3, #1a1a1a);
+ background: var(--surface-3);
}
.agp-skel-bar:last-child { width: 55%; margin-top: 4px; }
@keyframes agp-shimmer {
@@ -494,8 +494,8 @@
.agp-source-toggle {
display: flex;
gap: 3px;
- background: var(--t-bg-0, #000);
- border: 1px solid var(--t-stroke, #1a1a1a);
+ background: #000;
+ border: 1px solid var(--stroke);
border-radius: 9px;
padding: 3px;
flex-shrink: 0;
@@ -505,7 +505,7 @@
border-radius: 7px;
font: inherit;
font-size: 12px;
- color: var(--t-ink-dim, #888);
+ color: var(--ink-dim);
background: transparent;
border: 0;
cursor: pointer;
@@ -513,11 +513,11 @@
white-space: nowrap;
}
.agp-source-btn.active {
- background: var(--t-glass-strong, rgba(255,255,255,0.08));
- color: var(--t-ink, #e8e8e8);
+ background: var(--surface-2);
+ color: var(--ink);
}
.agp-source-btn:hover:not(.active) {
- color: var(--t-ink, #e8e8e8);
+ color: var(--ink);
}
/* ── Responsive ─────────────────────────────────────────────────────── */
@@ -528,7 +528,7 @@
}
.agp-grid-col {
border-right: 0;
- border-bottom: 1px solid var(--t-stroke, #1a1a1a);
+ border-bottom: 1px solid var(--stroke);
max-height: 50vh;
}
.agp-preview-col {
diff --git a/src/avatar-page.js b/src/avatar-page.js
index 7149c20f8..1be9e5c8b 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -9,6 +9,8 @@
import { openTalkMode } from './voice/talk-mode.js';
import { downloadAvatar } from './avatar-export.js';
+import { log } from './shared/log.js';
+import { emptyStateHTML } from './shared/state-kit.js';
const ATTACHED_KEY_PREFIX = 'avatar_attached_v1:';
@@ -40,7 +42,7 @@ if (!avatarId) {
$('av-shell').innerHTML = `<div class="av-error">No avatar specified.</div>`;
} else {
init().catch((err) => {
- console.error('[avatar] init', err);
+ log.error('[avatar] init', err);
$('av-shell').innerHTML = `<div class="av-error">${esc(err.message || 'Failed to load')}</div>`;
});
}
@@ -423,7 +425,7 @@ function openDownloadMenu(ev) {
}
setTimeout(closeDownloadMenu, 1500);
} catch (err) {
- console.error('[avatar] download failed', err);
+ log.error('[avatar] download failed', err);
statusEl.textContent =
format === 'vrm' && /humanoid/i.test(err?.message || '')
? "VRM needs a humanoid skeleton — try GLB."
@@ -582,7 +584,7 @@ function bindTabs() {
btn.classList.remove('copied');
}, 1800);
} catch (err) {
- console.error('[avatar] clipboard', err);
+ log.error('[avatar] clipboard', err);
}
});
}
@@ -603,7 +605,7 @@ function bindShareButtons() {
linkBtn.classList.remove('copied');
}, 1800);
} catch (err) {
- console.error('[avatar] copy link', err);
+ log.error('[avatar] copy link', err);
}
});
}
@@ -662,7 +664,7 @@ async function openDeployOnchain() {
document.body.appendChild(wrap);
new RegisterUI(wrap, () => { wrap.remove(); }, { initial });
} catch (err) {
- console.error('[avatar] deploy on-chain failed', err);
+ log.error('[avatar] deploy on-chain failed', err);
} finally {
btn.disabled = false;
if (btn.lastChild) btn.lastChild.textContent = ' Deploy on-chain';
@@ -718,7 +720,7 @@ async function openLaunchPumpFun() {
getPreviewViewer: () => null,
});
} catch (err) {
- console.error('[avatar] launch pump.fun failed', err);
+ log.error('[avatar] launch pump.fun failed', err);
} finally {
if (btn) btn.disabled = false;
}
@@ -753,7 +755,7 @@ async function openFeesPanel() {
getUser: () => user,
});
} catch (err) {
- console.error('[avatar] open fees panel failed', err);
+ log.error('[avatar] open fees panel failed', err);
} finally {
if (btn) btn.disabled = false;
}
@@ -803,7 +805,7 @@ async function startAgentWithAvatar() {
if (!newId) throw new Error('Server did not return new agent id');
location.href = `/agent/${encodeURIComponent(newId)}/edit`;
} catch (err) {
- console.error('[avatar] start agent', err);
+ log.error('[avatar] start agent', err);
btn.textContent = original;
btn.disabled = false;
alert(err.message || 'Failed to start agent');
@@ -817,7 +819,12 @@ async function loadSkills() {
if (!list) return;
const skills = await fetchSkills();
if (!skills.length) {
- list.innerHTML = '<div class="av-list-empty">No skills available.</div>';
+ list.innerHTML = emptyStateHTML({
+ compact: true,
+ icon: '🧩',
+ title: 'No skills available',
+ body: 'Skills give this avatar new abilities — wallet, memory, animations and more. None can be attached yet; check back soon.',
+ });
return;
}
list.innerHTML = skills.map(renderSkillRow).join('');
@@ -908,7 +915,12 @@ async function loadPlugins() {
if (!list) return;
const plugins = await fetchPlugins();
if (!plugins.length) {
- list.innerHTML = '<div class="av-list-empty">No plugins published yet.</div>';
+ list.innerHTML = emptyStateHTML({
+ compact: true,
+ icon: '🔌',
+ title: 'No plugins yet',
+ body: 'Plugins are community-built tools you can attach to extend what this avatar can do. None have been published yet — yours could be the first.',
+ });
return;
}
list.innerHTML = plugins.slice(0, 20).map(renderPluginRow).join('');
@@ -1089,7 +1101,7 @@ function bindChat() {
}
if (listening) { rec.stop(); return; }
try { rec.start(); listening = true; mic.classList.add('listening'); }
- catch (err) { console.warn('[avatar] STT start', err.message); }
+ catch (err) { log.warn('[avatar] STT start', err.message); }
});
rec.onresult = (e) => {
const text = e.results[0]?.[0]?.transcript;
@@ -1125,7 +1137,7 @@ function hydrateChatHistory() {
existing.forEach((n) => n.remove());
for (const m of chatHistory) appendChatMessage(m.role, m.content);
} catch (err) {
- console.warn('[avatar] memory hydrate failed', err.message);
+ log.warn('[avatar] memory hydrate failed', err.message);
}
}
@@ -1167,7 +1179,7 @@ async function speakReply(text) {
ttsAudio.onended = () => { URL.revokeObjectURL(url); ttsAudio = null; };
await ttsAudio.play();
} catch (err) {
- console.warn('[avatar] TTS playback failed', err.message);
+ log.warn('[avatar] TTS playback failed', err.message);
}
}
@@ -1252,7 +1264,7 @@ async function sendChatMessage(text) {
} catch (err) {
assistantNode.textContent = acc || `⚠ ${err.message}`;
finalizeThought(acc || err.message);
- console.error('[avatar] chat', err);
+ log.error('[avatar] chat', err);
} finally {
cursor.remove();
send.disabled = false;
@@ -1371,7 +1383,7 @@ async function measureModel(glbUrl) {
const { fetchGlbStats } = await import('./lib/glb-stats.js');
stats = await fetchGlbStats(glbUrl);
} catch (err) {
- console.warn('[avatar] glb stats parse failed', err.message);
+ log.warn('[avatar] glb stats parse failed', err.message);
return;
}
diff --git a/src/avatar-sculpt.js b/src/avatar-sculpt.js
index a3ad11e9c..7dd5b4ef8 100644
--- a/src/avatar-sculpt.js
+++ b/src/avatar-sculpt.js
@@ -19,6 +19,7 @@
*/
import { detectFaceAll } from './avatar-face-capture.js';
+import { log } from './shared/log.js';
/* ────────────────────────────────────────────────────────────────────────── *
* Category map — orders + groups the 52 ARKit names + common body morphs
@@ -677,7 +678,7 @@ function openFaceCaptureModal({ root, working, onDirty, rerender }) {
rerender?.();
setTimeout(teardown, 1200);
} catch (err) {
- console.error('[avatar-sculpt] capture failed', err);
+ log.error('[avatar-sculpt] capture failed', err);
status.textContent = `Capture failed: ${err.message}`;
shootBtn.disabled = false;
}
diff --git a/src/avatar-sdk-page.js b/src/avatar-sdk-page.js
index e2a526b20..be9700752 100644
--- a/src/avatar-sdk-page.js
+++ b/src/avatar-sdk-page.js
@@ -195,7 +195,7 @@ document.addEventListener('DOMContentLoaded', () => {
const wrap = document.querySelector('.sdk-hero-viewer');
if (wrap) {
const msg = document.createElement('p');
- msg.style.cssText = 'text-align:center;color:var(--sdk-dim);font-size:13px;padding:24px';
+ msg.style.cssText = 'text-align:center;color:var(--ink-dim);font-size:13px;padding:24px';
msg.textContent = 'Avatar preview unavailable in this environment.';
wrap.appendChild(msg);
}
diff --git a/src/avatar-studio-demo.js b/src/avatar-studio-demo.js
index b6168b4fd..b19d87f0a 100644
--- a/src/avatar-studio-demo.js
+++ b/src/avatar-studio-demo.js
@@ -15,6 +15,7 @@ import {
applyMorphsToRoot,
renderSculptPanel,
} from './avatar-sculpt.js';
+import { log } from './shared/log.js';
const BASE_GLB = '/avatars/default.glb';
const PRESETS_URL = '/accessories/presets.json';
@@ -169,7 +170,7 @@ function wireExport() {
URL.revokeObjectURL(url);
setStatus('Exported avatar.glb');
} catch (err) {
- console.error('[studio] export failed:', err);
+ log.error('[studio] export failed:', err);
setStatus(`Export failed: ${err.message}`);
} finally {
btn.disabled = false;
@@ -207,7 +208,7 @@ function wirePresetInteraction() {
try {
await handlePresetClick(card);
} catch (err) {
- console.warn('[studio] preset click failed:', err);
+ log.warn('[studio] preset click failed:', err);
setStatus(`Failed: ${err.message}`);
}
});
@@ -222,7 +223,7 @@ function wirePresetInteraction() {
try {
await accessoryMgr.applyPreset(preset);
} catch (err) {
- console.warn('[studio] hover preview failed:', err);
+ log.warn('[studio] hover preview failed:', err);
}
}, true);
@@ -233,7 +234,7 @@ function wirePresetInteraction() {
try {
await revertToCommitted();
} catch (err) {
- console.warn('[studio] revert failed:', err);
+ log.warn('[studio] revert failed:', err);
}
}, true);
}
@@ -473,7 +474,7 @@ window.addEventListener('pagehide', () => {
// ── Init ──────────────────────────────────────────────────────────────────────
boot().catch((err) => {
- console.error('[avatar-studio] boot failed:', err);
+ log.error('[avatar-studio] boot failed:', err);
setStatus(`Failed to initialize: ${err.message}`);
$('#as-viewport-loader')?.classList.add('hidden');
});
diff --git a/src/avatar-studio.js b/src/avatar-studio.js
index ab4e32624..841d91008 100644
--- a/src/avatar-studio.js
+++ b/src/avatar-studio.js
@@ -36,6 +36,7 @@ import {
clearDraft as clearDraftStorage,
DRAFT_KEY,
} from './avatar-studio-utils.js';
+import { log } from './shared/log.js';
const BASE_GLB_URL = '/avatars/default.glb';
const MAX_HISTORY = 50;
@@ -69,7 +70,7 @@ let searchQuery = '';
function queueOp(fn) {
const next = opQueue.then(fn).catch((err) => {
- console.warn('[avatar-studio] queued op failed:', err);
+ log.warn('[avatar-studio] queued op failed:', err);
});
opQueue = next;
return next;
@@ -125,7 +126,7 @@ const EYE_OFF =
// ── Init ─────────────────────────────────────────────────────────────
init().catch((err) => {
- console.error('[avatar-studio] init', err);
+ log.error('[avatar-studio] init', err);
$('as-shell').innerHTML = `<div class="as-error">${esc(err.message || 'Failed to load')}</div>`;
});
@@ -1190,7 +1191,7 @@ async function saveAvatar() {
// Log for debugging but don't block the save — the avatar will look right,
// it just won't be re-editable via ?edit= until this is retried.
const body = await patchRes.json().catch(() => ({}));
- console.warn('[avatar-studio] appearance PATCH failed (non-fatal):', body);
+ log.warn('[avatar-studio] appearance PATCH failed (non-fatal):', body);
}
}
updateProgress(92);
@@ -1200,7 +1201,7 @@ async function saveAvatar() {
try {
await uploadAvatarSnapshot({ avatarId: avatar.id, scene });
} catch (err) {
- console.warn('[avatar-studio] snapshot upload failed:', err?.message);
+ log.warn('[avatar-studio] snapshot upload failed:', err?.message);
}
updateProgress(100);
@@ -1222,7 +1223,7 @@ async function saveAvatar() {
window.location.href = `/avatars/${encodeURIComponent(avatar.id)}`;
} catch (err) {
hideSaveOverlay();
- console.error('[avatar-studio] save failed:', err);
+ log.error('[avatar-studio] save failed:', err);
if (err.code === 'not_signed_in' || err.stage === 'auth') {
const next = encodeURIComponent(location.pathname + location.search);
diff --git a/src/aws-marketplace-welcome.js b/src/aws-marketplace-welcome.js
index 34ea4a1dc..908888d31 100644
--- a/src/aws-marketplace-welcome.js
+++ b/src/aws-marketplace-welcome.js
@@ -11,6 +11,7 @@
// 3. Otherwise → show Sign in tab (they may already have an account).
// After auth, call /api/aws-marketplace/link with the customer ID to attach the subscription.
+import { log } from './shared/log.js';
const p = new URLSearchParams(location.search);
const customerId = p.get('customer');
const isTrial = p.get('trial') === '1';
@@ -68,7 +69,7 @@ async function linkAndIssue() {
try {
return await issueApiKey();
} catch (err) {
- console.error('[aws-marketplace/welcome] issueApiKey failed', err);
+ log.error('[aws-marketplace/welcome] issueApiKey failed', err);
return null;
}
}
diff --git a/src/brain.js b/src/brain.js
index 3d4e130c3..b00241925 100644
--- a/src/brain.js
+++ b/src/brain.js
@@ -13,7 +13,7 @@ const PROVIDERS = [
{ key: 'groq-llama', label: 'Llama 3.3 70B', short: 'Llama 3.3', network: 'Groq', color: '#ff9a3c', ctx: '128K', tier: 'Fast' },
{ key: 'qwen-plus', label: 'Qwen Plus', short: 'Qwen+', network: 'DashScope', color: '#69db7c', ctx: '131K', tier: 'Balanced' },
{ key: 'modelscope-qwen', label: 'Qwen3-Coder 480B', short: 'Qwen3-Code', network: 'ModelScope', color: '#40c057', ctx: '32K', tier: 'Flagship' },
- { key: 'deepseek-r1', label: 'DeepSeek R1', short: 'DeepSeek', network: 'DeepSeek', color: '#b197fc', ctx: '64K', tier: 'Reasoning' },
+ { key: 'deepseek-r1', label: 'DeepSeek R1', short: 'DeepSeek', network: 'DeepSeek', color: '#888888', ctx: '64K', tier: 'Reasoning' },
{ key: 'ibm-granite', label: 'IBM Granite 3.8B', short: 'Granite', network: 'IBM watsonx.ai', color: '#0f62fe', ctx: '128K', tier: 'Balanced' },
];
const PMAP = new Map(PROVIDERS.map(p => [p.key, p]));
diff --git a/src/character.css b/src/character.css
index 8528ce559..94641fc2d 100644
--- a/src/character.css
+++ b/src/character.css
@@ -9,56 +9,6 @@ body {
color: #1a1a2e;
}
-/* ── Nav ──────────────────────────────────────────────── */
-.ch-nav {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 16px 20px;
- position: sticky;
- top: 0;
- z-index: 10;
- background: rgba(200, 223, 247, 0.6);
- backdrop-filter: blur(12px);
-}
-
-.ch-nav-brand {
- font-size: 22px;
- font-weight: 700;
- color: #1a1a2e;
- text-decoration: none;
- letter-spacing: -0.5px;
-}
-
-.ch-nav-actions {
- display: flex;
- gap: 8px;
-}
-
-.ch-btn-ghost {
- background: transparent;
- border: 1.5px solid rgba(26, 26, 46, 0.3);
- border-radius: 24px;
- padding: 8px 18px;
- font-size: 14px;
- font-weight: 500;
- color: #1a1a2e;
- cursor: pointer;
- text-decoration: none;
-}
-
-.ch-btn-primary {
- background: linear-gradient(135deg, #2563eb, #1d4ed8);
- border: none;
- border-radius: 24px;
- padding: 8px 18px;
- font-size: 14px;
- font-weight: 600;
- color: #fff;
- cursor: pointer;
- text-decoration: none;
-}
-
/* ── Hero ─────────────────────────────────────────────── */
.ch-hero {
padding: 32px 20px 0;
@@ -455,5 +405,4 @@ body {
@media (min-width: 600px) {
.ch-hero { padding: 40px 32px 0; max-width: 560px; margin: 0 auto; }
.ch-section { padding: 20px 32px 0; max-width: 560px; margin: 0 auto; }
- .ch-nav { padding: 16px 32px; }
}
diff --git a/src/characters.css b/src/characters.css
index a54442cfb..3fd3bbd00 100644
--- a/src/characters.css
+++ b/src/characters.css
@@ -9,57 +9,6 @@ body {
color: #1a1a2e;
}
-/* ── Nav ──────────────────────────────────────────────── */
-.chs-nav {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 16px 20px;
- position: sticky;
- top: 0;
- z-index: 10;
- background: rgba(200, 223, 247, 0.65);
- backdrop-filter: blur(12px);
-}
-
-.chs-nav-brand {
- font-size: 22px;
- font-weight: 700;
- color: #1a1a2e;
- text-decoration: none;
- letter-spacing: -0.5px;
-}
-
-.chs-nav-right {
- display: flex;
- gap: 8px;
- align-items: center;
-}
-
-.chs-btn-ghost {
- background: transparent;
- border: 1.5px solid rgba(26, 26, 46, 0.3);
- border-radius: 24px;
- padding: 8px 18px;
- font-size: 14px;
- font-weight: 500;
- color: #1a1a2e;
- cursor: pointer;
- text-decoration: none;
-}
-
-.chs-btn-primary {
- background: linear-gradient(135deg, #2563eb, #1d4ed8);
- border: none;
- border-radius: 24px;
- padding: 8px 18px;
- font-size: 14px;
- font-weight: 600;
- color: #fff;
- cursor: pointer;
- text-decoration: none;
-}
-
/* ── Header ───────────────────────────────────────────── */
.chs-header {
padding: 32px 20px 20px;
@@ -141,9 +90,12 @@ body {
/* ── Character card ───────────────────────────────────── */
.chs-card {
+ /* Light-theme surface — character picker has its own visual identity.
+ Structural tokens (radius, transition) align to the canonical card system. */
background: rgba(255,255,255,0.55);
backdrop-filter: blur(10px);
- border-radius: 20px;
+ border: 1px solid rgba(255,255,255,0.7);
+ border-radius: var(--card-radius, 14px);
padding: 16px;
text-decoration: none;
color: inherit;
@@ -151,15 +103,28 @@ body {
flex-direction: column;
gap: 10px;
box-shadow: 0 2px 12px rgba(0,0,0,0.06);
- transition: transform 0.15s, box-shadow 0.15s;
cursor: pointer;
+ transition:
+ border-color 0.15s ease,
+ transform 0.15s ease,
+ box-shadow 0.15s ease;
}
.chs-card:hover {
+ border-color: rgba(255,255,255,0.95);
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(0,0,0,0.1);
}
+.chs-card:active {
+ transform: translateY(0) scale(0.99);
+}
+
+.chs-card:focus-visible {
+ outline: 2px solid #2563eb;
+ outline-offset: 2px;
+}
+
.chs-card-top {
display: flex;
align-items: center;
diff --git a/src/city/city-world.js b/src/city/city-world.js
index b1d8ed00d..55069300c 100644
--- a/src/city/city-world.js
+++ b/src/city/city-world.js
@@ -3,6 +3,7 @@ import { Sky } from 'three/addons/objects/Sky.js';
import { fetchOSMData, buildCity, buildMinimapStatic, CITY_HALF } from './city-map.js';
import { CityPlayer } from './city-player.js';
import { CityCamera } from './city-camera.js';
+import { log } from '../shared/log.js';
// ── DOM refs ──────────────────────────────────────────────────────────────────
@@ -82,7 +83,7 @@ async function main() {
progress(22 + frac * 30, label);
});
} catch (err) {
- console.error('OSM fetch failed — loading empty world:', err);
+ log.error('OSM fetch failed — loading empty world:', err);
osmData = { elements: [] };
}
@@ -184,4 +185,4 @@ function updateCoords(pos) {
function delay(ms) { return new Promise(r => setTimeout(r, ms)); }
-main().catch(console.error);
+main().catch(log.error);
diff --git a/src/club-perf.js b/src/club-perf.js
index 00c57db26..469a26eeb 100644
--- a/src/club-perf.js
+++ b/src/club-perf.js
@@ -13,6 +13,7 @@
// when constructing their parts of the scene. Anything that doesn't
// exist yet is simply gated for the future; the flag set is the contract.
+import { log } from './shared/log.js';
const PROFILE_TIERS = ['high', 'medium', 'low'];
/**
@@ -188,7 +189,7 @@ export function createFrameWatchdog({
// Smooth out the EMA so we don't immediately retrigger
// while the still-warm GPU recovers.
frameAvg = slowSec * 0.9;
- try { onDowngrade?.(next); } catch (err) { console.warn('[club-perf] onDowngrade threw', err); }
+ try { onDowngrade?.(next); } catch (err) { log.warn('[club-perf] onDowngrade threw', err); }
}
} else {
slowAccum = 0;
diff --git a/src/club.js b/src/club.js
index 7a92ac4a5..57a135ddb 100644
--- a/src/club.js
+++ b/src/club.js
@@ -50,6 +50,8 @@ import { ClubCamera } from './club-camera.js';
import { ClubAudio, styleAudioFor, TRACK_LABELS } from './club-audio.js';
import { playSequence, ticketSteps } from './club-sequence.js';
import { detectProfile, PROFILES, createFrameWatchdog, isMobileLayout } from './club-perf.js';
+import { log } from './shared/log.js';
+import { emptyStateHTML } from './shared/state-kit.js';
const AVATAR_URL = '/avatars/default.glb';
const MANIFEST_URL = '/animations/manifest.json';
@@ -112,6 +114,18 @@ const feedStatusEl = document.getElementById('club-feed-status');
const lbRowsEl = document.getElementById('club-lb-rows');
const lbTabsEls = document.querySelectorAll('.club-lb-tab');
+// Upgrade the static "No tips yet" line to a guided empty state (C06). Cleared
+// by renderTipRow() the moment the first tip settles.
+if (tipFeedEl) {
+ tipFeedEl.innerHTML = emptyStateHTML({
+ compact: true,
+ live: true,
+ icon: '💸',
+ title: 'No tips yet',
+ body: 'Tip a dancer and they take the pole — every tip lands here live, paid on-chain for $0.001. Be the first.',
+ });
+}
+
function setStatus(text, { kind = 'info' } = {}) {
if (!statusEl) return;
statusEl.textContent = text;
@@ -171,6 +185,7 @@ function renderTipRow(rowLike, { live = false, prepend = true } = {}) {
const timestamp = rowLike.created_at ?? rowLike.startsAt ?? new Date().toISOString();
tipFeedEl.querySelector('.club-feed-empty')?.remove();
+ tipFeedEl.querySelector('.tws-es')?.remove();
const row = document.createElement('div');
row.className = 'club-tip-row';
if (live) row.classList.add('is-live');
@@ -237,7 +252,7 @@ async function loadInitialTips({ attempt = 0 } = {}) {
}
setFeedStatus(null);
} catch (err) {
- console.warn('[club] tip history failed', err);
+ log.warn('[club] tip history failed', err);
if (attempt === 0) {
setFeedStatus("Couldn't load tip history — retrying", 'error');
setTimeout(() => loadInitialTips({ attempt: 1 }), 4000);
@@ -265,7 +280,7 @@ function subscribeTipStream() {
try {
es = new EventSource(TIPS_STREAM_URL);
} catch (err) {
- console.warn('[club] EventSource init failed', err);
+ log.warn('[club] EventSource init failed', err);
scheduleReconnect();
return;
}
@@ -278,7 +293,7 @@ function subscribeTipStream() {
const row = JSON.parse(e.data);
renderTipRow(row, { live: true });
} catch (err) {
- console.warn('[club] tip event parse failed', err);
+ log.warn('[club] tip event parse failed', err);
}
});
es.onerror = () => {
@@ -401,7 +416,7 @@ const DANCER_META = [
{ name: 'Aria', bio: 'Neon pink fire. Classical meets street.', palette: 'pink' },
{ name: 'Nova', bio: 'Cyan ice. Fluid and hypnotic.', palette: 'cyan' },
{ name: 'Blaze', bio: 'Amber heat. Power and precision.', palette: 'amber' },
- { name: 'Luna', bio: 'Violet dream. Gravity-defying flow.', palette: 'violet' },
+ { name: 'Luna', bio: 'Lunar glow. Gravity-defying flow.', palette: 'white' },
];
class PoleStation {
@@ -994,7 +1009,7 @@ if (typeof window !== 'undefined') window.__clubAudio = audio;
// loop back to ambience. Decoupled via custom event so the station class
// stays focused on motion.
window.addEventListener('club:performance-end', () => {
- audio.fadeOutStyle().catch((err) => console.warn('[club] fadeOutStyle', err));
+ audio.fadeOutStyle().catch((err) => log.warn('[club] fadeOutStyle', err));
});
// ── Tip flow (x402 drop-in) ──────────────────────────────────────────────
@@ -1014,15 +1029,25 @@ async function tipDancer({ dancer, dance, button }) {
return;
}
+ // A tip is a real on-chain micro-payment. First-timers get the wallet/USDC
+ // explainer + guided setup before the payment modal; returning users pass
+ // straight through. Lazy-loaded so the club only pays for it on first tip.
+ try {
+ const { ensureOnchainPrimer } = await import('./shared/onchain-primer.js');
+ if (!(await ensureOnchainPrimer({ action: 'tip' }))) return;
+ } catch (err) {
+ log.warn('[club] onchain primer unavailable', err);
+ }
+
// First click on a Tip button is the user gesture browsers require to
// unlock AudioContext. Do this BEFORE opening the wallet modal so the
// gesture isn't lost by the time we settle. Failures here are
// non-fatal — the rest of the tip flow still works without audio.
try {
await audio.ensureContext();
- audio.startAmbience().catch((err) => console.warn('[club] startAmbience', err));
+ audio.startAmbience().catch((err) => log.warn('[club] startAmbience', err));
} catch (err) {
- console.warn('[club] audio unavailable', err);
+ log.warn('[club] audio unavailable', err);
}
const url = `${TIP_ENDPOINT}?dancer=${encodeURIComponent(dancer)}&dance=${encodeURIComponent(dance)}`;
@@ -1052,7 +1077,7 @@ async function tipDancer({ dancer, dance, button }) {
audio.fadeToStyle(trackName).then(() => {
const label = TRACK_LABELS[trackName] || trackName;
setStatus(`Now playing: ${label}`, { kind: 'ok' });
- }).catch((err) => console.warn('[club] fadeToStyle', err));
+ }).catch((err) => log.warn('[club] fadeToStyle', err));
}
// Local echo — renderTipRow's dedupe ring (keyed on ticket_id) drops
@@ -1389,7 +1414,7 @@ const watchdog = createFrameWatchdog({
const dropped = disco.children[disco.children.length - 1];
disco.remove(dropped);
}
- console.info('[club] downgrading profile to', nextTier);
+ log.info('[club] downgrading profile to', nextTier);
},
});
@@ -1478,7 +1503,7 @@ async function fetchLeaderboard() {
const body = await res.json();
renderLeaderboard(body.rows || []);
} catch (err) {
- console.error('[club] leaderboard fetch failed', err);
+ log.error('[club] leaderboard fetch failed', err);
// Don't blow away an already-rendered table on a transient hiccup.
if (!lbRowsEl.querySelector('.club-lb-row')) {
lbRowsEl.innerHTML = '<div class="club-lb-empty">Leaderboard unavailable.</div>';
@@ -1637,7 +1662,7 @@ startLeaderboardPolling();
bootstrap()
.catch((err) => {
- console.error('[club] bootstrap failed', err);
+ log.error('[club] bootstrap failed', err);
setStatus(`Club failed to load: ${err.message}`, { kind: 'error' });
})
.finally(() => animate());
diff --git a/src/communities.js b/src/communities.js
index 66077b286..5774822c0 100644
--- a/src/communities.js
+++ b/src/communities.js
@@ -7,6 +7,7 @@
// is the signed-in user's real avatars (/api/avatars). No mocks, no fakes — if
// a source is empty or unreachable, the UI says so and offers a way forward.
+import { log } from './shared/log.js';
const NAME_STORAGE_KEY = 'walk:player-name';
const AVATAR_CHOICE_KEY = 'communities:avatar-choice';
const DEFAULT_AVATAR_URL = '/avatars/default.glb';
@@ -220,7 +221,7 @@ async function loadTrending() {
const data = await r.json();
renderCoins(Array.isArray(data) ? data : data?.coins || []);
} catch (err) {
- console.warn('[communities] trending failed:', err?.message ?? err);
+ log.warn('[communities] trending failed:', err?.message ?? err);
renderCoinError();
}
}
@@ -341,7 +342,7 @@ async function loadCoinProfile(mint) {
const r = await fetch(`/api/pump/coin?mint=${encodeURIComponent(mint)}`, { headers: { accept: 'application/json' } });
if (r.ok) coin = await r.json();
} catch (err) {
- console.warn('[communities] coin profile', err?.message ?? err);
+ log.warn('[communities] coin profile', err?.message ?? err);
}
// User may have navigated away during the fetch.
@@ -466,7 +467,7 @@ async function loadCoinMarket(mint) {
if (lbl) lbl.textContent = g.isGraduated ? 'graduated' : 'to graduation';
}
} catch (err) {
- console.warn('[communities] coin market', err?.message ?? err);
+ log.warn('[communities] coin market', err?.message ?? err);
}
}
@@ -503,7 +504,7 @@ async function loadCoinTrades(mint) {
$('cp-trades-hint').textContent = `Last ${trades.length}`;
wrap.hidden = false;
} catch (err) {
- console.warn('[communities] coin trades', err?.message ?? err);
+ log.warn('[communities] coin trades', err?.message ?? err);
}
}
diff --git a/src/community/town.js b/src/community/town.js
index b63e6daa7..2a4c125e4 100644
--- a/src/community/town.js
+++ b/src/community/town.js
@@ -12,6 +12,7 @@
import { fetchCapabilities, fetchMessages, connectRealtime } from './town-client.js';
import { getSession, signInWithX, ensureSolanaWallet, postAsUser, logout } from './town-auth.js';
+import { log } from '../shared/log.js';
const MAX_BUBBLES = 4;
const BUBBLE_TTL_MS = 7000;
@@ -531,7 +532,7 @@ export class Town {
onLike: (evt) => this._applyLike(evt),
});
} catch (err) {
- console.warn('[town] realtime unavailable:', err?.message ?? err);
+ log.warn('[town] realtime unavailable:', err?.message ?? err);
this._setStatus('offline');
}
}
diff --git a/src/constellation/main.js b/src/constellation/main.js
index 8c1b14fcb..f843c0ee6 100644
--- a/src/constellation/main.js
+++ b/src/constellation/main.js
@@ -489,7 +489,7 @@ async function init() {
setStatus('live', `Embedded by IBM&nbsp;Granite · <code>${escapeHtml(model || EMBED_MODEL_HINT)}</code> · ${dimensions || dim}d`);
} catch (e) {
if (e.code === 'watsonx_unconfigured') {
- setStatus('off', 'IBM watsonx not configured — showing tokens by trending rank. <a href="/ibm" style="color:var(--ibm-light)">Enable →</a>');
+ setStatus('off', 'IBM watsonx not configured — showing tokens by trending rank. <a href="/ibm" style="color:var(--brand-blue-light)">Enable →</a>');
} else if (e.status === 404) {
setStatus('off', 'Granite embeddings endpoint not deployed yet — showing tokens by trending rank.');
} else {
diff --git a/src/create-review-features.js b/src/create-review-features.js
index ded8deb15..9eb263af0 100644
--- a/src/create-review-features.js
+++ b/src/create-review-features.js
@@ -13,6 +13,7 @@
import { openTalkMode } from './voice/talk-mode.js';
import { downloadAvatar } from './avatar-export.js';
+import { log } from './shared/log.js';
// ── Feature-preview modal ────────────────────────────────────────────────────
@@ -341,7 +342,7 @@ export async function openIdentityModal(ctx = {}) {
link.removeAttribute('href');
link.style.pointerEvents = 'none';
card.querySelector('[data-explorer-hint]').hidden = true;
- console.warn('[identity-preview] keypair gen failed', err);
+ log.warn('[identity-preview] keypair gen failed', err);
}
}
@@ -611,7 +612,7 @@ export default function Page() {
skel.hidden = true;
}, 'image/png');
} catch (err) {
- console.warn('[embed-preview] canvas snapshot failed', err);
+ log.warn('[embed-preview] canvas snapshot failed', err);
}
} else {
skel.textContent = 'Preview will render here once your avatar is loaded.';
@@ -695,7 +696,7 @@ export function openDownloadModal(ctx) {
statusEl.textContent = `Saved ${result.filename} · ${prettyBytes(result.size)}`;
statusEl.dataset.tone = 'ok';
} catch (err) {
- console.error('[create-review] download failed', err);
+ log.error('[create-review] download failed', err);
statusEl.textContent =
err?.message?.includes('humanoid') && format === 'vrm'
? "Couldn't write VRM — this avatar's skeleton isn't humanoid enough. Try GLB instead."
diff --git a/src/create-review.js b/src/create-review.js
index ed80770b4..04942ce77 100644
--- a/src/create-review.js
+++ b/src/create-review.js
@@ -36,6 +36,7 @@ import {
slugify,
toggleEmoteStrip,
} from './create-review-features.js';
+import { log } from './shared/log.js';
const RESUME_KEY = '3dagent:guest-avatar-resume';
const $ = (sel) => document.querySelector(sel);
@@ -64,7 +65,7 @@ async function boot() {
// Kick off the 3D mount but don't block UI wiring on it — the loading
// overlay stays up until renderPreview() resolves and hides it.
renderPreview(staged).catch((err) => {
- console.error('[create-review] renderPreview failed', err);
+ log.error('[create-review] renderPreview failed', err);
});
wireControls();
@@ -104,7 +105,7 @@ async function renderPreview(record) {
try {
await viewerScene.mount({ container, glbBlob: record.blob, cameraPreset: 'full' });
} catch (err) {
- console.error('[create-review] failed to mount viewer', err);
+ log.error('[create-review] failed to mount viewer', err);
$('#viewer-loading').innerHTML =
'<span style="color:#ffb3b3">Couldn\'t render this model.</span>';
return;
@@ -126,7 +127,7 @@ async function renderPreview(record) {
// it before requesting. Prefer the calmer breathing loop; fall back to the
// plain idle clip if breathing isn't in the manifest.
playBaseIdle().catch((err) =>
- console.warn('[create-review] base idle failed', err),
+ log.warn('[create-review] base idle failed', err),
);
}
@@ -356,9 +357,12 @@ async function onSave({ auto = false } = {}) {
// If the user backgrounded the tab, ping a Notification so they know to
// come back. Best-effort: silently no-ops if permission was never granted.
notifySaveComplete(name);
+ // Mark the "create your first avatar" step of the getting-started guide
+ // done at the true completion point, before we navigate away.
+ try { window.__twsGuide?.complete('create'); } catch (_) {}
window.location.href = '/app?agent=' + agent.id;
} catch (err) {
- console.error('[create-review] save failed', err);
+ log.error('[create-review] save failed', err);
setSaveCancellable(false);
if (err.code === 'upload_aborted') {
@@ -750,6 +754,6 @@ function showStatus(msg, type = 'info') {
window.addEventListener('beforeunload', releaseObjectUrl);
boot().catch((err) => {
- console.error('[create-review] boot failed', err);
+ log.error('[create-review] boot failed', err);
setPageState('empty');
});
diff --git a/src/create-video.js b/src/create-video.js
index 48986a64a..345f6db3d 100644
--- a/src/create-video.js
+++ b/src/create-video.js
@@ -212,7 +212,7 @@ async function startGeneration() {
if (!res.ok) {
const e = await res.json().catch(() => ({}));
if (res.status === 402 && e.error === 'free_trial_used') {
- showResult('error', 'You've used your 1 free video. Upgrade to generate more.');
+ showResult('error', 'You\'ve used your 1 free video. Upgrade to generate more.');
retryBtn.textContent = 'Upgrade plan';
retryBtn.onclick = () => { window.location.href = '/dashboard'; };
generateBtn.disabled = false;
diff --git a/src/create.js b/src/create.js
index a0ead15a9..1f225e8b6 100644
--- a/src/create.js
+++ b/src/create.js
@@ -1,6 +1,7 @@
import { apiFetch } from './account.js';
import { AvatarCreator } from './avatar-creator.js';
import { stage as stageGuestAvatar } from './guest-avatar.js';
+import { log } from './shared/log.js';
// GLB magic bytes: ASCII "glTF"
const GLB_MAGIC = [0x67, 0x6c, 0x54, 0x46];
@@ -101,7 +102,7 @@ async function handleFork(avatarId) {
window.location.href = '/create-review';
} catch (err) {
hideSaveOverlay();
- console.error('[create] fork failed:', err);
+ log.error('[create] fork failed:', err);
showStatus(err.message || 'Could not remix this avatar. Try again.', 'error');
}
}
@@ -237,7 +238,7 @@ async function stageAndReview(blob, meta = {}) {
await stageGuestAvatar(blob, meta);
} catch (err) {
hideSaveOverlay();
- console.error('[create] failed to stage guest avatar:', err);
+ log.error('[create] failed to stage guest avatar:', err);
showStatus('Could not save your avatar locally. Check browser storage settings.', 'error');
return;
}
diff --git a/src/cz-flow.js b/src/cz-flow.js
index 91e6aeb0a..285e4d8d4 100644
--- a/src/cz-flow.js
+++ b/src/cz-flow.js
@@ -3,6 +3,7 @@
*/
import { ensureWallet, getIdentityRegistry } from './erc8004/agent-registry.js';
+import { log } from './shared/log.js';
/**
* Start the claim flow based on the current state.
@@ -107,7 +108,7 @@ export function mountEmbedCopy(container, { state }) {
button.textContent = orig;
}, 2000);
} catch (err) {
- console.error('Copy failed:', err);
+ log.error('Copy failed:', err);
button.textContent = 'Copy failed';
setTimeout(() => {
button.textContent = 'Copy embed';
diff --git a/src/demo/os-combined.js b/src/demo/os-combined.js
index ac11d2f40..6ce33e0d3 100644
--- a/src/demo/os-combined.js
+++ b/src/demo/os-combined.js
@@ -30,6 +30,7 @@ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
import { FilesetResolver, FaceLandmarker } from '@mediapipe/tasks-vision';
import { TRIANGULATION } from './triangulation.js';
+import { log } from '../shared/log.js';
const MODEL_URL =
'https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task';
@@ -242,7 +243,7 @@ btnBuild.addEventListener('click', async () => {
setStatus(exportStatus, 'ready to export');
} catch (err) {
setStatus(buildStatus, `build failed: ${err.message}`, 'err');
- console.error('[os-combined] build failed', err);
+ log.error('[os-combined] build failed', err);
} finally {
btnBuild.disabled = false;
}
diff --git a/src/demo/os-selfie.js b/src/demo/os-selfie.js
index a47a3c077..a3afb1f23 100644
--- a/src/demo/os-selfie.js
+++ b/src/demo/os-selfie.js
@@ -35,6 +35,7 @@ import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
import { FilesetResolver, FaceLandmarker } from '@mediapipe/tasks-vision';
import { TRIANGULATION } from './triangulation.js';
+import { log } from '../shared/log.js';
const MODEL_URL =
'https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task';
@@ -241,7 +242,7 @@ btnBuild.addEventListener('click', async () => {
setStatus(exportStatus, 'ready to export');
} catch (err) {
setStatus(buildStatus, `build failed: ${err.message}`, 'err');
- console.error('[os-selfie] build failed', err);
+ log.error('[os-selfie] build failed', err);
} finally {
btnBuild.disabled = false;
}
diff --git a/src/element.js b/src/element.js
index a4a51ada2..49cd08ca7 100644
--- a/src/element.js
+++ b/src/element.js
@@ -24,6 +24,7 @@ import { protocol, ACTION_TYPES } from './agent-protocol.js';
import { AgentAvatar } from './agent-avatar.js';
// END:EMBED_BRIDGES_IMPORT
import { AgentNotifier } from './agent-notifier.js';
+import { log } from './shared/log.js';
const MODES = ['inline', 'floating', 'section', 'fullscreen'];
@@ -386,7 +387,7 @@ const BASE_STYLE = `
.alert-banner button:hover { opacity: 1; }
/* Rich token card unfurl rendered inline in chat */
.token-card { margin: 6px 0; padding: 10px 12px; background: rgba(0,0,0,.25); border: 1px solid rgba(255,255,255,.08); border-radius: 10px; font: 12px var(--agent-chat-font); color: var(--agent-on-surface); }
- .token-card.solana { border-left: 3px solid #c084fc; }
+ .token-card.solana { border-left: 3px solid rgba(255,255,255,0.3); }
.token-card-header { display: flex; align-items: center; gap: 8px; }
.token-card-symbol { font: 700 14px var(--agent-chat-font); }
.token-card-name { opacity: .7; }
@@ -395,7 +396,7 @@ const BASE_STYLE = `
.token-card-stat .label { font: 600 9px/1 var(--agent-chat-font); letter-spacing: .06em; text-transform: uppercase; opacity: .5; }
.token-card-stat .value { font: 600 13px var(--agent-chat-font); font-variant-numeric: tabular-nums; }
.token-card-bar { margin-top: 8px; height: 6px; background: rgba(255,255,255,.08); border-radius: 999px; overflow: hidden; }
- .token-card-bar .fill { height: 100%; background: linear-gradient(90deg, #3b82f6, #c084fc); transition: width .4s; }
+ .token-card-bar .fill { height: 100%; background: linear-gradient(90deg, #3b82f6, rgba(255,255,255,0.7)); transition: width .4s; }
.token-card-bar .fill.danger { background: linear-gradient(90deg, #f59e0b, #ef4444); }
.token-card .flags { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 6px; }
.token-card .flag { font: 600 9px/1 var(--agent-chat-font); letter-spacing: .04em; text-transform: uppercase; padding: 3px 6px; border-radius: 4px; background: rgba(239,68,68,.18); color: #fecaca; border: 1px solid rgba(239,68,68,.32); }
@@ -1405,7 +1406,7 @@ class Agent3DElement extends HTMLElement {
}
}
} catch (_e) {
- console.warn('[agent-3d] embed-policy fetch failed; continuing', _e);
+ log.warn('[agent-3d] embed-policy fetch failed; continuing', _e);
}
}
@@ -1508,7 +1509,7 @@ class Agent3DElement extends HTMLElement {
}),
);
} catch (e) {
- console.warn('[agent-3d] skill load failed', spec, e);
+ log.warn('[agent-3d] skill load failed', spec, e);
}
}
@@ -1540,7 +1541,7 @@ class Agent3DElement extends HTMLElement {
}
}
} catch (e) {
- console.warn('[agent-3d] skill-access fetch failed; defaulting to allow-all', e);
+ log.warn('[agent-3d] skill-access fetch failed; defaulting to allow-all', e);
}
}
@@ -1577,7 +1578,7 @@ class Agent3DElement extends HTMLElement {
} catch (e) {
// Empathy is non-essential — embed still works without it. Log so
// integrators can see the failure during development.
- console.warn('[agent-3d] AgentAvatar attach failed; continuing without empathy/lipsync', e);
+ log.warn('[agent-3d] AgentAvatar attach failed; continuing without empathy/lipsync', e);
this._avatar = null;
}
@@ -1795,7 +1796,7 @@ class Agent3DElement extends HTMLElement {
// LiveKit realtime voice — connect when voice="livekit" and agent-id is set
if (this.getAttribute('voice') === 'livekit' && _backendId) {
this._connectLiveKit(_backendId).catch((err) => {
- console.warn('[agent-3d] LiveKit connect failed', err);
+ log.warn('[agent-3d] LiveKit connect failed', err);
});
}
@@ -1828,7 +1829,7 @@ class Agent3DElement extends HTMLElement {
}),
);
} catch (err) {
- console.error('[agent-3d] boot failed', err);
+ log.error('[agent-3d] boot failed', err);
this._loadingEl.hidden = true;
// Resolve errors should already have been caught and replaced with the
// default-avatar manifest in _resolveManifest. Anything reaching here is
@@ -1870,7 +1871,7 @@ class Agent3DElement extends HTMLElement {
try {
return await resolveByAvatarId(avatarIdAttr, { origin: apiBase });
} catch (err) {
- console.warn(
+ log.warn(
'[agent-3d] avatar-id resolve failed, using default avatar:',
err,
);
@@ -1878,7 +1879,7 @@ class Agent3DElement extends HTMLElement {
}
}
if (src) {
- if (agentIdAttr) console.warn('[agent-3d] both src and agent-id provided; using src');
+ if (agentIdAttr) log.warn('[agent-3d] both src and agent-id provided; using src');
// Plain .glb / .gltf URLs are bare bodies, not manifests — treat
// them as if `body=` had been set so users don't need to know the
// distinction.
@@ -1932,7 +1933,7 @@ class Agent3DElement extends HTMLElement {
return await resolveAgentById(agentIdAttr);
} catch (err) {
// Never let avatar rendering error out — fall back to default avatar.
- console.warn('[agent-3d] agent resolve failed, using default avatar:', err);
+ log.warn('[agent-3d] agent resolve failed, using default avatar:', err);
return this._defaultFallbackManifest();
}
}
@@ -2427,7 +2428,7 @@ class Agent3DElement extends HTMLElement {
const text = await this._runtime.listen();
if (text) this.say(text, { voice: true });
} catch (e) {
- console.warn('[agent-3d] listen failed', e);
+ log.warn('[agent-3d] listen failed', e);
} finally {
this._listening = false;
this._micEl.dataset.listening = 'false';
@@ -2453,7 +2454,7 @@ class Agent3DElement extends HTMLElement {
});
if (!resp.ok) {
const body = await resp.json().catch(() => ({}));
- console.warn('[agent-3d] livekit-token fetch failed', resp.status, body);
+ log.warn('[agent-3d] livekit-token fetch failed', resp.status, body);
return;
}
const { token, serverUrl } = await resp.json();
diff --git a/src/embed-action-bridge.js b/src/embed-action-bridge.js
index ef2858af0..4e3123af9 100644
--- a/src/embed-action-bridge.js
+++ b/src/embed-action-bridge.js
@@ -2,6 +2,7 @@
// Translates host requests into AgentProtocol events and mirrors agent events back to the host.
// See specs/EMBED_SPEC.md §Bridge Protocol
+import { log } from './shared/log.js';
const PROTOCOL_VERSION = 1;
const MAX_QUEUED_EVENTS = 256;
@@ -108,7 +109,7 @@ export class EmbedActionBridge {
const list = this._getClips();
return Array.isArray(list) ? list : [];
} catch (err) {
- console.warn('[embed-action-bridge] getClips failed', err);
+ log.warn('[embed-action-bridge] getClips failed', err);
return [];
}
}
@@ -149,7 +150,7 @@ export class EmbedActionBridge {
// message we use the referrer-derived origin (best effort); after we lock,
// we use the host's actual origin.
if (!this._parentOrigin) {
- console.warn('[embed-action-bridge] parent origin unknown; dropping', msg.op);
+ log.warn('[embed-action-bridge] parent origin unknown; dropping', msg.op);
return;
}
this._win.parent.postMessage(
diff --git a/src/first-meet.css b/src/first-meet.css
index 849622d70..006a8d323 100644
--- a/src/first-meet.css
+++ b/src/first-meet.css
@@ -1,4 +1,4 @@
-/* first-meet.css — scoped under .first-meet-root */
+/* first-meet.css — scoped under .first-meet-root and .fm-* */
.first-meet-root {
position: fixed;
@@ -87,7 +87,7 @@
}
.fm-btn-share:hover {
- background: #e8e8e8;
+ background: var(--ink);
}
.fm-btn-continue {
@@ -123,19 +123,413 @@
}
}
+/* ── Screen-reader live region ────────────────────────────────────────────── */
+
+.fm-sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip: rect(0 0 0 0);
+ white-space: nowrap;
+ pointer-events: none;
+}
+
+/* ── Coach-mark spotlight ─────────────────────────────────────────────────── */
+
+/*
+ * A fixed div anchored to the target's bounding rect; the massive box-shadow
+ * dims everything else without needing to fight stacking contexts on the target.
+ */
+.fm-spotlight {
+ position: fixed;
+ border-radius: 16px;
+ pointer-events: none;
+ z-index: 9820;
+ opacity: 0;
+ transition:
+ opacity 0.2s ease,
+ top 0.22s ease,
+ left 0.22s ease,
+ width 0.22s ease,
+ height 0.22s ease;
+}
+
+.fm-spotlight.fm-spotlight-on {
+ opacity: 1;
+ box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.65);
+}
+
+/* ── Tour bubble ──────────────────────────────────────────────────────────── */
+
+.fm-tour-bubble {
+ position: fixed;
+ z-index: 9825;
+ width: 300px;
+ background: #111111;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 14px;
+ padding: 18px 20px 16px;
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.7);
+ color: var(--ink);
+ font-family: 'Inter', system-ui, -apple-system, sans-serif;
+ font-size: 13px;
+ line-height: 1.55;
+ animation: fm-bubble-in 0.18s ease both;
+}
+
+@keyframes fm-bubble-in {
+ from { opacity: 0; transform: translateY(8px); }
+ to { opacity: 1; transform: translateY(0); }
+}
+
+.fm-tour-meta {
+ font-size: 11px;
+ font-weight: 600;
+ color: rgba(255, 255, 255, 0.3);
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ margin-bottom: 7px;
+}
+
+.fm-tour-title {
+ font-size: 15px;
+ font-weight: 600;
+ color: #ffffff;
+ margin-bottom: 7px;
+ line-height: 1.3;
+}
+
+.fm-tour-body {
+ margin: 0 0 14px;
+ color: rgba(255, 255, 255, 0.6);
+ font-size: 13px;
+}
+
+.fm-tour-nav {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.fm-tour-ghost {
+ background: transparent;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: rgba(255, 255, 255, 0.5);
+ border-radius: 8px;
+ padding: 6px 12px;
+ font-size: 12px;
+ font-weight: 500;
+ cursor: pointer;
+ font-family: inherit;
+ transition: background 0.14s, color 0.14s;
+ line-height: 1;
+}
+
+.fm-tour-ghost:hover {
+ background: rgba(255, 255, 255, 0.06);
+ color: var(--ink);
+}
+
+.fm-tour-ghost:focus-visible {
+ outline: 2px solid #3d7eff;
+ outline-offset: 2px;
+}
+
+.fm-tour-skip {
+ margin-right: auto;
+}
+
+.fm-tour-primary {
+ background: #ffffff;
+ color: #0a0a0f;
+ border: none;
+ border-radius: 8px;
+ padding: 6px 14px;
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ font-family: inherit;
+ line-height: 1;
+ transition: background 0.14s, transform 0.1s;
+}
+
+.fm-tour-primary:hover {
+ background: #e0e0e0;
+}
+
+.fm-tour-primary:active {
+ transform: scale(0.97);
+}
+
+.fm-tour-primary:focus-visible {
+ outline: 2px solid #3d7eff;
+ outline-offset: 2px;
+}
+
+/* ── Next-steps checklist panel ───────────────────────────────────────────── */
+
+.fm-checklist-panel {
+ position: fixed;
+ bottom: 24px;
+ right: 24px;
+ z-index: 9810;
+ width: 284px;
+ background: #111111;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 14px;
+ box-shadow: 0 16px 48px rgba(0, 0, 0, 0.65);
+ font-family: 'Inter', system-ui, -apple-system, sans-serif;
+ font-size: 13px;
+ color: var(--ink);
+ opacity: 0;
+ transform: translateY(10px);
+ transition: opacity 0.28s ease, transform 0.28s ease;
+}
+
+.fm-checklist-panel.fm-cl-visible {
+ opacity: 1;
+ transform: translateY(0);
+}
+
+.fm-cl-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 12px 14px 10px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.07);
+}
+
+.fm-cl-title {
+ font-size: 12px;
+ font-weight: 600;
+ color: rgba(255, 255, 255, 0.9);
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+}
+
+.fm-cl-dismiss {
+ background: none;
+ border: none;
+ color: rgba(255, 255, 255, 0.35);
+ font-size: 17px;
+ line-height: 1;
+ cursor: pointer;
+ padding: 0 2px;
+ transition: color 0.14s;
+ font-family: inherit;
+}
+
+.fm-cl-dismiss:hover { color: rgba(255, 255, 255, 0.8); }
+
+.fm-cl-dismiss:focus-visible {
+ outline: 2px solid #3d7eff;
+ outline-offset: 2px;
+ border-radius: 4px;
+}
+
+.fm-cl-list {
+ margin: 0;
+ padding: 6px 0 8px;
+ list-style: none;
+}
+
+.fm-cl-item {
+ display: flex;
+ align-items: flex-start;
+ gap: 10px;
+ padding: 7px 14px;
+}
+
+.fm-cl-check {
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+ border: 1.5px solid rgba(255, 255, 255, 0.18);
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ margin-top: 1px;
+ transition: border-color 0.15s, background 0.15s;
+ color: var(--success);
+}
+
+.fm-cl-item.is-done .fm-cl-check {
+ border-color: var(--success);
+ background: rgba(74, 222, 128, 0.12);
+}
+
+.fm-cl-content {
+ flex: 1;
+ min-width: 0;
+}
+
+.fm-cl-label {
+ display: block;
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--ink);
+ text-decoration: none;
+ line-height: 1.3;
+}
+
+.fm-cl-label.fm-cl-link:hover {
+ color: #fff;
+ text-decoration: underline;
+}
+
+.fm-cl-label.fm-cl-link:focus-visible {
+ outline: 2px solid #3d7eff;
+ outline-offset: 2px;
+ border-radius: 2px;
+}
+
+.fm-cl-item.is-done .fm-cl-label {
+ color: rgba(255, 255, 255, 0.4);
+ text-decoration: line-through;
+}
+
+.fm-cl-sub {
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.35);
+ margin-top: 2px;
+ line-height: 1.35;
+}
+
+.fm-cl-mono {
+ font-family: 'SF Mono', 'Fira Code', ui-monospace, monospace;
+ font-size: 10px;
+ word-break: break-all;
+}
+
+/* Optional / accordion item */
+
+.fm-cl-toggle {
+ background: none;
+ border: none;
+ padding: 0;
+ margin: 0;
+ font-size: 13px;
+ font-weight: 500;
+ color: rgba(255, 255, 255, 0.55);
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ font-family: inherit;
+ line-height: 1.3;
+ text-align: left;
+}
+
+.fm-cl-toggle:hover { color: var(--ink); }
+
+.fm-cl-toggle:focus-visible {
+ outline: 2px solid #3d7eff;
+ outline-offset: 2px;
+ border-radius: 2px;
+}
+
+.fm-cl-opt-tag {
+ font-size: 10px;
+ font-weight: 400;
+ color: rgba(255, 255, 255, 0.25);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 4px;
+ padding: 0 4px;
+ line-height: 1.6;
+}
+
+.fm-cl-chevron {
+ width: 10px;
+ height: 10px;
+ flex-shrink: 0;
+ transition: transform 0.18s ease;
+ opacity: 0.45;
+}
+
+.fm-cl-chevron.open {
+ transform: rotate(180deg);
+}
+
+.fm-cl-collapse {
+ overflow: hidden;
+ max-height: 0;
+ transition: max-height 0.2s ease;
+}
+
+.fm-cl-collapse.open {
+ max-height: 72px;
+}
+
+.fm-cl-cta {
+ display: inline-block;
+ margin-top: 5px;
+ font-size: 12px;
+ color: rgba(255, 255, 255, 0.45);
+ text-decoration: none;
+}
+
+.fm-cl-cta:hover { color: var(--ink); text-decoration: underline; }
+.fm-cl-cta:focus-visible { outline: 2px solid #3d7eff; outline-offset: 2px; border-radius: 2px; }
+
+/* Share copy button */
+
+.fm-cl-copy {
+ display: inline-block;
+ margin-top: 5px;
+ background: rgba(255, 255, 255, 0.05);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 6px;
+ color: rgba(255, 255, 255, 0.55);
+ font-size: 11.5px;
+ padding: 3px 10px;
+ cursor: pointer;
+ font-family: inherit;
+ transition: background 0.14s, color 0.14s;
+ line-height: 1.5;
+}
+
+.fm-cl-copy:hover {
+ background: rgba(255, 255, 255, 0.09);
+ color: var(--ink);
+}
+
+.fm-cl-copy:focus-visible {
+ outline: 2px solid #3d7eff;
+ outline-offset: 2px;
+}
+
/* ── Reduced motion overrides ─────────────────────────────────────────────── */
@media (prefers-reduced-motion: reduce) {
- .fm-fade-overlay {
+ .fm-fade-overlay,
+ .fm-subtitle,
+ .fm-actions {
transition: none;
}
- .fm-subtitle {
+
+ .fm-confetti-piece {
+ display: none;
+ }
+
+ .fm-spotlight {
transition: none;
}
- .fm-actions {
+
+ .fm-tour-bubble {
+ animation: none;
+ }
+
+ .fm-checklist-panel {
transition: none;
}
- .fm-confetti-piece {
- display: none;
+
+ .fm-cl-collapse {
+ transition: none;
+ }
+
+ .fm-cl-chevron {
+ transition: none;
}
}
diff --git a/src/first-meet.js b/src/first-meet.js
index d0e5dc8c1..2e5a4a7ce 100644
--- a/src/first-meet.js
+++ b/src/first-meet.js
@@ -2,12 +2,13 @@
* playFirstMeet — first-encounter celebration sequence for a newly generated avatar.
*
* @param {object} opts
- * @param {object} opts.viewer — SceneController / AgentAvatar (duck-typed: .playClip(name) OR .mixer + .animations)
- * @param {{ id: string, name: string, slug: string }} opts.agent
+ * @param {object} opts.viewer — SceneController / AgentAvatar (duck-typed: .playClip(name) OR .mixer + .animations). Pass null if no 3D viewer.
+ * @param {{ id: string, name: string }} opts.agent
* @param {() => void} opts.onShare — called when user clicks "Share"
* @param {() => void} opts.onContinue — called when user clicks "Continue"
* @returns {Promise<void>} resolves when user clicks either button
*/
+import { log } from './shared/log.js';
export async function playFirstMeet({ viewer, agent, onShare, onContinue }) {
const reducedMotion =
typeof window !== 'undefined' &&
@@ -22,17 +23,24 @@ export async function playFirstMeet({ viewer, agent, onShare, onContinue }) {
document.head.appendChild(link);
}
- // Build root overlay
+ // Build root overlay — a full-screen celebration sequence, not a classic dialog,
+ // but acts as a modal region so screen readers treat it as one.
+ const subtitleId = `fm-label-${Math.trunc(performance.now())}`;
const root = document.createElement('div');
root.className = 'first-meet-root';
+ root.setAttribute('role', 'dialog');
+ root.setAttribute('aria-modal', 'true');
+ root.setAttribute('aria-labelledby', subtitleId);
- // Fade overlay (black → transparent)
+ // Fade overlay (black → transparent) — decorative, hidden from AT
const overlay = document.createElement('div');
overlay.className = 'fm-fade-overlay';
+ overlay.setAttribute('aria-hidden', 'true');
- // Subtitle
+ // Subtitle — also serves as the accessible dialog label via aria-labelledby
const subtitle = document.createElement('div');
subtitle.className = 'fm-subtitle';
+ subtitle.id = subtitleId;
subtitle.textContent = `Hello, I'm ${agent?.name ?? 'your agent'}.`;
// Action buttons
@@ -68,7 +76,7 @@ export async function playFirstMeet({ viewer, agent, onShare, onContinue }) {
// 4. Scripted bone tilt via viewer.mixer + content skeleton
// — bones probed: 'mixamorigRightHand', 'RightHand', 'mixamorigRightArm', 'RightArm'
function tryWave() {
- if (reducedMotion) return;
+ if (reducedMotion || !viewer) return;
// Method 1 & 2: direct clip by name
if (typeof viewer?.playClip === 'function') {
@@ -189,7 +197,339 @@ export async function playFirstMeet({ viewer, agent, onShare, onContinue }) {
btnContinue.addEventListener('click', () => {
cleanup();
onContinue?.();
+ // Launch guided tour unless already completed
+ if (!localStorage.getItem(TOUR_DONE_KEY)) {
+ runTour(agent).catch(log.error);
+ }
resolve();
});
});
}
+
+// ── Tour constants ─────────────────────────────────────────────────────────────
+
+const TOUR_DONE_KEY = 'threews:tour:done';
+
+// ── Utility ───────────────────────────────────────────────────────────────────
+
+function waitForEl(selector, timeoutMs = 3000) {
+ return new Promise((resolve) => {
+ const el = document.querySelector(selector);
+ if (el) return resolve(el);
+ const obs = new MutationObserver(() => {
+ const found = document.querySelector(selector);
+ if (found) { obs.disconnect(); resolve(found); }
+ });
+ obs.observe(document.body, { childList: true, subtree: true });
+ setTimeout(() => { obs.disconnect(); resolve(null); }, timeoutMs);
+ });
+}
+
+function escHtml(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
+ }[c]));
+}
+
+// ── Coach-mark tour ───────────────────────────────────────────────────────────
+
+async function runTour(agent) {
+ if (localStorage.getItem(TOUR_DONE_KEY)) return;
+
+ const STEPS = [
+ {
+ selectors: ['.dnx-hero-card'],
+ title: 'Your agent is live',
+ body: 'Click "Live page" to preview, "Edit" to customize the look, or "Embed" to deploy on any website.',
+ },
+ {
+ selectors: ['#dnx-onboarding', '.dnx-ob'],
+ title: 'Your setup checklist',
+ body: 'Complete these steps to unlock your agent\'s full potential — from personality to payments.',
+ },
+ {
+ selectors: ['.dnx-shortcuts-grid', '.dnx-quick-card'],
+ title: 'Quick shortcuts',
+ body: 'Shortcuts to your most-used tools. Pin any page from the directory below to customize this section.',
+ },
+ ];
+
+ // Screen-reader live region
+ const liveRegion = document.createElement('div');
+ liveRegion.className = 'fm-sr-only';
+ liveRegion.setAttribute('aria-live', 'polite');
+ liveRegion.setAttribute('aria-atomic', 'true');
+ document.body.appendChild(liveRegion);
+
+ // Spotlight rect highlight
+ const spotlight = document.createElement('div');
+ spotlight.className = 'fm-spotlight';
+ spotlight.setAttribute('aria-hidden', 'true');
+ document.body.appendChild(spotlight);
+
+ // Tooltip bubble
+ const bubble = document.createElement('div');
+ bubble.className = 'fm-tour-bubble';
+ bubble.setAttribute('role', 'dialog');
+ bubble.setAttribute('aria-modal', 'false');
+ bubble.setAttribute('aria-label', 'Guided tour');
+ document.body.appendChild(bubble);
+
+ let activeTarget = null;
+ let stepIndex = 0;
+
+ function finish() {
+ liveRegion.remove();
+ spotlight.remove();
+ bubble.remove();
+ if (activeTarget) activeTarget.removeAttribute('data-fm-tour-target');
+ document.removeEventListener('keydown', keyHandler);
+ localStorage.setItem(TOUR_DONE_KEY, '1');
+ showChecklist(agent);
+ }
+
+ async function goToStep(idx) {
+ if (idx >= STEPS.length) { finish(); return; }
+
+ const step = STEPS[idx];
+ stepIndex = idx;
+
+ // Clear previous target
+ if (activeTarget) activeTarget.removeAttribute('data-fm-tour-target');
+
+ // Find target — try each selector, wait for first one
+ let target = null;
+ for (const sel of step.selectors) {
+ target = document.querySelector(sel);
+ if (target) break;
+ }
+ if (!target) {
+ target = await waitForEl(step.selectors[0], 2000);
+ }
+ if (!target) {
+ // Skip this step — element not available
+ goToStep(idx + 1);
+ return;
+ }
+
+ activeTarget = target;
+ target.setAttribute('data-fm-tour-target', '');
+
+ // Position spotlight over target
+ const rect = target.getBoundingClientRect();
+ const PAD = 8;
+ spotlight.style.top = `${rect.top - PAD}px`;
+ spotlight.style.left = `${rect.left - PAD}px`;
+ spotlight.style.width = `${rect.width + PAD * 2}px`;
+ spotlight.style.height = `${rect.height + PAD * 2}px`;
+ spotlight.classList.add('fm-spotlight-on');
+
+ // Render bubble
+ const isLast = idx === STEPS.length - 1;
+ bubble.innerHTML = `
+ <div class="fm-tour-meta">${idx + 1} / ${STEPS.length}</div>
+ <div class="fm-tour-title">${escHtml(step.title)}</div>
+ <p class="fm-tour-body">${escHtml(step.body)}</p>
+ <div class="fm-tour-nav">
+ ${idx > 0
+ ? `<button class="fm-tour-ghost" type="button" data-action="back" aria-label="Previous step">Back</button>`
+ : ''}
+ <button class="fm-tour-ghost fm-tour-skip" type="button" data-action="skip">Skip tour</button>
+ <button class="fm-tour-primary" type="button" data-action="next">
+ ${isLast ? 'Done' : 'Next →'}
+ </button>
+ </div>
+ `;
+
+ // Position bubble near target
+ positionBubble(bubble, rect);
+
+ liveRegion.textContent = `Tour step ${idx + 1} of ${STEPS.length}: ${step.title}. ${step.body}`;
+
+ // Wire buttons
+ bubble.querySelector('[data-action="next"]').addEventListener('click', () => goToStep(idx + 1));
+ bubble.querySelector('[data-action="skip"]').addEventListener('click', finish);
+ const backBtn = bubble.querySelector('[data-action="back"]');
+ if (backBtn) backBtn.addEventListener('click', () => goToStep(idx - 1));
+
+ // Move focus to primary action
+ bubble.querySelector('[data-action="next"]').focus();
+ }
+
+ function positionBubble(el, targetRect) {
+ const bw = Math.min(300, window.innerWidth - 32);
+ el.style.width = `${bw}px`;
+
+ const preferredLeft = Math.min(
+ Math.max(16, targetRect.left + targetRect.width / 2 - bw / 2),
+ window.innerWidth - bw - 16,
+ );
+ el.style.left = `${preferredLeft}px`;
+
+ const spaceBelow = window.innerHeight - targetRect.bottom;
+ if (spaceBelow >= 160) {
+ el.style.top = `${targetRect.bottom + 14}px`;
+ el.style.bottom = '';
+ } else {
+ el.style.bottom = `${window.innerHeight - targetRect.top + 14}px`;
+ el.style.top = '';
+ }
+ }
+
+ function keyHandler(e) {
+ if (e.key === 'Escape') finish();
+ if (e.key === 'ArrowRight' || e.key === 'ArrowDown') goToStep(stepIndex + 1);
+ if ((e.key === 'ArrowLeft' || e.key === 'ArrowUp') && stepIndex > 0) goToStep(stepIndex - 1);
+ }
+ document.addEventListener('keydown', keyHandler);
+
+ goToStep(0);
+}
+
+// ── Next-steps checklist ──────────────────────────────────────────────────────
+
+function showChecklist(agent) {
+ const agentId = agent?.id;
+ const shareUrl = agentId ? `${location.origin}/agent/${agentId}` : null;
+
+ const ITEMS = [
+ {
+ id: 'avatar',
+ label: 'Customize your avatar',
+ sub: 'Edit look, style, and accessories.',
+ href: '/dashboard/avatars',
+ },
+ {
+ id: 'personality',
+ label: 'Add personality',
+ sub: 'Set system prompt and AI model.',
+ href: '/brain',
+ },
+ {
+ id: 'payments',
+ label: 'Enable payments',
+ sub: 'Charge per message or set a subscription.',
+ href: '/dashboard/monetize',
+ optional: true,
+ },
+ {
+ id: 'share',
+ label: 'Share your agent',
+ sub: shareUrl ? shareUrl.replace(/^https?:\/\//, '') : 'Copy the live link.',
+ shareUrl,
+ },
+ ];
+
+ function getStored() {
+ try { return JSON.parse(localStorage.getItem('threews:checklist') || '{}'); } catch { return {}; }
+ }
+ function setStored(obj) {
+ localStorage.setItem('threews:checklist', JSON.stringify(obj));
+ }
+
+ const panel = document.createElement('div');
+ panel.className = 'fm-checklist-panel';
+ panel.setAttribute('role', 'region');
+ panel.setAttribute('aria-label', 'Next steps checklist');
+
+ let paymentsOpen = false;
+
+ function render() {
+ const stored = getStored();
+ panel.innerHTML = `
+ <div class="fm-cl-head">
+ <span class="fm-cl-title">Next steps</span>
+ <button class="fm-cl-dismiss" type="button" aria-label="Dismiss checklist">×</button>
+ </div>
+ <ul class="fm-cl-list" role="list">
+ ${ITEMS.map((item) => {
+ const done = !!stored[item.id];
+ return `
+ <li class="fm-cl-item${done ? ' is-done' : ''}${item.optional ? ' is-optional' : ''}" data-item="${item.id}">
+ <span class="fm-cl-check" aria-hidden="true">${done
+ ? `<svg viewBox="0 0 12 12" width="9" height="9" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 6.5l2.5 2.5L10 3"/></svg>`
+ : ''}</span>
+ <div class="fm-cl-content">
+ ${item.optional ? `
+ <button class="fm-cl-toggle" type="button" aria-expanded="${paymentsOpen}">
+ ${escHtml(item.label)}&nbsp;<span class="fm-cl-opt-tag">optional</span>
+ <svg class="fm-cl-chevron${paymentsOpen ? ' open' : ''}" viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M2 3.5l3 3 3-3"/></svg>
+ </button>
+ <div class="fm-cl-collapse${paymentsOpen ? ' open' : ''}">
+ <div class="fm-cl-sub">${escHtml(item.sub)}</div>
+ <a class="fm-cl-cta" href="${item.href}" data-action="${item.id}">Set up payments →</a>
+ </div>
+ ` : item.shareUrl ? `
+ <span class="fm-cl-label">${escHtml(item.label)}</span>
+ <div class="fm-cl-sub fm-cl-mono">${escHtml(item.sub)}</div>
+ <button class="fm-cl-copy" type="button" data-action="share" data-url="${escHtml(item.shareUrl)}">Copy link</button>
+ ` : `
+ <a class="fm-cl-label fm-cl-link" href="${item.href}" data-action="${item.id}">${escHtml(item.label)}</a>
+ <div class="fm-cl-sub">${escHtml(item.sub)}</div>
+ `}
+ </div>
+ </li>
+ `;
+ }).join('')}
+ </ul>
+ `;
+
+ // Dismiss
+ panel.querySelector('.fm-cl-dismiss').onclick = () => {
+ panel.classList.remove('fm-cl-visible');
+ setTimeout(() => panel.remove(), 300);
+ };
+
+ // Payments accordion toggle
+ const toggle = panel.querySelector('.fm-cl-toggle');
+ if (toggle) {
+ toggle.onclick = () => {
+ paymentsOpen = !paymentsOpen;
+ render();
+ };
+ }
+
+ // Action clicks — mark items done on click-through
+ panel.querySelectorAll('[data-action]').forEach((el) => {
+ el.addEventListener('click', (e) => {
+ const action = el.dataset.action;
+ const stored = getStored();
+
+ if (action === 'share') {
+ e.preventDefault();
+ const url = el.dataset.url;
+ if (url) {
+ navigator.clipboard?.writeText(url).then(() => {
+ el.textContent = 'Copied!';
+ setTimeout(() => { el.textContent = 'Copy link'; }, 2000);
+ }).catch(() => {
+ // Fallback: select text
+ el.textContent = url;
+ const range = document.createRange();
+ range.selectNodeContents(el);
+ window.getSelection()?.removeAllRanges();
+ window.getSelection()?.addRange(range);
+ });
+ }
+ stored.share = true;
+ setStored(stored);
+ render();
+ return;
+ }
+
+ // Mark clicked item done (optimistic)
+ if (['avatar', 'personality', 'payments'].includes(action)) {
+ stored[action] = true;
+ setStored(stored);
+ }
+ // Let link navigate
+ });
+ });
+ }
+
+ render();
+ document.body.appendChild(panel);
+
+ // Animate in on next frame
+ requestAnimationFrame(() => requestAnimationFrame(() => panel.classList.add('fm-cl-visible')));
+}
diff --git a/src/forge.js b/src/forge.js
index ee5d2fa18..1dbbab901 100644
--- a/src/forge.js
+++ b/src/forge.js
@@ -1,4 +1,7 @@
// Forge — text → 3D generator (browser client).
+import { skeletonHTML, errorStateHTML, ensureStateKitStyles } from './shared/state-kit.js';
+import { showSharePanel } from './shared/share.js';
+ensureStateKitStyles();
//
// Drives /api/forge: POST a prompt to start a job, then poll GET /api/forge?job
// until it resolves to a GLB. State transitions are driven by real API
@@ -40,6 +43,7 @@ const els = {
again: document.getElementById('again'),
retry: document.getElementById('retry'),
errorMessage: document.getElementById('error-message'),
+ forgeShareBtn: document.getElementById('forge-share-btn'),
creations: document.getElementById('creations'),
creationsGrid: document.getElementById('creations-grid'),
creationsCount: document.getElementById('creations-count'),
@@ -181,19 +185,42 @@ function showResult(glbUrl, prompt) {
`${prompt.replace(/[^a-z0-9]+/gi, '-').slice(0, 48).replace(/^-|-$/g, '') || 'forge'}.glb`,
);
showState('result');
+ // Surface adjacent features now that a model exists (embed it / drop it in a
+ // world). The site-wide discovery layer (public/feature-discovery.js) renders
+ // the contextual cross-link card; this just announces the moment.
+ document.dispatchEvent(new CustomEvent('tws:feature-done', { detail: { feature: 'forge' } }));
+ // Update share button label with creation context (non-blocking).
+ if (els.forgeShareBtn) {
+ els.forgeShareBtn.dataset.sharePrompt = prompt;
+ }
}
// Load (or reload) the "Your creations" strip from durable storage. Hidden
// entirely when persistence is off or the client has no creations yet.
async function loadGallery() {
if (!els.creations) return;
+
+ // Show skeleton while the real fetch is in flight.
+ els.creations.classList.remove('is-hidden');
+ els.creationsGrid.setAttribute('aria-busy', 'true');
+ els.creationsGrid.innerHTML = skeletonHTML(4, 'card');
+
let data;
try {
const res = await fetch('/api/forge-gallery?limit=24', { headers: CLIENT_HEADERS });
data = await res.json().catch(() => ({}));
} catch {
+ // On network error, show error state with a retry that reloads the gallery.
+ els.creationsGrid.removeAttribute('aria-busy');
+ els.creationsGrid.innerHTML = errorStateHTML({
+ title: "Couldn't load your creations",
+ body: 'Check your connection — your models are still saved.',
+ });
+ els.creationsGrid.querySelector('[data-sk-retry]')?.addEventListener('click', loadGallery);
return;
}
+
+ els.creationsGrid.removeAttribute('aria-busy');
const creations = Array.isArray(data?.creations) ? data.creations : [];
if (!data?.enabled || creations.length === 0) {
els.creations.classList.add('is-hidden');
@@ -206,6 +233,7 @@ async function loadGallery() {
card.className = 'creation';
card.title = c.prompt || 'Forged model';
card.setAttribute('aria-label', `Open: ${c.prompt || 'forged model'}`);
+ if (c.id) card.dataset.creationId = c.id;
if (c.preview_image_url) {
const img = document.createElement('img');
@@ -395,5 +423,60 @@ els.download.addEventListener('click', () => {
sendFeedback({ downloaded: true });
});
+// Share button — open share panel with copy-link, X, Farcaster, and remix CTA.
+if (els.forgeShareBtn) {
+ els.forgeShareBtn.addEventListener('click', () => {
+ const origin = location.origin;
+ const prompt = els.forgeShareBtn.dataset.sharePrompt || lastPrompt || '';
+ const id = currentCreationId;
+ const shareUrl = id
+ ? `${origin}/forge/share/${id}`
+ : `${origin}/forge`;
+ const remixUrl = prompt
+ ? `${origin}/forge?prompt=${encodeURIComponent(prompt)}`
+ : `${origin}/forge`;
+ showSharePanel(
+ {
+ kind: 'forge',
+ id: id || '',
+ title: prompt || 'Forged creation',
+ description: 'A 3D model generated with text → 3D on three.ws',
+ shareUrl,
+ remixUrl,
+ },
+ els.forgeShareBtn,
+ );
+ });
+}
+
+// Handle ?prompt= (pre-fill the prompt box from a remix link)
+// and ?share= (load a shared creation from the gallery).
+(function handleQueryParams() {
+ const params = new URLSearchParams(location.search);
+ const promptParam = params.get('prompt');
+ const shareParam = params.get('share');
+ if (promptParam && els.prompt) {
+ els.prompt.value = decodeURIComponent(promptParam).slice(0, 300);
+ els.prompt.focus();
+ }
+ if (shareParam) {
+ // Attempt to load the shared creation once the gallery fetch completes.
+ // We hook into the gallery load so the creation card is available.
+ const origLoadGallery = loadGallery;
+ // Override load to highlight the shared creation after gallery loads.
+ // This is a one-shot intercept via a flag.
+ window.__forgeShareId = shareParam;
+ }
+})();
+
// Surface any previously forged models for this browser on load.
-loadGallery();
+loadGallery().then(() => {
+ const shareId = window.__forgeShareId;
+ if (!shareId) return;
+ // Find the creation card in the grid and trigger it.
+ const card = els.creationsGrid?.querySelector(`[data-creation-id="${shareId}"]`);
+ if (card) {
+ card.click();
+ card.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ }
+});
diff --git a/src/friends-panel.css b/src/friends-panel.css
index 3fb4498ae..b45f0b934 100644
--- a/src/friends-panel.css
+++ b/src/friends-panel.css
@@ -120,6 +120,6 @@
font-weight: 800;
line-height: 15px;
text-align: center;
- box-shadow: 0 0 0 2px #0a0a0a;
+ box-shadow: 0 0 0 2px var(--bg-0);
pointer-events: none;
}
diff --git a/src/friends.js b/src/friends.js
index e62dc5b6d..c37b632a9 100644
--- a/src/friends.js
+++ b/src/friends.js
@@ -13,6 +13,7 @@
// The panel UI (game/friends-panel.js) is a pure view over this client.
import { apiFetch } from './api.js';
+import { log } from './shared/log.js';
// ── presence ticket ─────────────────────────────────────────────────────────
// Short-lived, account-scoped token the realm room verifies before publishing
@@ -66,7 +67,7 @@ export class FriendsClient {
try {
fn(this);
} catch (e) {
- console.error('[friends] listener threw:', e);
+ log.error('[friends] listener threw:', e);
}
}
}
@@ -140,7 +141,7 @@ export class FriendsClient {
} catch (err) {
this.loadError = 'network';
this.loaded = true;
- console.warn('[friends] refresh failed:', err?.message);
+ log.warn('[friends] refresh failed:', err?.message);
}
this._emit();
}
@@ -233,7 +234,7 @@ export class FriendsClient {
// open composer rebuilds every few seconds and steals the caret.
if (changed || !quiet) this._emit();
} catch (err) {
- if (!quiet) console.warn('[friends] thread load failed:', err?.message);
+ if (!quiet) log.warn('[friends] thread load failed:', err?.message);
}
}
diff --git a/src/glossary/page.js b/src/glossary/page.js
new file mode 100644
index 000000000..a9654d7c6
--- /dev/null
+++ b/src/glossary/page.js
@@ -0,0 +1,132 @@
+// /glossary — full plain-language glossary page.
+//
+// Renders every term from the single source of truth in public/glossary.js
+// (exposed as window.twsGlossary) so this page never forks the definitions.
+// Adds live search, deep-linkable per-term anchors (/glossary#x402), and a
+// target flash when arriving via one of those anchors.
+
+const grid = document.getElementById('glos-grid');
+const input = document.getElementById('glos-q');
+const countEl = document.getElementById('glos-count');
+const emptyEl = document.getElementById('glos-empty');
+
+function escapeHtml(s) {
+ return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
+ }[c]));
+}
+
+// glossary.js is injected sitewide by nav.js (async). Wait for it rather than
+// duplicating the term data here. Resolves null if it never arrives so the page
+// can still show a graceful message instead of a blank void.
+function waitForGlossary() {
+ if (window.twsGlossary && window.twsGlossary.terms) return Promise.resolve(window.twsGlossary);
+ // Ensure the script is present even on a page that somehow lacks nav.js.
+ if (!document.querySelector('script[src="/glossary.js"]')) {
+ const s = document.createElement('script');
+ s.src = '/glossary.js';
+ document.head.appendChild(s);
+ }
+ return new Promise((resolve) => {
+ let tries = 0;
+ const iv = setInterval(() => {
+ if (window.twsGlossary && window.twsGlossary.terms) {
+ clearInterval(iv);
+ resolve(window.twsGlossary);
+ } else if (++tries > 120) {
+ clearInterval(iv);
+ resolve(null);
+ }
+ }, 50);
+ });
+}
+
+function slugFor(g, key) {
+ if (typeof g.slug === 'function') return g.slug(key);
+ return String(key).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
+}
+
+function render(g) {
+ const terms = g.terms || {};
+ const labels = g.labels || {};
+ const keys = Object.keys(terms).sort((a, b) =>
+ (labels[a] || a).localeCompare(labels[b] || b));
+
+ grid.innerHTML = keys.map((key) => {
+ const id = 'g-' + slugFor(g, key);
+ const label = escapeHtml(labels[key] || key);
+ const def = escapeHtml(terms[key]);
+ return (
+ `<article class="glos-card" id="${id}" tabindex="-1" ` +
+ `data-term-key="${escapeHtml(key)}">` +
+ `<h2 class="glos-card-term">${label}</h2>` +
+ `<p class="glos-card-def">${def}</p>` +
+ `</article>`
+ );
+ }).join('');
+
+ countEl.textContent = `${keys.length} terms`;
+ return keys.length;
+}
+
+function applyFilter() {
+ const q = (input.value || '').trim().toLowerCase();
+ const cards = grid.querySelectorAll('.glos-card');
+ let shown = 0;
+ cards.forEach((card) => {
+ const hay = card.textContent.toLowerCase();
+ const match = !q || hay.includes(q);
+ card.hidden = !match;
+ if (match) shown += 1;
+ });
+
+ if (q && shown === 0) {
+ emptyEl.querySelector('span').textContent = input.value.trim();
+ emptyEl.hidden = false;
+ countEl.hidden = true;
+ } else {
+ emptyEl.hidden = true;
+ countEl.hidden = false;
+ countEl.textContent = q ? `${shown} of ${cards.length} terms` : `${cards.length} terms`;
+ }
+}
+
+// Scroll to and flash the card named by the URL hash (/glossary#x402).
+function highlightFromHash() {
+ const id = decodeURIComponent((location.hash || '').replace(/^#/, ''));
+ if (!id) return;
+ const target = document.getElementById(id.startsWith('g-') ? id : 'g-' + id);
+ if (!target) return;
+ // Clearing any active filter guarantees the target is visible.
+ if (input.value) { input.value = ''; applyFilter(); }
+ target.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ target.focus({ preventScroll: true });
+ grid.querySelectorAll('.glos-card.is-target').forEach((el) => el.classList.remove('is-target'));
+ // Re-trigger the CSS animation on repeat visits to the same anchor.
+ void target.offsetWidth;
+ target.classList.add('is-target');
+}
+
+async function init() {
+ const g = await waitForGlossary();
+ if (!g) {
+ grid.innerHTML = '';
+ emptyEl.textContent = 'Glossary failed to load. Refresh to try again.';
+ emptyEl.hidden = false;
+ countEl.hidden = true;
+ return;
+ }
+
+ render(g);
+
+ let raf = 0;
+ input.addEventListener('input', () => {
+ cancelAnimationFrame(raf);
+ raf = requestAnimationFrame(applyFilter);
+ });
+
+ window.addEventListener('hashchange', highlightFromHash);
+ highlightFromHash();
+}
+
+init();
diff --git a/src/guest-avatar.js b/src/guest-avatar.js
index 94e023a0f..768be78a7 100644
--- a/src/guest-avatar.js
+++ b/src/guest-avatar.js
@@ -14,6 +14,7 @@
* /login post-auth check.
*/
+import { log } from './shared/log.js';
const DB_NAME = 'three-ws-guest';
const STORE = 'avatars';
const KEY = 'pending';
@@ -121,7 +122,7 @@ export async function load() {
}),
);
} catch (err) {
- console.warn('[guest-avatar] load failed:', err);
+ log.warn('[guest-avatar] load failed:', err);
return null;
}
}
@@ -144,7 +145,7 @@ export async function clear() {
}),
);
} catch (err) {
- console.warn('[guest-avatar] clear failed:', err);
+ log.warn('[guest-avatar] clear failed:', err);
}
}
diff --git a/src/handle.js b/src/handle.js
index a5c7642fd..607a45579 100644
--- a/src/handle.js
+++ b/src/handle.js
@@ -6,6 +6,7 @@
// directly, so it stays small and the avatar runtime is identical wherever
// it shows up.
+import { log } from './shared/log.js';
const main = document.getElementById('main');
const handle = (() => {
@@ -23,7 +24,7 @@ if (!handle) {
renderClaimLanding();
} else {
render(handle).catch((err) => {
- console.error('[handle] render failed', err);
+ log.error('[handle] render failed', err);
renderNotFound(err?.message || 'Could not load this profile.');
});
}
@@ -116,7 +117,7 @@ GET ${escapeHtml(avatar.model_url)}</pre>
try {
iframe.contentWindow?.postMessage(msg, new URL(embedUrl).origin);
} catch (err) {
- console.warn('[handle] postMessage failed', err);
+ log.warn('[handle] postMessage failed', err);
}
};
@@ -175,7 +176,7 @@ GET ${escapeHtml(avatar.model_url)}</pre>
btn.classList.remove('copied');
}, 1400);
} catch (err) {
- console.warn('[handle] clipboard failed', err);
+ log.warn('[handle] clipboard failed', err);
}
});
});
diff --git a/src/header-user.js b/src/header-user.js
index 65a4acc95..173416399 100644
--- a/src/header-user.js
+++ b/src/header-user.js
@@ -25,7 +25,7 @@ function injectStyles() {
.hu-root { position: relative; display: inline-flex; }
.hu-avatar {
width: 32px; height: 32px; border-radius: 50%;
- background: linear-gradient(135deg, #ffffff 0%, #9a8cff 100%);
+ background: linear-gradient(135deg, #ffffff 0%, #888888 100%);
color: #fff; font-size: 13px; font-weight: 600; letter-spacing: 0.02em;
border: 1px solid rgba(255,255,255,0.08);
display: inline-flex; align-items: center; justify-content: center;
@@ -33,9 +33,9 @@ function injectStyles() {
transition: transform 0.12s ease, box-shadow 0.15s ease;
font-family: inherit;
}
-.hu-avatar:hover { box-shadow: 0 0 0 3px rgba(106,92,255,0.18); }
-.hu-avatar:focus-visible { outline: 2px solid #9a8cff; outline-offset: 2px; }
-.hu-avatar[aria-expanded="true"] { box-shadow: 0 0 0 3px rgba(106,92,255,0.28); }
+.hu-avatar:hover { box-shadow: 0 0 0 3px rgba(255,255,255,0.09); }
+.hu-avatar:focus-visible { outline: 2px solid rgba(255,255,255,0.28); outline-offset: 2px; }
+.hu-avatar[aria-expanded="true"] { box-shadow: 0 0 0 3px rgba(255,255,255,0.14); }
.hu-avatar svg { width: 16px; height: 16px; display: block; }
.hu-menu {
@@ -60,7 +60,7 @@ function injectStyles() {
}
.hu-identity-avatar {
width: 36px; height: 36px; border-radius: 50%;
- background: linear-gradient(135deg, #ffffff 0%, #9a8cff 100%);
+ background: linear-gradient(135deg, #ffffff 0%, #888888 100%);
color: #fff; font-size: 14px; font-weight: 600;
display: inline-flex; align-items: center; justify-content: center;
flex-shrink: 0;
@@ -91,7 +91,7 @@ function injectStyles() {
.hu-item.danger:hover { background: rgba(255,80,80,0.08); color: #ffb3b3; }
.hu-divider { height: 1px; background: #23232f; margin: 6px 4px; }
-.hu-copy-flash { color: #9a8cff !important; }
+.hu-copy-flash { color: #888888 !important; }
`;
const style = document.createElement('style');
style.setAttribute('data-header-user', '');
@@ -169,7 +169,7 @@ function buildMenu(user, identity, options) {
items.push(`<a class="hu-item" href="/settings">${SETTINGS_ICON}<span>Settings</span></a>`);
}
items.push(`<a class="hu-item" href="/dashboard/portfolio">${PORTFOLIO_ICON}<span>Portfolio</span></a>`);
- items.push(`<a class="hu-item" href="/dashboard/wallets">${WALLETS_ICON}<span>Linked wallets</span></a>`);
+ items.push(`<a class="hu-item" href="/dashboard/account#wallets">${WALLETS_ICON}<span>Linked wallets</span></a>`);
const copyTarget = identity.walletAddr || (identity.hasRealEmail ? user.email : '');
if (copyTarget) {
diff --git a/src/home-v4-hero.js b/src/home-v4-hero.js
deleted file mode 100644
index 1e1d5d807..000000000
--- a/src/home-v4-hero.js
+++ /dev/null
@@ -1,385 +0,0 @@
-import {
- WebGLRenderer,
- Scene,
- PerspectiveCamera,
- AnimationMixer,
- AnimationClip,
- Box3,
- Vector3,
- Clock,
- HemisphereLight,
- DirectionalLight,
- ACESFilmicToneMapping,
- SRGBColorSpace,
- PMREMGenerator,
- Points,
- BufferGeometry,
- Float32BufferAttribute,
- ShaderMaterial,
- AdditiveBlending,
- MathUtils,
-} from 'three';
-import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
-import { MeshSurfaceSampler } from 'three/addons/math/MeshSurfaceSampler.js';
-import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
-
-const PARTICLE_COUNT = 6000;
-const MATERIALIZE_DURATION = 2.0;
-const CROSSFADE_START = 0.5;
-const MODEL_URL = '/avatars/cz.glb';
-
-const VERT = `
-attribute vec3 aStart;
-attribute vec3 aTarget;
-attribute float aSeed;
-uniform float uProgress;
-uniform float uTime;
-uniform float uParticleAlpha;
-varying float vAlpha;
-void main() {
- float p = clamp(uProgress + aSeed * 0.3 - 0.15, 0.0, 1.0);
- float ease = p * p * (3.0 - 2.0 * p);
- vec3 pos = mix(aStart, aTarget, ease);
- float drift = sin(uTime * 2.0 + aSeed * 6.28) * (1.0 - ease) * 0.05;
- pos.x += drift;
- pos.y += drift * 0.5;
- vec4 mvPos = modelViewMatrix * vec4(pos, 1.0);
- gl_PointSize = max(1.5, 4.0 * (300.0 / -mvPos.z));
- gl_Position = projectionMatrix * mvPos;
- vAlpha = uParticleAlpha * (0.4 + 0.6 * aSeed);
-}
-`;
-
-const FRAG = `
-varying float vAlpha;
-void main() {
- float d = length(gl_PointCoord - 0.5) * 2.0;
- if (d > 1.0) discard;
- float alpha = (1.0 - d * d) * vAlpha;
- gl_FragColor = vec4(1.0, 0.84, 0.4, alpha);
-}
-`;
-
-export class HeroScene {
- constructor(canvas) {
- this.canvas = canvas;
- this._raf = 0;
- this._disposed = false;
- this._visible = true;
-
- const LOW_MEMORY = typeof navigator.deviceMemory === 'number' && navigator.deviceMemory < 2;
- const REDUCED_MOTION = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
- this._skipParticles = LOW_MEMORY || REDUCED_MOTION || window.innerWidth < 768;
-
- this.renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true });
- this.renderer.toneMapping = ACESFilmicToneMapping;
- this.renderer.toneMappingExposure = 1.0;
- this.renderer.outputColorSpace = SRGBColorSpace;
- this.renderer.setClearColor(0x000000, 0);
-
- this.scene = new Scene();
- this.camera = new PerspectiveCamera(16, 1, 0.1, 100);
- this.camera.position.set(0.3, 1.0, 18);
-
- const pmrem = new PMREMGenerator(this.renderer);
- this.scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
- pmrem.dispose();
-
- this.scene.add(new HemisphereLight(0xffffff, 0x444466, 0.6));
- const sun = new DirectionalLight(0xffffff, 1.2);
- sun.position.set(4, 8, 6);
- this.scene.add(sun);
-
- this._clock = new Clock();
- this._loader = new GLTFLoader();
-
- this.model = null;
- this.mixer = null;
- this.particles = null;
- this._particleMat = null;
- this._progress = 0;
- this._materialized = false;
- this._modelOpacityTargets = [];
-
- this._mouseX = 0;
- this._mouseY = 0;
- this._targetTheta = 0;
- this._targetPhi = 0;
- this._currentTheta = 0;
- this._currentPhi = 0;
-
- this._baseCamPos = new Vector3();
- this._focusY = 1.0;
-
- this._resize();
- this._ro = new ResizeObserver(() => this._resize());
- this._ro.observe(canvas);
-
- this._visibilityObserver = new IntersectionObserver(
- (entries) => {
- this._visible = entries.at(-1).isIntersecting;
- if (this._visible && !this._raf) {
- this._clock.start();
- this._raf = requestAnimationFrame(this._tick);
- }
- },
- { rootMargin: '100px' },
- );
- this._visibilityObserver.observe(canvas);
-
- this._onMouseMove = this._onMouseMove.bind(this);
- window.addEventListener('mousemove', this._onMouseMove, { passive: true });
-
- this._tick = this._tick.bind(this);
- this._load();
- }
-
- _resize() {
- const dpr = Math.min(devicePixelRatio || 1, window.innerWidth < 768 ? 1 : 2);
- const w = this.canvas.clientWidth;
- const h = this.canvas.clientHeight;
- if (!w || !h) return;
- this.renderer.setPixelRatio(dpr);
- this.renderer.setSize(w, h, false);
- this.camera.aspect = w / h;
- this.camera.updateProjectionMatrix();
- }
-
- _onMouseMove(e) {
- this._mouseX = (e.clientX / window.innerWidth) * 2 - 1;
- this._mouseY = (e.clientY / window.innerHeight) * 2 - 1;
- }
-
- async _load() {
- let gltf;
- try {
- gltf = await this._loader.loadAsync(MODEL_URL);
- } catch {
- return;
- }
- if (this._disposed) return;
-
- this.model = gltf.scene;
- this.scene.add(this.model);
-
- const box = new Box3().setFromObject(this.model);
- const size = box.getSize(new Vector3());
- const center = box.getCenter(new Vector3());
- this.model.position.x -= center.x;
- this.model.position.z -= center.z;
- this.model.position.y -= box.min.y;
-
- this.model.updateMatrixWorld(true);
-
- const targetHeight = size.y;
- const dist = (targetHeight / 2) / Math.tan((this.camera.fov / 2) * (Math.PI / 180));
- this._focusY = targetHeight * 0.5;
- this.camera.position.set(0.3, this._focusY, dist * 1.1);
- this._baseCamPos.copy(this.camera.position);
- this.camera.lookAt(0, this._focusY, 0);
-
- this.mixer = new AnimationMixer(this.model);
- const knownNodes = new Set();
- this.model.traverse((n) => { if (n.name) knownNodes.add(n.name); });
-
- for (const clip of gltf.animations || []) {
- const tracks = clip.tracks.filter((t) => knownNodes.has(t.name.split('.')[0]));
- if (tracks.length === 0) continue;
- const filtered = new AnimationClip(clip.name, clip.duration, tracks);
- const action = this.mixer.clipAction(filtered);
- action.play();
- break;
- }
-
- if (!gltf.animations?.length) {
- this._loadIdleAnim(knownNodes);
- }
-
- if (this._skipParticles) {
- this._materialized = true;
- this._progress = 1;
- this._startLoop();
- return;
- }
-
- this._collectOpacityTargets();
- this._setModelOpacity(0);
- this._buildParticles();
- this._startLoop();
- }
-
- async _loadIdleAnim(knownNodes) {
- try {
- const manifest = await fetch('/animations/manifest.json').then(r => r.json());
- const arr = Array.isArray(manifest) ? manifest : manifest.animations || [];
- const idle = arr.find(d => d.name === 'idle' || d.name === 'av-idle-breath');
- if (!idle) return;
- const json = await fetch(idle.url).then(r => r.json());
- const clip = AnimationClip.parse(json);
- const tracks = clip.tracks.filter(t => knownNodes.has(t.name.split('.')[0]));
- if (tracks.length === 0) return;
- const filtered = new AnimationClip(clip.name, clip.duration, tracks);
- const action = this.mixer.clipAction(filtered);
- action.play();
- } catch { /* manifest/clip fetch is non-critical enhancement */ }
- }
-
- _collectOpacityTargets() {
- this._modelOpacityTargets = [];
- this.model.traverse((child) => {
- if (child.isMesh && child.material) {
- const mats = Array.isArray(child.material) ? child.material : [child.material];
- for (const mat of mats) {
- mat.transparent = true;
- this._modelOpacityTargets.push(mat);
- }
- }
- });
- }
-
- _setModelOpacity(v) {
- for (const mat of this._modelOpacityTargets) {
- mat.opacity = v;
- }
- }
-
- _buildParticles() {
- const meshes = [];
- this.model.traverse((child) => {
- if (child.isMesh && child.geometry) meshes.push(child);
- });
- if (meshes.length === 0) return;
-
- const starts = new Float32Array(PARTICLE_COUNT * 3);
- const targets = new Float32Array(PARTICLE_COUNT * 3);
- const seeds = new Float32Array(PARTICLE_COUNT);
- const pos = new Vector3();
-
- let idx = 0;
- const perMesh = Math.ceil(PARTICLE_COUNT / meshes.length);
-
- for (const mesh of meshes) {
- const sampler = new MeshSurfaceSampler(mesh).setWeightAttribute(null).build();
- const count = Math.min(perMesh, PARTICLE_COUNT - idx);
- for (let i = 0; i < count; i++) {
- sampler.sample(pos);
- pos.applyMatrix4(mesh.matrixWorld);
-
- targets[idx * 3] = pos.x;
- targets[idx * 3 + 1] = pos.y;
- targets[idx * 3 + 2] = pos.z;
-
- const theta = Math.random() * Math.PI * 2;
- const phi = Math.acos(2 * Math.random() - 1);
- const r = 2 + Math.random() * 4;
- starts[idx * 3] = pos.x + r * Math.sin(phi) * Math.cos(theta);
- starts[idx * 3 + 1] = pos.y + r * Math.sin(phi) * Math.sin(theta);
- starts[idx * 3 + 2] = pos.z + r * Math.cos(phi);
-
- seeds[idx] = Math.random();
- idx++;
- }
- }
-
- const geo = new BufferGeometry();
- geo.setAttribute('aStart', new Float32BufferAttribute(starts, 3));
- geo.setAttribute('aTarget', new Float32BufferAttribute(targets, 3));
- geo.setAttribute('aSeed', new Float32BufferAttribute(seeds, 1));
- geo.setAttribute('position', new Float32BufferAttribute(targets, 3));
-
- this._particleMat = new ShaderMaterial({
- vertexShader: VERT,
- fragmentShader: FRAG,
- uniforms: {
- uProgress: { value: 0 },
- uTime: { value: 0 },
- uParticleAlpha: { value: 1 },
- },
- transparent: true,
- depthWrite: false,
- blending: AdditiveBlending,
- });
-
- this.particles = new Points(geo, this._particleMat);
- this.scene.add(this.particles);
- }
-
- _startLoop() {
- this._clock.start();
- this._raf = requestAnimationFrame(this._tick);
- }
-
- _tick() {
- if (this._disposed) return;
-
- if (!this._visible && this._materialized) {
- this._raf = 0;
- return;
- }
-
- const dt = this._clock.getDelta();
- const elapsed = this._clock.getElapsedTime();
-
- if (this.mixer) this.mixer.update(dt);
-
- if (!this._materialized && this.particles) {
- this._progress = Math.min(this._progress + dt / MATERIALIZE_DURATION, 1);
- this._particleMat.uniforms.uProgress.value = this._progress;
- this._particleMat.uniforms.uTime.value = elapsed;
-
- if (this._progress >= CROSSFADE_START) {
- const fade = (this._progress - CROSSFADE_START) / (1 - CROSSFADE_START);
- this._setModelOpacity(fade);
- this._particleMat.uniforms.uParticleAlpha.value = 1 - fade;
- }
-
- if (this._progress >= 1) {
- this._materialized = true;
- this._setModelOpacity(1);
- this.scene.remove(this.particles);
- this.particles.geometry.dispose();
- this._particleMat.dispose();
- this.particles = null;
- this._particleMat = null;
- for (const mat of this._modelOpacityTargets) {
- mat.transparent = false;
- }
- }
- }
-
- if (this._materialized) {
- this._targetTheta = this._mouseX * 12;
- this._targetPhi = this._mouseY * 6;
- this._currentTheta = MathUtils.lerp(this._currentTheta, this._targetTheta, 0.03);
- this._currentPhi = MathUtils.lerp(this._currentPhi, this._targetPhi, 0.03);
-
- const thetaRad = this._currentTheta * (Math.PI / 180);
- const dist = this._baseCamPos.z;
- this.camera.position.x = this._baseCamPos.x + Math.sin(thetaRad) * dist * 0.05;
- this.camera.position.y = this._baseCamPos.y - this._currentPhi * 0.01;
- this.camera.lookAt(0, this._focusY, 0);
- }
-
- this.renderer.render(this.scene, this.camera);
- this._raf = requestAnimationFrame(this._tick);
- }
-
- dispose() {
- this._disposed = true;
- cancelAnimationFrame(this._raf);
- this._ro.disconnect();
- this._visibilityObserver.disconnect();
- window.removeEventListener('mousemove', this._onMouseMove);
- if (this.particles) {
- this.particles.geometry.dispose();
- this._particleMat?.dispose();
- }
- this.renderer.dispose();
- }
-}
-
-const canvas = document.getElementById('v4-hero-canvas');
-if (canvas) {
- const heroScene = new HeroScene(canvas);
- window._v4Hero = heroScene;
-}
diff --git a/src/home-v4-scroll.js b/src/home-v4-scroll.js
deleted file mode 100644
index 811efd9eb..000000000
--- a/src/home-v4-scroll.js
+++ /dev/null
@@ -1,174 +0,0 @@
-/**
- * home-v4 scroll orchestration.
- */
-
-const LOW_MEMORY = typeof navigator.deviceMemory === 'number' && navigator.deviceMemory < 2;
-
-/* ── Scroll reveal ───────────────────────────────────── */
-(function initReveals() {
- const els = document.querySelectorAll('.v4-reveal');
- const observer = new IntersectionObserver(
- (entries) => {
- for (const entry of entries) {
- if (entry.isIntersecting) {
- entry.target.classList.add('revealed');
- observer.unobserve(entry.target);
- }
- }
- },
- { root: null, threshold: 0.1, rootMargin: '0px 0px -40px 0px' },
- );
- for (const el of els) {
- const siblings = Array.from(el.parentElement.querySelectorAll('.v4-reveal'));
- const idx = siblings.indexOf(el);
- el.style.transitionDelay = idx * 0.08 + 's';
- observer.observe(el);
- }
-})();
-
-/* ── Stats ───────────────────────────────────────────── */
-(async function loadStats() {
- try {
- const r = await fetch('/api/home-stats');
- if (!r.ok) return;
- const data = await r.json();
- if (!data || data.available === false) return;
- const agentEl = document.querySelector('[data-stat="agents"]');
- const onchainEl = document.querySelector('[data-stat="onchain"]');
- if (agentEl && data.agents != null) agentEl.textContent = formatNum(data.agents);
- const onchainVal = data.onchain_agents ?? data.onchain;
- if (onchainEl && onchainVal != null) onchainEl.textContent = formatNum(onchainVal);
- } catch { /* stats are non-critical enhancement */ }
-})();
-
-function formatNum(n) {
- if (n >= 1000) return (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k';
- return String(n);
-}
-
-/* ── Off-screen pause helper for Act2Viewer instances ── */
-function observeViewerVisibility(canvas, viewer) {
- let visible = true;
- let paused = false;
- const original = viewer._tick.bind(viewer);
-
- const observer = new IntersectionObserver(
- (entries) => {
- visible = entries.at(-1).isIntersecting;
- if (visible && paused) {
- paused = false;
- viewer._clock.start();
- requestAnimationFrame(original);
- }
- },
- { rootMargin: '200px' },
- );
- observer.observe(canvas);
-
- const originalTick = viewer._tick;
- viewer._tick = function () {
- if (!visible) {
- paused = true;
- return;
- }
- originalTick.call(viewer);
- };
-}
-
-/* ── Experience section: Act2Viewer + animation chips ── */
-(function initExperience() {
- const canvas = document.getElementById('v4-exp-canvas');
- if (!canvas || LOW_MEMORY) return;
-
- let viewer = null;
- let currentModelUrl = '/avatars/cz.glb';
- let activeChip = null;
-
- const observer = new IntersectionObserver(
- (entries) => {
- if (entries.at(-1).isIntersecting && !viewer) {
- observer.disconnect();
- boot();
- }
- },
- { rootMargin: '600px' },
- );
- observer.observe(canvas);
-
- function boot() {
- if (!window.Act2Viewer) return;
- viewer = new window.Act2Viewer(canvas, { fov: 14 });
- observeViewerVisibility(canvas, viewer);
- window.addEventListener('pagehide', () => viewer?.dispose(), { once: true });
-
- viewer.onClipsReady = (clips) => {
- buildChips(clips);
- };
-
- viewer.loadModel(currentModelUrl);
-
- const modelBtns = document.querySelectorAll('.v4-model-btn');
- for (const btn of modelBtns) {
- btn.addEventListener('click', () => {
- const url = btn.dataset.model;
- if (url === currentModelUrl) return;
- currentModelUrl = url;
- for (const b of modelBtns) b.classList.remove('active');
- btn.classList.add('active');
- viewer.loadModel(url);
- });
- }
- }
-
- function buildChips(clips) {
- const container = document.getElementById('v4-anim-chips');
- if (!container) return;
- container.innerHTML = '';
- activeChip = null;
-
- for (const def of clips) {
- const btn = document.createElement('button');
- btn.className = 'v4-chip';
- btn.textContent = def.label || def.name;
- btn.addEventListener('click', () => {
- if (activeChip) activeChip.classList.remove('active');
- btn.classList.add('active');
- activeChip = btn;
- viewer.playClip(def.name);
- });
- container.appendChild(btn);
- }
- }
-})();
-
-/* ── CTA section wave avatar ─────────────────────────── */
-(function initCloseViewer() {
- const canvas = document.getElementById('v4-close-canvas');
- if (!canvas || LOW_MEMORY) return;
-
- const observer = new IntersectionObserver(
- (entries) => {
- if (entries.at(-1).isIntersecting) {
- observer.disconnect();
- boot();
- }
- },
- { rootMargin: '400px' },
- );
- observer.observe(canvas);
-
- async function boot() {
- if (!window.Act2Viewer) return;
- const viewer = new window.Act2Viewer(canvas, { fov: 14 });
- observeViewerVisibility(canvas, viewer);
- window.addEventListener('pagehide', () => viewer?.dispose(), { once: true });
- await viewer.loadModel('/avatars/cz.glb', { autoPlay: false });
- const waveClip = viewer.listAvailableClips().find(c => /wave|waving/i.test(c.name));
- if (waveClip) {
- viewer.playClip(waveClip.name);
- } else {
- const clips = viewer.listAvailableClips();
- if (clips.length) viewer.playClip(clips[0].name);
- }
- }
-})();
diff --git a/src/ibm-galaxy.js b/src/ibm-galaxy.js
index 7aa3a639f..d6552fe30 100644
--- a/src/ibm-galaxy.js
+++ b/src/ibm-galaxy.js
@@ -11,6 +11,7 @@
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
+import { log } from './shared/log.js';
const RADIUS = 100; // matches the server's projection half-width
@@ -632,7 +633,7 @@ async function runSearch(query) {
const data = await res.json();
applySearchResults(query, data);
} catch (err) {
- console.error('[galaxy] search failed', err);
+ log.error('[galaxy] search failed', err);
els.results.innerHTML = `<div class="r-head"><span>Search unavailable right now.</span></div>`;
els.results.classList.add('show');
} finally {
@@ -740,7 +741,7 @@ async function load() {
if (!res.ok) throw new Error(`galaxy ${res.status}`);
data = await res.json();
} catch (err) {
- console.error('[galaxy] load failed', err);
+ log.error('[galaxy] load failed', err);
els.errorMsg.textContent = 'Something went wrong reaching the galaxy service. Check your connection and try again.';
showOnly(els.error);
return;
diff --git a/src/ibm-identity.js b/src/ibm-identity.js
new file mode 100644
index 000000000..8837f22c5
--- /dev/null
+++ b/src/ibm-identity.js
@@ -0,0 +1,250 @@
+// Identity Firewall — client module for /ibm/identity.
+//
+// Calls POST /api/agents/identity-check with the candidate name + description,
+// then renders a verdict showing:
+// · overall status (clear / review / block / unavailable)
+// · identity-uniqueness gauge (from Granite embedding cosine distance)
+// · nearest existing agents by cosine similarity
+// · Granite Guardian content-screen chips (harm / social_bias / sexual_content)
+// · a designed "watsonx not configured" state when the API returns configured:false
+//
+// No mock data, no fake verdicts. The page HTML defines all DOM elements this
+// module references by ID.
+
+const $ = (id) => document.getElementById(id);
+
+const nameEl = $('name');
+const descEl = $('desc');
+const runBtn = $('run');
+const runLabel = $('run-label');
+const emptyEl = $('empty');
+const verdictEl = $('verdict');
+const countEl = $('count');
+
+function esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]),
+ );
+}
+
+// ── Character counter ───────────────────────────────────────────────────────
+descEl.addEventListener('input', () => {
+ countEl.textContent = descEl.value.length;
+});
+
+// ── Example chips ───────────────────────────────────────────────────────────
+document.getElementById('examples').addEventListener('click', (e) => {
+ const chip = e.target.closest('.chip');
+ if (!chip) return;
+ nameEl.value = chip.dataset.name || '';
+ descEl.value = chip.dataset.desc || '';
+ countEl.textContent = descEl.value.length;
+ run();
+});
+
+// ── Run check ───────────────────────────────────────────────────────────────
+let busy = false;
+
+async function run() {
+ const name = nameEl.value.trim();
+ const description = descEl.value.trim();
+ if (!name && !description) { nameEl.focus(); return; }
+ if (busy) return;
+
+ busy = true;
+ runBtn.disabled = true;
+ runLabel.textContent = 'Checking with Granite…';
+ const spinner = document.createElement('span');
+ spinner.className = 'spinner';
+ runBtn.insertBefore(spinner, runBtn.firstChild);
+
+ // Show skeleton in the verdict panel while waiting
+ showSkeleton();
+
+ try {
+ const res = await fetch('/api/agents/identity-check', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ name, description }),
+ });
+ const data = await res.json();
+ if (!res.ok) {
+ renderError(data?.error_description || data?.error || 'Check failed. Please try again.');
+ } else {
+ render(data);
+ }
+ } catch {
+ renderError('Network error. Please try again.');
+ } finally {
+ busy = false;
+ runBtn.disabled = false;
+ spinner.remove();
+ runLabel.textContent = 'Run identity check';
+ }
+}
+
+runBtn.addEventListener('click', run);
+nameEl.addEventListener('keydown', (e) => { if (e.key === 'Enter') run(); });
+
+// ── Skeleton state ──────────────────────────────────────────────────────────
+function showSkeleton() {
+ emptyEl.style.display = 'none';
+ verdictEl.classList.add('show');
+ verdictEl.dataset.state = 'loading';
+ verdictEl.innerHTML = `
+ <div class="verdict-skeleton">
+ <div class="sk-row">
+ <div class="sk-icon"></div>
+ <div class="sk-lines"><div class="sk-line sk-line--lg"></div><div class="sk-line sk-line--sm"></div></div>
+ </div>
+ <div class="sk-bar"></div>
+ <div class="sk-line sk-line--md"></div>
+ <div class="sk-line sk-line--sm"></div>
+ <div class="sk-line sk-line--md"></div>
+ </div>`;
+
+ // Inject skeleton styles once
+ if (!document.getElementById('sk-styles')) {
+ const s = document.createElement('style');
+ s.id = 'sk-styles';
+ s.textContent = `
+.verdict-skeleton { display:flex; flex-direction:column; gap:12px; }
+.sk-row { display:flex; align-items:center; gap:14px; }
+.sk-icon { width:46px; height:46px; border-radius:13px; flex:none; background:var(--panel,rgba(255,255,255,0.06)); animation:sk-pulse 1.4s ease-in-out infinite; }
+.sk-lines { flex:1; display:flex; flex-direction:column; gap:8px; }
+.sk-line { height:12px; border-radius:6px; background:var(--panel,rgba(255,255,255,0.06)); animation:sk-pulse 1.4s ease-in-out infinite; }
+.sk-line--lg { width:70%; }
+.sk-line--md { width:55%; }
+.sk-line--sm { width:40%; }
+.sk-bar { height:8px; border-radius:99px; background:var(--panel,rgba(255,255,255,0.06)); animation:sk-pulse 1.4s ease-in-out infinite; }
+@keyframes sk-pulse { 0%,100%{opacity:.5} 50%{opacity:1} }
+ `.trim();
+ document.head.appendChild(s);
+ }
+}
+
+// ── Restore verdict DOM from skeleton back to original structure ─────────────
+function restoreVerdictDOM() {
+ verdictEl.innerHTML = `
+ <div class="status-row">
+ <div class="status-icon" id="status-icon">·</div>
+ <div class="status-text">
+ <div class="label" id="status-label">—</div>
+ <div class="meta" id="status-meta"></div>
+ </div>
+ </div>
+ <div id="uniq-block">
+ <div class="gauge"><span id="uniq-bar" style="width:0%"></span></div>
+ <div class="gauge-cap"><span>Identity uniqueness</span><span id="uniq-pct">—</span></div>
+ </div>
+ <ul class="reasons" id="reasons"></ul>
+ <div id="neighbors-block" style="display:none">
+ <div class="section-title">Nearest existing agents · Granite cosine</div>
+ <div id="neighbors"></div>
+ </div>
+ <div id="guardian-block" style="display:none">
+ <div class="section-title">Granite Guardian content screen</div>
+ <div class="guardian-chips" id="guardian-chips"></div>
+ </div>`;
+}
+
+// ── Error state ─────────────────────────────────────────────────────────────
+function renderError(msg) {
+ restoreVerdictDOM();
+ verdictEl.classList.add('show');
+ verdictEl.dataset.state = 'unavailable';
+ $('status-icon').textContent = '!';
+ $('status-label').textContent = 'Could not check';
+ $('status-meta').textContent = msg;
+ $('uniq-block').style.display = 'none';
+ $('reasons').innerHTML = '';
+ $('neighbors-block').style.display = 'none';
+ $('guardian-block').style.display = 'none';
+}
+
+// ── Verdict rendering ───────────────────────────────────────────────────────
+const ICON = { clear: '✓', review: '⚠', block: '✗', unavailable: '·' };
+const LABEL = {
+ clear: 'Distinct identity',
+ review: 'Similar identity exists',
+ block: 'Identity conflict',
+ unavailable: 'Check unavailable',
+};
+
+function render(data) {
+ restoreVerdictDOM();
+ verdictEl.classList.add('show');
+
+ const state = data.status || 'unavailable';
+ verdictEl.dataset.state = state;
+ $('status-icon').textContent = ICON[state] || '·';
+ $('status-label').textContent = LABEL[state] || 'Unknown';
+
+ // Unconfigured: show a clear designed state, no fake data
+ if (!data.configured || state === 'unavailable') {
+ $('status-meta').textContent =
+ 'IBM watsonx.ai is not configured on this deployment. ' +
+ 'Set WATSONX_API_KEY + WATSONX_PROJECT_ID to enable Granite identity checks.';
+ $('uniq-block').style.display = 'none';
+ $('reasons').innerHTML = '';
+ $('neighbors-block').style.display = 'none';
+ $('guardian-block').style.display = 'none';
+ return;
+ }
+
+ // Uniqueness gauge
+ const pct = data.uniqueness != null ? Math.round(data.uniqueness * 100) : null;
+ $('status-meta').textContent = pct != null ? `${pct}% distinct from existing agents` : '';
+ if (pct != null) {
+ $('uniq-block').style.display = 'block';
+ $('uniq-bar').style.width = pct + '%';
+ $('uniq-pct').textContent = pct + '%';
+ } else {
+ $('uniq-block').style.display = 'none';
+ }
+
+ // Reasons list
+ $('reasons').innerHTML = (data.reasons || [])
+ .map((r) => `<li>${esc(r)}</li>`)
+ .join('');
+
+ // Nearest agents
+ const sims = (data.similar || []).filter((s) => s.score > 0);
+ if (sims.length) {
+ $('neighbors-block').style.display = 'block';
+ $('neighbors').innerHTML = sims.slice(0, 5).map((s) => {
+ const score = Math.round(s.score * 100);
+ const tag = s.owned
+ ? '<span class="ntag">yours</span>'
+ : s.public ? '' : '<span class="ntag">private</span>';
+ return `<a class="neighbor" href="/agent/${esc(s.id)}" target="_blank" rel="noopener">
+ <span class="nname">${esc(s.name || 'Agent')}</span>
+ <span class="nbar"><span style="width:${score}%"></span></span>
+ <span class="nscore">${score}%</span>${tag}
+ </a>`;
+ }).join('');
+ } else {
+ $('neighbors-block').style.display = 'none';
+ }
+
+ // Guardian content screen
+ const g = data.guardian;
+ if (g) {
+ $('guardian-block').style.display = 'block';
+ const flagged = new Set(g.flagged || []);
+ const reasons = g.reasons || [];
+ const labelFor = (risk) => {
+ const m = reasons.find((x) => x.risk === risk);
+ return m ? m.label : risk;
+ };
+ const risks = ['harm', 'social_bias', 'sexual_content'];
+ $('guardian-chips').innerHTML = risks.map((risk) => {
+ const isFlag = flagged.has(risk);
+ const label = (labelFor(risk) || risk).replace(/_/g, ' ');
+ return `<span class="gchip ${isFlag ? 'flag' : ''}"><span class="gd"></span>${esc(label)}: ${isFlag ? 'flagged' : 'clear'}</span>`;
+ }).join('');
+ } else {
+ $('guardian-block').style.display = 'none';
+ }
+}
diff --git a/src/ibm-proof.js b/src/ibm-proof.js
index a7eb2c3b8..6f2796228 100644
--- a/src/ibm-proof.js
+++ b/src/ibm-proof.js
@@ -220,7 +220,7 @@ function setupChartHover() {
cross.style.display = 'block'; cross.style.left = best.px + 'px'; cross.style.height = rect.height + 'px';
tip.style.display = 'block'; tip.style.left = best.px + 'px'; tip.style.top = best.py + 'px';
const when = new Date(best.t * 1000).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit' });
- const tag = best.kind === 'forecast' ? '<span style="color:var(--ibm-light)">· forecast</span>' : `<span style="color:var(--faint)">· ${when}</span>`;
+ const tag = best.kind === 'forecast' ? '<span style="color:var(--brand-blue-light)">· forecast</span>' : `<span style="color:var(--faint)">· ${when}</span>`;
tip.innerHTML = `${fmtPrice(best.c)} ${tag}`;
});
}
@@ -235,7 +235,7 @@ function clearPanels() {
const govEl = $('gov');
govEl.classList.remove('passed', 'flagged');
const svgStroke = $('gov-shield')?.querySelector('svg');
- if (svgStroke) svgStroke.setAttribute('stroke', 'var(--ibm-light)');
+ if (svgStroke) svgStroke.setAttribute('stroke', 'var(--brand-blue-light)');
$('gov-title').textContent = 'Running Granite…';
$('gov-sub').textContent = 'Forecasting and screening the narration.';
$('gov-model').textContent = '';
@@ -294,7 +294,7 @@ function renderProof(data) {
].filter(([, v]) => v).map(([k, v]) => `<span class="m"><b>${k}</b> ${v}</span>`).join('');
const at = data.attester?.address;
$('p-attester').innerHTML = at
- ? `<a href="${data.attester.explorer}" target="_blank" rel="noopener" style="color:var(--ibm-light);text-decoration:none">${at}</a>`
+ ? `<a href="${data.attester.explorer}" target="_blank" rel="noopener" style="color:var(--brand-blue-light);text-decoration:none">${at}</a>`
: '<span style="color:var(--faint)">not configured — set AVATAR_WALLET_SECRET to enable notarization</span>';
}
diff --git a/src/ibm-suite-nav.js b/src/ibm-suite-nav.js
new file mode 100644
index 000000000..367384915
--- /dev/null
+++ b/src/ibm-suite-nav.js
@@ -0,0 +1,217 @@
+// Injects a consistent IBM Granite suite-switcher into every /ibm/* page.
+// Each demo page imports this module; it adds a "IBM suite" pill with a
+// dropdown listing all seven demos — current demo highlighted, siblings linked.
+// Self-contained: creates its own <style> and appends to the page's .topbar.
+
+const SUITE = [
+ { id: 'galaxy', label: 'Agent Galaxy', path: '/ibm/galaxy', tag: 'embeddings' },
+ { id: 'oracle', label: 'Granite Oracle', path: '/ibm/oracle', tag: 'TimeSeries' },
+ { id: 'twin', label: 'Digital Twin', path: '/ibm/twin', tag: 'back-test + what-if' },
+ { id: 'trust-layer', label: 'Trust Layer', path: '/ibm/trust-layer', tag: 'Guardian' },
+ { id: 'identity', label: 'Identity Firewall', path: '/ibm/identity', tag: 'embeddings + Guardian' },
+ { id: 'proof', label: 'Granite Proof', path: '/ibm/proof', tag: 'on-chain attestation' },
+ { id: 'vision', label: 'Granite Vision', path: '/ibm/vision', tag: 'multimodal' },
+];
+
+const curPath = window.location.pathname.replace(/\/$/, '');
+
+function init() {
+ const topbar = document.querySelector('.topbar');
+ if (!topbar) return;
+
+ injectStyles();
+
+ const wrap = document.createElement('div');
+ wrap.className = 'sn-wrap';
+ wrap.setAttribute('role', 'navigation');
+ wrap.setAttribute('aria-label', 'IBM Granite demo suite');
+
+ const btn = document.createElement('button');
+ btn.className = 'sn-btn';
+ btn.type = 'button';
+ btn.setAttribute('aria-haspopup', 'true');
+ btn.setAttribute('aria-expanded', 'false');
+ btn.innerHTML =
+ '<span class="sn-dot"></span>IBM suite' +
+ '<svg class="sn-chevron" width="10" height="10" viewBox="0 0 10 10" fill="none" aria-hidden="true">' +
+ '<path d="M2 3.5L5 6.5L8 3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>' +
+ '</svg>';
+
+ const dropdown = document.createElement('div');
+ dropdown.className = 'sn-drop';
+ dropdown.setAttribute('role', 'menu');
+ dropdown.id = 'ibm-suite-menu';
+ btn.setAttribute('aria-controls', 'ibm-suite-menu');
+
+ for (const demo of SUITE) {
+ const isCurrent = demo.path === curPath;
+ const item = document.createElement('a');
+ item.className = 'sn-item' + (isCurrent ? ' sn-item--current' : '');
+ item.href = isCurrent ? '#' : demo.path;
+ item.setAttribute('role', 'menuitem');
+ if (isCurrent) {
+ item.setAttribute('aria-current', 'page');
+ item.addEventListener('click', (e) => e.preventDefault());
+ }
+ item.innerHTML =
+ `<span class="sn-name">${demo.label}</span>` +
+ `<span class="sn-tag">${demo.tag}</span>`;
+ dropdown.appendChild(item);
+ }
+
+ wrap.appendChild(btn);
+ wrap.appendChild(dropdown);
+ topbar.appendChild(wrap);
+
+ let open = false;
+
+ function setOpen(force) {
+ open = typeof force === 'boolean' ? force : !open;
+ btn.setAttribute('aria-expanded', String(open));
+ dropdown.classList.toggle('sn-drop--open', open);
+ btn.classList.toggle('sn-btn--open', open);
+ }
+
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ setOpen();
+ });
+
+ document.addEventListener('click', (e) => {
+ if (!wrap.contains(e.target)) setOpen(false);
+ });
+
+ document.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape') {
+ setOpen(false);
+ btn.focus();
+ }
+ });
+}
+
+function injectStyles() {
+ const style = document.createElement('style');
+ style.textContent = `
+.sn-wrap {
+ position: relative;
+ display: inline-flex;
+ align-items: center;
+ pointer-events: auto;
+ flex-shrink: 0;
+ z-index: 50;
+}
+.sn-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ background: var(--panel, rgba(255,255,255,0.06));
+ border: 1px solid var(--border, rgba(255,255,255,0.1));
+ border-radius: 99px;
+ padding: 6px 12px;
+ font: 12px/1 -apple-system, system-ui, "Segoe UI", Roboto, sans-serif;
+ color: var(--muted, #9fb0c8);
+ cursor: pointer;
+ transition: border-color .15s, color .15s, background .15s;
+ white-space: nowrap;
+ backdrop-filter: blur(12px);
+ -webkit-backdrop-filter: blur(12px);
+}
+.sn-btn:hover,
+.sn-btn--open {
+ border-color: rgba(120,169,255,0.5);
+ color: var(--text, #e8edf5);
+}
+.sn-btn:focus-visible {
+ outline: 2px solid rgba(120,169,255,0.7);
+ outline-offset: 2px;
+}
+.sn-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--brand-blue, #0f62fe);
+ box-shadow: 0 0 8px var(--brand-blue, #0f62fe);
+ flex: none;
+}
+.sn-chevron {
+ flex: none;
+ opacity: 0.6;
+ transition: transform .2s;
+}
+.sn-btn--open .sn-chevron {
+ transform: rotate(180deg);
+}
+.sn-drop {
+ display: none;
+ position: absolute;
+ top: calc(100% + 8px);
+ right: 0;
+ min-width: 240px;
+ background: var(--panel2, rgba(10,14,22,0.97));
+ border: 1px solid var(--border, rgba(255,255,255,0.1));
+ border-radius: 14px;
+ overflow: hidden;
+ box-shadow: 0 24px 60px rgba(0,0,0,0.65);
+ backdrop-filter: blur(24px);
+ -webkit-backdrop-filter: blur(24px);
+ z-index: 200;
+}
+.sn-drop--open {
+ display: block;
+ animation: sn-in .15s ease;
+}
+@keyframes sn-in {
+ from { opacity: 0; transform: translateY(-4px) scale(0.98); }
+ to { opacity: 1; transform: none; }
+}
+.sn-item {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 11px 16px;
+ text-decoration: none;
+ color: var(--text, #e8edf5);
+ border-bottom: 1px solid var(--border, rgba(255,255,255,0.07));
+ transition: background .1s;
+}
+.sn-item:last-child {
+ border-bottom: none;
+}
+.sn-item:hover:not(.sn-item--current) {
+ background: rgba(120,169,255,0.08);
+}
+.sn-item:focus-visible {
+ outline: 2px solid rgba(120,169,255,0.7);
+ outline-offset: -2px;
+}
+.sn-item--current {
+ background: rgba(15,98,254,0.1);
+ cursor: default;
+ pointer-events: none;
+}
+.sn-item--current .sn-name {
+ color: var(--brand-blue-light, #78a9ff);
+}
+.sn-name {
+ font-size: 13px;
+ font-weight: 500;
+}
+.sn-tag {
+ font-size: 11px;
+ color: var(--faint, #6b7b96);
+ white-space: nowrap;
+}
+@media (max-width: 480px) {
+ .sn-btn { padding: 5px 10px; font-size: 11px; gap: 5px; }
+ .sn-drop { min-width: 200px; }
+}
+ `.trim();
+ document.head.appendChild(style);
+}
+
+if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+} else {
+ init();
+}
diff --git a/src/ibm-vision.js b/src/ibm-vision.js
index 0bada93c7..596516ae8 100644
--- a/src/ibm-vision.js
+++ b/src/ibm-vision.js
@@ -15,6 +15,7 @@ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+import { log } from './shared/log.js';
const REDUCED_MOTION =
typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
@@ -391,7 +392,7 @@ function loadModel(url) {
undefined,
(err) => {
if (token !== loadToken) return;
- console.warn('[granite-vision] model load failed', url, err);
+ log.warn('[granite-vision] model load failed', url, err);
if (!state.current?.thumbnail) {
showError(
'Couldn’t load this avatar',
diff --git a/src/idle-animation.js b/src/idle-animation.js
index cf7982d57..163d13185 100644
--- a/src/idle-animation.js
+++ b/src/idle-animation.js
@@ -12,6 +12,7 @@
*/
import { ACTION_TYPES } from './agent-protocol.js';
+import { log } from './shared/log.js';
const DEG2RAD = Math.PI / 180;
const TWO_PI = Math.PI * 2;
@@ -241,7 +242,7 @@ export class IdleAnimation {
!this._hipBone &&
this._morphMeshes.length === 0
) {
- console.warn(
+ log.warn(
'[IdleAnimation] No bones or morph targets found on avatar root — channels will be no-ops.',
);
}
diff --git a/src/labs.js b/src/labs.js
new file mode 100644
index 000000000..5118db48c
--- /dev/null
+++ b/src/labs.js
@@ -0,0 +1,257 @@
+// Use the static generated manifest. In dev Vite serves this from public/;
+// in prod Vercel serves it as a static asset (same content the /api/features
+// function returns, just without the extra CORS round-trip).
+const REGISTRY_URL = '/features.json';
+
+// Category metadata derived from path patterns in the registry
+const CATEGORIES = {
+ '/lipsync': { label: 'Voice', cat: 'voice', color: '#a78bfa', bg: 'rgba(167,139,250,.12)' },
+ '/lipsync/mic': { label: 'Voice', cat: 'voice', color: '#a78bfa', bg: 'rgba(167,139,250,.12)' },
+ '/voice': { label: 'Voice', cat: 'voice', color: '#a78bfa', bg: 'rgba(167,139,250,.12)' },
+ '/brain': { label: 'AI', cat: 'ai', color: '#60a5fa', bg: 'rgba(96,165,250,.12)' },
+ '/unstoppable': { label: 'AI', cat: 'ai', color: '#60a5fa', bg: 'rgba(96,165,250,.12)' },
+ '/three-live': { label: '3D Live', cat: '3d', color: '#34d399', bg: 'rgba(52,211,153,.12)' },
+ '/forever': { label: 'Crypto', cat: 'crypto', color: '#f97316', bg: 'rgba(249,115,22,.12)' },
+};
+
+function categorize(path) {
+ if (CATEGORIES[path]) return CATEGORIES[path];
+ return { label: 'x402', cat: 'x402', color: '#fbbf24', bg: 'rgba(251,191,36,.12)' };
+}
+
+// Human-readable plain-language blurb (trimmed to ~120 chars max for cards)
+function blurb(description) {
+ if (!description) return '';
+ const stripped = description.replace(/ — .*$/, '').trim();
+ return stripped.length > 130 ? stripped.slice(0, 127) + '…' : stripped;
+}
+
+// Check if a route resolves (HEAD fetch, 3s timeout)
+async function checkLive(path) {
+ try {
+ const ctrl = new AbortController();
+ const t = setTimeout(() => ctrl.abort(), 3000);
+ const res = await fetch(path, { method: 'HEAD', signal: ctrl.signal });
+ clearTimeout(t);
+ return res.status < 500;
+ } catch {
+ return false;
+ }
+}
+
+function buildSkeletons(count) {
+ return Array.from({ length: count }, () => {
+ const el = document.createElement('div');
+ el.className = 'gem-skeleton';
+ el.setAttribute('aria-hidden', 'true');
+ el.innerHTML = `
+ <div class="sk-preview"></div>
+ <div class="sk-body">
+ <div class="sk-line title"></div>
+ <div class="sk-line wide"></div>
+ <div class="sk-line short"></div>
+ </div>`;
+ return el;
+ });
+}
+
+function buildCard(gem) {
+ const { path, title, description } = gem;
+ const meta = categorize(path);
+
+ const article = document.createElement('article');
+ article.className = 'gem-card';
+ article.dataset.path = path;
+ article.dataset.cat = meta.cat;
+
+ // Set CSS custom properties for the category gradient on the card element
+ article.style.setProperty('--gem-cat-color', meta.color);
+ article.style.setProperty('--gem-cat-bg-1', meta.bg.replace(/\)$/, '').replace(/,[^,]+$/, ', 0.08)'));
+ article.style.setProperty('--gem-cat-bg-2', meta.bg.replace(/\)$/, '').replace(/,[^,]+$/, ', 0.03)'));
+
+ article.innerHTML = `
+ <div class="gem-preview" role="img" aria-label="Preview of ${escHtml(title)}">
+ <div class="gem-preview-fallback">
+ <span class="gem-preview-path">${escHtml(path)}</span>
+ </div>
+ <span class="gem-cat-badge"
+ style="color:${meta.color};background:${meta.bg};border-color:${meta.color}22"
+ aria-label="Category: ${escHtml(meta.label)}"
+ >${escHtml(meta.label)}</span>
+ </div>
+ <div class="gem-body">
+ <div class="gem-header">
+ <h2 class="gem-title">${escHtml(title)}</h2>
+ <span class="gem-status" data-state="checking" aria-live="polite" aria-label="Status: checking">Checking</span>
+ </div>
+ <p class="gem-desc">${escHtml(blurb(description))}</p>
+ <a class="gem-cta" href="${escHtml(path)}" aria-label="Try ${escHtml(title)}">Try it →</a>
+ </div>`;
+
+ return article;
+}
+
+function escHtml(str) {
+ return String(str)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
+
+// Attach a lazy-loading iframe preview via IntersectionObserver
+function attachPreview(card) {
+ const previewEl = card.querySelector('.gem-preview');
+ if (!previewEl) return;
+ const path = card.dataset.path;
+
+ const observer = new IntersectionObserver((entries, obs) => {
+ if (!entries[0].isIntersecting) return;
+ obs.disconnect();
+
+ const iframe = document.createElement('iframe');
+ iframe.src = path;
+ iframe.setAttribute('loading', 'lazy');
+ iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin');
+ iframe.setAttribute('tabindex', '-1');
+ iframe.setAttribute('aria-hidden', 'true');
+ iframe.setAttribute('title', '');
+ previewEl.insertBefore(iframe, previewEl.firstChild);
+ }, { rootMargin: '200px' });
+
+ observer.observe(card);
+}
+
+// Update a card's status pill
+async function updateStatus(card, statusCounter) {
+ const path = card.dataset.path;
+ const pill = card.querySelector('.gem-status');
+ if (!pill) return;
+
+ const live = await checkLive(path);
+ pill.dataset.state = live ? 'live' : 'offline';
+ pill.textContent = live ? 'Live' : 'Offline';
+ pill.setAttribute('aria-label', `Status: ${live ? 'live' : 'offline'}`);
+
+ if (live) statusCounter.count++;
+ statusCounter.done++;
+ if (statusCounter.done === statusCounter.total) {
+ const liveEl = document.getElementById('labs-live-count');
+ if (liveEl) liveEl.textContent = statusCounter.count;
+ }
+}
+
+let allGems = [];
+let activeFilter = 'all';
+
+function applyFilter(cat) {
+ activeFilter = cat;
+ const grid = document.getElementById('labs-grid');
+ if (!grid) return;
+
+ const cards = grid.querySelectorAll('.gem-card');
+ let visible = 0;
+ cards.forEach(card => {
+ const match = cat === 'all' || card.dataset.cat === cat;
+ card.hidden = !match;
+ if (match) visible++;
+ });
+
+ const countEl = document.getElementById('labs-result-count');
+ if (countEl) countEl.textContent = `${visible} feature${visible !== 1 ? 's' : ''}`;
+
+ const emptyEl = document.getElementById('labs-empty');
+ if (emptyEl) emptyEl.setAttribute('aria-hidden', visible > 0 ? 'true' : 'false');
+}
+
+async function load() {
+ const grid = document.getElementById('labs-grid');
+ if (!grid) return;
+
+ // Clear skeletons, keep empty/error states
+ Array.from(grid.querySelectorAll('.gem-skeleton')).forEach(el => el.remove());
+ grid.setAttribute('aria-busy', 'true');
+
+ const errorEl = document.getElementById('labs-error');
+ if (errorEl) errorEl.setAttribute('aria-hidden', 'true');
+ const emptyEl = document.getElementById('labs-empty');
+ if (emptyEl) emptyEl.setAttribute('aria-hidden', 'true');
+
+ let manifest;
+ try {
+ const res = await fetch(REGISTRY_URL);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ manifest = await res.json();
+ } catch {
+ grid.setAttribute('aria-busy', 'false');
+ if (errorEl) errorEl.setAttribute('aria-hidden', 'false');
+ return;
+ }
+
+ // Collect all showcase pages across all sections
+ allGems = manifest.sections
+ .flatMap(s => s.pages)
+ .filter(p => p.showcase === true);
+
+ // Update gem count
+ const countEl = document.getElementById('labs-gem-count');
+ if (countEl) countEl.textContent = allGems.length;
+
+ if (allGems.length === 0) {
+ grid.setAttribute('aria-busy', 'false');
+ if (emptyEl) emptyEl.setAttribute('aria-hidden', 'false');
+ return;
+ }
+
+ // Status counter shared across all async checks
+ const statusCounter = { total: allGems.length, done: 0, count: 0 };
+
+ // Build and insert cards
+ const fragment = document.createDocumentFragment();
+ for (const gem of allGems) {
+ const card = buildCard(gem);
+ fragment.appendChild(card);
+ }
+ grid.insertBefore(fragment, grid.querySelector('.labs-empty'));
+ grid.setAttribute('aria-busy', 'false');
+
+ // Apply current filter
+ applyFilter(activeFilter);
+
+ // Attach iframe previews and kick off status checks concurrently
+ for (const gem of allGems) {
+ const card = grid.querySelector(`.gem-card[data-path="${CSS.escape(gem.path)}"]`);
+ if (!card) continue;
+ attachPreview(card);
+ updateStatus(card, statusCounter);
+ }
+
+ // Update result count
+ const resultEl = document.getElementById('labs-result-count');
+ if (resultEl) {
+ resultEl.textContent = `${allGems.length} feature${allGems.length !== 1 ? 's' : ''}`;
+ }
+}
+
+function init() {
+ // Filter buttons
+ document.querySelectorAll('.labs-filter').forEach(btn => {
+ btn.addEventListener('click', () => {
+ document.querySelectorAll('.labs-filter').forEach(b => b.classList.remove('active'));
+ btn.classList.add('active');
+ applyFilter(btn.dataset.cat || 'all');
+ });
+ });
+
+ // Retry button
+ const retryBtn = document.getElementById('labs-retry');
+ if (retryBtn) retryBtn.addEventListener('click', load);
+
+ load();
+}
+
+if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+} else {
+ init();
+}
diff --git a/src/live-economy.js b/src/live-economy.js
index 69a6bc634..fbb77f9cc 100644
--- a/src/live-economy.js
+++ b/src/live-economy.js
@@ -15,7 +15,7 @@ const FOV = 60;
// 3D positions (x, y, z). Camera looks slightly down at the stage.
const CAM_POS = new THREE.Vector3(0, 6, 18);
const CAM_TARGET = new THREE.Vector3(0, 1.5, 0);
-const AGENT_A_POS = new THREE.Vector3(-7, 0, 0); // Oracle (purple, right in world space)
+const AGENT_A_POS = new THREE.Vector3(-7, 0, 0); // Oracle (white, right in world space)
const AGENT_B_POS = new THREE.Vector3( 7, 0, 0); // Trader (blue, left)
const TV_POS = new THREE.Vector3( 0, 4.2, -6);
@@ -49,8 +49,8 @@ const sunLight = new THREE.DirectionalLight(0xc0cfff, 0.6);
sunLight.position.set(0, 20, 10);
scene.add(sunLight);
-// Oracle point light (purple)
-const oracleLight = new THREE.PointLight(0xa855f7, 3.5, 18);
+// Oracle point light (white)
+const oracleLight = new THREE.PointLight(0xffffff, 2.5, 18);
oracleLight.position.set(AGENT_A_POS.x, 4, AGENT_A_POS.z + 2);
scene.add(oracleLight);
@@ -105,7 +105,7 @@ function makePedestal(position, color) {
return { group, ring };
}
-const pedestalA = makePedestal(AGENT_A_POS, 0xa855f7); // Oracle purple
+const pedestalA = makePedestal(AGENT_A_POS, 0xffffff); // Oracle white
const pedestalB = makePedestal(AGENT_B_POS, 0x4e8cff); // Trader blue
// ── TV Screen ─────────────────────────────────────────────────────────────
@@ -167,9 +167,9 @@ export function drawTvData(markets) {
tvCtx.fillRect(0, 0, TV_W, TV_H);
// Header bar
- tvCtx.fillStyle = 'rgba(168,85,247,0.15)';
+ tvCtx.fillStyle = 'rgba(255,255,255,0.07)';
tvCtx.fillRect(0, 0, TV_W, 44);
- tvCtx.fillStyle = '#a855f7';
+ tvCtx.fillStyle = '#888888';
tvCtx.font = 'bold 13px -apple-system, system-ui, sans-serif';
tvCtx.textAlign = 'left';
tvCtx.fillText('● ORACLE INTEL FEED · SOLANA LIVE', 16, 28);
diff --git a/src/marketplace-detail.js b/src/marketplace-detail.js
index bb4333702..e13d8030d 100644
--- a/src/marketplace-detail.js
+++ b/src/marketplace-detail.js
@@ -12,6 +12,7 @@
import { onchainBadgeHTML } from './shared/onchain-badge.js';
import { coinChipHTML } from './shared/agent-coin.js';
+import { log } from './shared/log.js';
const API = '/api';
const $ = (id) => document.getElementById(id);
@@ -203,7 +204,7 @@ export async function submitPreviewMessage(e) {
footer.textContent = modelLabel ? `via ${modelLabel}` : '';
} catch (err) {
if (err.name === 'AbortError') return;
- console.error('[marketplace] preview', err);
+ log.error('[marketplace] preview', err);
if (assistantBubble) {
assistantBubble.classList.remove('streaming');
if (!assistantText) assistantText = '— preview failed';
@@ -252,7 +253,7 @@ export async function openCreatorModal(creatorId, deps = {}) {
activeCreator = j?.data;
renderCreatorModal(activeCreator, deps);
} catch (err) {
- console.error('[marketplace] creator', err);
+ log.error('[marketplace] creator', err);
$('creator-modal-title').textContent = 'Could not load creator';
$('creator-agents-grid').innerHTML = `<div class="market-empty">${escapeHtml(err.message || 'Failed')}</div>`;
$('creator-avatars-grid').innerHTML = '';
diff --git a/src/marketplace-lobby.js b/src/marketplace-lobby.js
index 59949b248..c2886a2d2 100644
--- a/src/marketplace-lobby.js
+++ b/src/marketplace-lobby.js
@@ -38,6 +38,7 @@ import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast } from 'three-mesh-bvh';
import { EffectComposer, RenderPass, SelectiveBloomEffect, EffectPass } from 'postprocessing';
import { getMeshoptDecoder } from './viewer/internal.js';
+import { log } from './shared/log.js';
// Accelerate click-to-select raycasting with a BVH. Patches the Three.js
// prototypes once at module load — idempotent if the main viewer already did so.
@@ -156,7 +157,7 @@ export async function mountLobby(canvas, avatars, options = {}) {
slotMeta[i].avatar = avatar;
},
undefined,
- (err) => console.warn('[lobby] failed to load', url, err?.message),
+ (err) => log.warn('[lobby] failed to load', url, err?.message),
);
});
});
diff --git a/src/marketplace.js b/src/marketplace.js
index c771a3a33..8273728f4 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -18,6 +18,9 @@ import {
} from './marketplace-detail.js';
import { onchainBadgeHTML } from './shared/onchain-badge.js';
import { coinChipHTML } from './shared/agent-coin.js';
+import { skeletonHTML, ensureStateKitStyles } from './shared/state-kit.js';
+import { log } from './shared/log.js';
+ensureStateKitStyles();
const API = '/api';
@@ -43,7 +46,7 @@ async function fetchUserPurchases() {
const list = j.data?.purchases || [];
purchasedSkills = new Set(list.map((p) => `${p.agent_id}:${p.skill}`));
} catch (err) {
- console.error('[marketplace] purchases', err);
+ log.error('[marketplace] purchases', err);
}
}
@@ -55,7 +58,7 @@ async function fetchUserBookmarks() {
const j = await r.json();
bookmarkedAgents = new Set(j.data?.agent_ids || []);
} catch (err) {
- console.error('[marketplace] bookmarks', err);
+ log.error('[marketplace] bookmarks', err);
}
}
@@ -85,7 +88,7 @@ async function toggleAgentBookmarkFromCard(agentId, btn) {
btn.classList.toggle('on', wasOn);
btn.setAttribute('aria-pressed', String(wasOn));
btn.textContent = wasOn ? '★' : '☆';
- console.error('[marketplace] toggle bookmark', err);
+ log.error('[marketplace] toggle bookmark', err);
}
}
@@ -150,7 +153,7 @@ const els = {
// Filter values that round-trip through ?tab= on the list view. Kept here so
// readRoute and syncFilterToUrl agree on which strings are valid.
const LIST_FILTER_TABS = new Set(['agents', 'avatars', 'onchain']);
-const SORT_VALUES = new Set(['recommended', 'recent', 'popular']);
+const SORT_VALUES = new Set(['recommended', 'recent', 'popular', 'top_rated']);
function readRoute() {
const m = location.pathname.match(/^\/marketplace\/agents\/([^/]+)/);
@@ -331,7 +334,7 @@ async function loadCategories() {
const j = await r.json();
renderCategories(j.data);
} catch (err) {
- console.error('[marketplace] categories', err);
+ log.error('[marketplace] categories', err);
}
}
@@ -428,7 +431,8 @@ async function loadList(reset = false) {
if (reset) {
state.items = [];
state.cursor = null;
- els.grid.innerHTML = '<div class="market-empty">Loading…</div>';
+ els.grid.setAttribute('aria-busy', 'true');
+ els.grid.innerHTML = skeletonHTML(8, 'card');
}
try {
const url = new URL(`${API}/marketplace/agents`, location.origin);
@@ -447,7 +451,7 @@ async function loadList(reset = false) {
state.cursor = nextCursor;
renderGrid();
} catch (err) {
- console.error('[marketplace] list', err);
+ log.error('[marketplace] list', err);
els.grid.innerHTML = renderErrorState('agents');
} finally {
state.loading = false;
@@ -503,7 +507,7 @@ async function loadPublicAvatars() {
renderGrid();
updateOnchainChipCount();
} catch (err) {
- console.error('[marketplace] public avatars', err);
+ log.error('[marketplace] public avatars', err);
}
}
@@ -532,7 +536,7 @@ async function loadOnchainAgents(reset = false) {
if (state.filter === 'onchain' || state.filter === 'all') renderGrid();
updateOnchainChipCount();
} catch (err) {
- console.error('[marketplace] onchain', err);
+ log.error('[marketplace] onchain', err);
}
}
@@ -575,7 +579,7 @@ async function openLobby() {
},
});
} catch (err) {
- console.error('[marketplace] lobby load', err);
+ log.error('[marketplace] lobby load', err);
closeLobby();
}
}
@@ -600,7 +604,7 @@ async function loadTheme() {
state.theme = theme;
renderTheme();
} catch (err) {
- console.error('[marketplace] theme', err);
+ log.error('[marketplace] theme', err);
}
}
@@ -657,7 +661,7 @@ async function loadFeatured() {
renderHero();
startHeroAutoplay();
} catch (err) {
- console.error('[marketplace] featured', err);
+ log.error('[marketplace] featured', err);
}
}
@@ -940,6 +944,13 @@ function renderGrid() {
const totalCards = agentItems.length + avatars.length + onchain.length;
+ const resultCountEl = $('market-result-count');
+ if (resultCountEl) {
+ resultCountEl.textContent = totalCards
+ ? `${totalCards} result${totalCards === 1 ? '' : 's'}`
+ : '';
+ }
+
if (!totalCards) {
const stillLoading =
(!state.publicAvatarsLoaded && state.filter !== 'agents' && state.filter !== 'onchain') ||
@@ -986,6 +997,7 @@ function renderGrid() {
html += '<div class="market-loadmore-spinner" aria-label="Loading more…"></div>';
}
+ els.grid.removeAttribute('aria-busy');
els.grid.innerHTML = html;
// Poster cache + shimmer-off for model-viewers.
@@ -1007,6 +1019,12 @@ function renderGrid() {
}
navTo(`/marketplace/agents/${card.dataset.id}`);
});
+ card.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ navTo(`/marketplace/agents/${card.dataset.id}`);
+ }
+ });
});
els.grid.querySelectorAll('[data-avatar-id]').forEach((card) => {
card.addEventListener('click', (e) => {
@@ -1021,6 +1039,13 @@ function renderGrid() {
const id = card.dataset.avatarId;
if (id) navTo(`/marketplace/avatars/${encodeURIComponent(id)}`);
});
+ card.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ const id = card.dataset.avatarId;
+ if (id) navTo(`/marketplace/avatars/${encodeURIComponent(id)}`);
+ }
+ });
});
els.grid.querySelectorAll('[data-onchain-id]').forEach((card) => {
const oid = card.dataset.onchainId;
@@ -1037,6 +1062,17 @@ function renderGrid() {
});
});
+ // Card profile links — intercept normal left-clicks for SPA navigation so
+ // the user stays in the single-page context. Ctrl/Cmd/middle-click falls
+ // through to let the browser open in a new tab as expected.
+ els.grid.querySelectorAll('.card-profile-link').forEach((link) => {
+ link.addEventListener('click', (e) => {
+ if (e.ctrlKey || e.metaKey || e.shiftKey || e.button !== 0) return;
+ e.preventDefault();
+ navTo(link.getAttribute('href'));
+ });
+ });
+
// Tag pills inside cards navigate to ?tag=X so the URL is shareable and
// browser back/forward works. render() picks up state.tag from the route.
els.grid.querySelectorAll('[data-tag]').forEach((pill) => {
@@ -1241,7 +1277,7 @@ async function renderAvatarSalePanel(avatar) {
const j = await r.json();
detail = j?.avatar;
} catch (err) {
- console.warn('[marketplace] sale-panel fetch failed', err);
+ log.warn('[marketplace] sale-panel fetch failed', err);
return;
}
if (!detail) return;
@@ -1645,7 +1681,7 @@ async function loadSkillCategories() {
skillsState.categories = Array.isArray(j?.categories) ? j.categories : [];
renderSkillCategoryChips();
} catch (err) {
- console.error('[marketplace] skills categories', err);
+ log.error('[marketplace] skills categories', err);
}
}
@@ -1700,10 +1736,14 @@ async function loadSkillsTab(force = false, append = false) {
skillsState.cursor = j?.next_cursor || null;
skillsState.loaded = true;
} catch (err) {
- console.error('[marketplace] skills load', err);
+ log.error('[marketplace] skills load', err);
if (grid && !append) {
- grid.innerHTML = `<div class="market-empty">Failed to load skills. <button id="skills-retry" class="market-empty-cta-btn">Retry</button></div>`;
- $('skills-retry')?.addEventListener('click', () => loadSkillsTab(true));
+ grid.innerHTML = renderErrorState('skills');
+ grid.querySelector('[data-empty-action="empty-retry"]')?.addEventListener('click', () => {
+ grid.setAttribute('aria-busy', 'true');
+ grid.innerHTML = renderSkeletons(8);
+ loadSkillsTab(true);
+ });
}
} finally {
skillsState.loading = false;
@@ -1851,7 +1891,7 @@ async function loadSkillDetail(id) {
skill = j?.skill || null;
}
} catch (err) {
- console.error('[marketplace] skill detail', err);
+ log.error('[marketplace] skill detail', err);
}
if (readRoute().view !== 'skill-detail') return;
@@ -2033,7 +2073,7 @@ function copyToClipboard(text, btn) {
btn.textContent = 'Copied!';
btn.classList.add('copied');
setTimeout(() => { btn.textContent = original; btn.classList.remove('copied'); }, 1500);
- }).catch((err) => console.error('[marketplace] clipboard', err));
+ }).catch((err) => log.error('[marketplace] clipboard', err));
}
// Render the per-call x402 panel. Free skills hide it entirely — there's
@@ -2095,7 +2135,7 @@ async function toggleSkillInstall(id) {
await loadSkillDetail(id);
loadSkillsTab(true);
} catch (err) {
- console.error('[marketplace] skill install', err);
+ log.error('[marketplace] skill install', err);
btn.disabled = false;
btn.textContent = wasInstalled ? 'Installed ✓ — Remove' : 'Install';
}
@@ -2117,7 +2157,7 @@ async function rateSkill(id, rating) {
_skillDetailId = null;
await loadSkillDetail(id);
} catch (err) {
- console.error('[marketplace] skill rate', err);
+ log.error('[marketplace] skill rate', err);
}
}
@@ -2135,7 +2175,7 @@ async function shareCurrentPage(btn, title, text) {
btn.classList.add('copied');
setTimeout(() => { btn.textContent = original; btn.classList.remove('copied'); }, 1800);
} catch (err) {
- console.error('[marketplace] share copy', err);
+ log.error('[marketplace] share copy', err);
}
}
@@ -2168,7 +2208,7 @@ async function loadPurchases(force = false) {
purchasesState.items = j?.data?.purchases || [];
purchasesState.loaded = true;
} catch (err) {
- console.error('[marketplace] purchases load', err);
+ log.error('[marketplace] purchases load', err);
} finally {
purchasesState.loading = false;
}
@@ -2221,7 +2261,7 @@ function renderPurchaseCard(p) {
const thumb = p.agent_thumbnail
? `<div class="avatar avatar-img" style="background-image:url('${escapeHtml(p.agent_thumbnail)}');width:36px;height:36px;border-radius:8px;flex-shrink:0"></div>`
: `<div class="avatar" style="width:36px;height:36px;border-radius:8px;flex-shrink:0;display:flex;align-items:center;justify-content:center;background:#1a1a1a;font-size:16px">${escapeHtml(initial(p.agent_name || '?'))}</div>`;
- return `<div class="market-card-agent" data-purchase-agent="${escapeHtml(p.agent_id)}" style="cursor:pointer">
+ return `<div class="card card--interactive market-card-agent" data-purchase-agent="${escapeHtml(p.agent_id)}">
<div class="head">
${thumb}
<div style="min-width:0;flex:1">
@@ -2334,7 +2374,7 @@ async function loadEarnTab(force = false) {
earnState.loaded = true;
} catch (err) {
- console.error('[marketplace] earn tab', err);
+ log.error('[marketplace] earn tab', err);
earnState.errorMsg = 'Network error — check your connection and try again.';
} finally {
earnState.loading = false;
@@ -2358,7 +2398,7 @@ async function loadEarnRevenue() {
earnState.revTimeseries = j.timeseries || [];
}
} catch (err) {
- console.error('[marketplace] revenue chart', err);
+ log.error('[marketplace] revenue chart', err);
} finally {
earnState.revLoading = false;
}
@@ -2560,11 +2600,11 @@ function renderEarnTransactions() {
if (!visible.length) { el.innerHTML = ''; return; }
const kindIcons = { skill: '≡', avatar: '◉', agent: '▣' };
- const kindColors = { skill: '#60a5fa', avatar: '#a78bfa', agent: '#34d399' };
+ const kindColors = { skill: '#60a5fa', avatar: '#888888', agent: '#34d399' };
el.innerHTML = visible.map(e => {
const icon = kindIcons[e.kind] || '·';
- const color = kindColors[e.kind] || 'var(--mk-text-3)';
+ const color = kindColors[e.kind] || 'var(--ink-dim)';
const statusCls = e.status === 'settled' ? 'earn-status-settled' : 'earn-status-pending';
const date = e.created_at ? formatDate(e.created_at) : '';
return `<div class="earn-txn">
@@ -2909,8 +2949,8 @@ async function loadAnimationsTab(force = false) {
animState.items = arr;
animState.loaded = true;
} catch (err) {
- console.error('[marketplace] animations', err);
- if (grid) grid.innerHTML = `<div class="market-empty">Could not load animations.</div>`;
+ log.error('[marketplace] animations', err);
+ if (grid) grid.innerHTML = renderErrorState('animations');
} finally {
animState.loading = false;
}
@@ -3013,7 +3053,7 @@ async function loadAnimDetail(name) {
animState.loaded = true;
}
} catch (err) {
- console.error('[marketplace] anim manifest', err);
+ log.error('[marketplace] anim manifest', err);
}
}
@@ -3176,7 +3216,7 @@ async function loadOnchainDetail(composite) {
item = j?.item || null;
}
} catch (err) {
- console.error('[marketplace] onchain detail', err);
+ log.error('[marketplace] onchain detail', err);
}
}
@@ -3337,7 +3377,10 @@ async function loadMemoryTab(force = false) {
if (memoryState.loaded && !force) { renderMemoryTab(); return; }
memoryState.loading = true;
const body = $('market-memory-body');
- if (body) body.innerHTML = `<div class="market-empty">Loading…</div>`;
+ if (body) {
+ body.setAttribute('aria-busy', 'true');
+ body.innerHTML = skeletonHTML(4, 'row');
+ }
try {
const agentsRes = await fetch(`${API}/marketplace/agents/mine`, { credentials: 'include' });
if (agentsRes.status === 401) {
@@ -3368,7 +3411,7 @@ async function loadMemoryTab(force = false) {
memoryState.entries = memorySets.flat().sort((a, b) => (b.updatedAt || b.createdAt || 0) - (a.updatedAt || a.createdAt || 0));
memoryState.loaded = true;
} catch (err) {
- console.error('[marketplace] memory', err);
+ log.error('[marketplace] memory', err);
} finally {
memoryState.loading = false;
}
@@ -3447,7 +3490,7 @@ function renderMemoryTab() {
}
function _memoryIconBg(type) {
- const map = { user: 'background:rgba(59,130,246,0.15)', feedback: 'background:rgba(234,179,8,0.15)', project: 'background:rgba(34,197,94,0.15)', reference: 'background:rgba(168,85,247,0.15)' };
+ const map = { user: 'background:rgba(59,130,246,0.15)', feedback: 'background:rgba(234,179,8,0.15)', project: 'background:rgba(34,197,94,0.15)', reference: 'background:rgba(255,255,255,0.07)' };
return map[type] || 'background:rgba(255,255,255,0.06)';
}
@@ -3479,7 +3522,7 @@ async function loadMine(force = false) {
mineState.items = Array.isArray(j) ? j : (j?.data?.items ?? []);
mineState.loaded = true;
} catch (err) {
- console.error('[marketplace] mine', err);
+ log.error('[marketplace] mine', err);
} finally {
mineState.loading = false;
}
@@ -3513,20 +3556,13 @@ function renderMineGrid() {
}
function renderSkeletons(n) {
- const cards = Array.from({ length: n }, () =>
- `<div class="market-card-skeleton"><div class="sk-thumb"></div><div class="sk-line"></div><div class="sk-line short"></div></div>`,
- ).join('');
- return cards;
+ return skeletonHTML(n, 'card');
}
-// Empty-state block with a recovery action — when the grid is empty we want
-// the user to be able to escape the dead-end with one click (clear the search,
-// drop the filter, or submit/create their own content).
function renderEmptyState() {
const hasSearch = !!state.q;
const hasTag = !!state.tag;
const hasCategory = !!state.category;
- const hasFilter = state.filter && state.filter !== 'all';
let title;
let body;
@@ -3559,33 +3595,31 @@ function renderEmptyState() {
actions.push({ id: 'empty-create-avatar', label: '+ Create Avatar', primary: false });
}
+ // Use state-kit shell; keep data-empty-action for the existing delegation handler.
const buttons = actions
.map(
(a) =>
- `<button type="button" class="market-empty-cta-btn${a.primary ? ' primary' : ''}" data-empty-action="${a.id}">${escapeHtml(a.label)}</button>`,
+ `<button type="button" class="tws-es-btn${a.primary ? ' tws-es-btn--primary' : ''}" data-empty-action="${a.id}">${escapeHtml(a.label)}</button>`,
)
.join('');
- return `
- <div class="market-empty-cta" role="status">
- <h3>${escapeHtml(title)}</h3>
- <p>${body}</p>
- <div class="market-empty-cta-actions">${buttons}</div>
- </div>`;
+ return `<div class="tws-es" role="status">
+ <h3 class="tws-es-title">${escapeHtml(title)}</h3>
+ <p class="tws-es-body">${body}</p>
+ <div class="tws-es-actions">${buttons}</div>
+ </div>`;
}
-// Error state with a retry CTA. Shown when an API call rejects so the user
-// can recover without manually refreshing the page.
function renderErrorState(scope = 'agents') {
const label = scope === 'avatars' ? 'avatars' : scope === 'onchain' ? 'onchain agents' : 'agents';
- return `
- <div class="market-empty-cta" role="alert">
- <h3>Couldn't load ${escapeHtml(label)}</h3>
- <p>The marketplace server didn't respond. Check your connection and try again.</p>
- <div class="market-empty-cta-actions">
- <button type="button" class="market-empty-cta-btn primary" data-empty-action="empty-retry" data-retry-scope="${escapeHtml(scope)}">Retry</button>
- </div>
- </div>`;
+ return `<div class="tws-es tws-es--error" role="alert">
+ <div class="tws-es-icon tws-es-icon--err" aria-hidden="true"><svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="16" cy="16" r="14" stroke="currentColor" stroke-width="1.5" opacity=".35"/><path d="M16 9v8" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><circle cx="16" cy="22.5" r="1.25" fill="currentColor"/></svg></div>
+ <h3 class="tws-es-title">Couldn't load ${escapeHtml(label)}</h3>
+ <p class="tws-es-body">The marketplace server didn't respond. Check your connection and try again.</p>
+ <div class="tws-es-actions">
+ <button type="button" class="tws-es-btn tws-es-btn--primary" data-empty-action="empty-retry" data-retry-scope="${escapeHtml(scope)}">Retry</button>
+ </div>
+ </div>`;
}
// Single delegated click handler so empty-state buttons keep working across
@@ -3630,7 +3664,8 @@ function bindEmptyStateActions() {
location.href = '/create';
} else if (action === 'empty-retry') {
const scope = btn.dataset.retryScope || 'agents';
- els.grid.innerHTML = '<div class="market-empty">Retrying…</div>';
+ els.grid.setAttribute('aria-busy', 'true');
+ els.grid.innerHTML = skeletonHTML(8, 'card');
if (scope === 'avatars') {
state.publicAvatarsLoaded = false;
loadPublicAvatars();
@@ -3696,11 +3731,11 @@ function renderAvatarCard(a, spotlight = false) {
const bmActive = getAvatarBookmarks().has(a.avatarId || '');
const priceBadge = priceBadgeHtml(a.price);
const cardClasses = ['market-card-avatar', isSpotlight && 'market-card-avatar--featured'].filter(Boolean).join(' ');
- return `<div class="${cardClasses}" data-avatar-id="${escapeHtml(a.avatarId || '')}">
+ return `<div class="${cardClasses}" role="link" tabindex="0" data-avatar-id="${escapeHtml(a.avatarId || '')}">
<div class="thumb">${spotlightBadge}${priceBadge}${preview}</div>
<div class="body">
<div class="title-row">
- <div class="title">${name}</div>
+ <a class="title card-profile-link" href="/marketplace/avatars/${encodeURIComponent(a.avatarId || '')}" tabindex="-1">${name}</a>
<button type="button" class="card-heart${bmActive ? ' active' : ''}" data-bm-id="${escapeHtml(a.avatarId||'')}" aria-label="Bookmark" aria-pressed="${bmActive}">♥</button>
</div>
<div class="byline">${authorLine}${when ? `<span class="dot">·</span><span class="when">${escapeHtml(when)}</span>` : ''}</div>
@@ -3755,14 +3790,14 @@ function renderCard(a) {
const bmOn = bookmarkedAgents.has(a.id);
const starBtn = `<button type="button" class="card-star${bmOn ? ' on' : ''}" data-agent-bm="${escapeHtml(a.id)}" aria-label="Bookmark agent" aria-pressed="${bmOn}" title="${bmOn ? 'Remove bookmark' : 'Bookmark agent'}">${bmOn ? '★' : '☆'}</button>`;
const onchainBadge = onchainBadgeHTML(a);
- return `<div class="market-card-agent" data-id="${a.id}">
+ return `<div class="card card--interactive market-card-agent" role="link" tabindex="0" data-id="${a.id}">
${previewStrip}
${priceBadge}
${starBtn}
<div class="head">
${avatarBlock}
<div style="min-width:0;flex:1">
- <div class="title">${escapeHtml(a.name || 'Untitled')}</div>
+ <a class="title card-profile-link" href="/marketplace/agents/${a.id}" tabindex="-1">${escapeHtml(a.name || 'Untitled')}</a>
<div class="author">${escapeHtml(author)}</div>
</div>
</div>
@@ -3818,7 +3853,7 @@ function renderOnchainCard(a) {
return `<div class="market-card-avatar onchain" role="link" tabindex="0" data-onchain-id="${escapeHtml(onchainId)}" data-onchain-href="${escapeHtml(href)}">
<div class="thumb">${priceBadge}${preview}</div>
<div class="body">
- <div class="title">${name}</div>
+ <a class="title card-profile-link" href="/marketplace/onchain/${encodeURIComponent(onchainId)}" tabindex="-1">${name}</a>
<div class="byline">
<span class="card-chain">${chain}</span>
${ownerShort ? `<span class="dot">·</span><span class="card-author muted">${escapeHtml(ownerShort)}</span>` : ''}
@@ -3879,7 +3914,7 @@ async function loadDetail(id) {
renderSimilar(similar);
}).catch(() => { /* best-effort — main detail already rendered */ });
} catch (err) {
- console.error('[marketplace] detail load', err);
+ log.error('[marketplace] detail load', err);
if (!cached) showDetailState('error', { id });
}
}
@@ -3998,7 +4033,7 @@ async function loadAvatarDetail(id) {
avatar = _normaliseAvatar(j?.avatar || j?.data?.avatar || j);
}
} catch (err) {
- console.error('[marketplace] avatar detail fetch', err);
+ log.error('[marketplace] avatar detail fetch', err);
}
}
@@ -4062,7 +4097,7 @@ async function loadAvatarDetail(id) {
shareBtn.classList.add('copied');
setTimeout(() => { shareBtn.textContent = original; shareBtn.classList.remove('copied'); }, 1800);
} catch (err) {
- console.error('[marketplace] share copy', err);
+ log.error('[marketplace] share copy', err);
}
};
}
@@ -4380,23 +4415,38 @@ function renderSimilar(items) {
card.addEventListener('click', () => navTo(`/marketplace/agents/${card.dataset.id}`));
});
- side.innerHTML =
- `<div class="related-side-title">Related Agents <a href="#" id="rel-more">View More ›</a></div>` +
- items
- .slice(0, 4)
- .map(
- (a) => `<div class="related-card" data-id="${a.id}">
- <div class="av">${initial(a.name)}</div>
- <div style="min-width:0">
- <div class="name">${escapeHtml(a.name || '')}</div>
- <div class="desc">${escapeHtml(a.description || '')}</div>
- </div>
- </div>`,
- )
- .join('');
- side.querySelectorAll('[data-id]').forEach((card) => {
- card.addEventListener('click', () => navTo(`/marketplace/agents/${card.dataset.id}`));
- });
+ // "View more" toggles the side list between the top 4 and the full set,
+ // rather than dead-ending on an href="#". Only shown when there's more to see.
+ const renderSideList = (expanded) => {
+ const shown = expanded ? items : items.slice(0, 4);
+ const moreLabel = items.length > 4 ? (expanded ? 'Show less ‹' : 'View more ›') : '';
+ side.innerHTML =
+ `<div class="related-side-title">Related Agents${
+ moreLabel ? ` <a href="#" id="rel-more" role="button">${moreLabel}</a>` : ''
+ }</div>` +
+ shown
+ .map(
+ (a) => `<div class="related-card" data-id="${a.id}">
+ <div class="av">${initial(a.name)}</div>
+ <div style="min-width:0">
+ <div class="name">${escapeHtml(a.name || '')}</div>
+ <div class="desc">${escapeHtml(a.description || '')}</div>
+ </div>
+ </div>`,
+ )
+ .join('');
+ side.querySelectorAll('[data-id]').forEach((card) => {
+ card.addEventListener('click', () => navTo(`/marketplace/agents/${card.dataset.id}`));
+ });
+ const moreLink = side.querySelector('#rel-more');
+ if (moreLink) {
+ moreLink.addEventListener('click', (e) => {
+ e.preventDefault();
+ renderSideList(!expanded);
+ });
+ }
+ };
+ renderSideList(false);
}
// ── Reviews & Ratings ─────────────────────────────────────────────────────
@@ -4429,7 +4479,7 @@ async function loadReviews(agentId) {
renderReviewInput();
renderReviewsList();
} catch (err) {
- console.error('[marketplace] reviews', err);
+ log.error('[marketplace] reviews', err);
reviewsState.loading = false;
const msg = $('d-rating-msg');
if (msg) { msg.textContent = 'Could not load reviews.'; msg.classList.add('err'); }
@@ -4528,7 +4578,7 @@ function renderReviewInput() {
</div>
</div>
<div class="review-edit-form" id="d-review-edit-form" hidden>
- <span style="font-size:12px;color:var(--mk-text-2)">Update your rating:</span>
+ <span style="font-size:12px;color:var(--ink-dim)">Update your rating:</span>
<span class="stars review-star-picker" id="d-rating-pick-edit" role="radiogroup" aria-label="Pick a rating">
${[1,2,3,4,5].map(i => `<button type="button" class="star-pick${i <= reviewsState.myReview.rating ? ' active' : ''}" data-rating="${i}" aria-label="${i} star${i>1?'s':''}">${i <= reviewsState.myReview.rating ? '★' : '☆'}</button>`).join('')}
</span>
@@ -4555,7 +4605,7 @@ function renderReviewInput() {
bindStarPicker($('d-rating-pick-edit'));
} else {
input.innerHTML = `
- <span style="font-size:12px;color:var(--mk-text-2)">Your rating:</span>
+ <span style="font-size:12px;color:var(--ink-dim)">Your rating:</span>
<span class="stars review-star-picker" id="d-rating-pick" role="radiogroup" aria-label="Pick a rating">
${[1,2,3,4,5].map(i => `<button type="button" class="star-pick" data-rating="${i}" aria-label="${i} star${i>1?'s':''}">${i <= reviewsState.selectedRating ? '★' : '☆'}</button>`).join('')}
</span>
@@ -4631,7 +4681,7 @@ async function submitReview(rating, body) {
setTimeout(() => { if (msg) msg.textContent = ''; }, 3000);
loadReviews(reviewsState.agentId);
} catch (err) {
- console.error('[marketplace] submit review', err);
+ log.error('[marketplace] submit review', err);
if (msg) { msg.textContent = err.message || 'Failed to save review.'; msg.classList.add('err'); }
} finally {
reviewsState.submitting = false;
@@ -4662,7 +4712,7 @@ async function deleteReview() {
setTimeout(() => { if (msg) msg.textContent = ''; }, 3000);
loadReviews(reviewsState.agentId);
} catch (err) {
- console.error('[marketplace] delete review', err);
+ log.error('[marketplace] delete review', err);
if (msg) { msg.textContent = err.message || 'Delete failed.'; msg.classList.add('err'); }
} finally {
reviewsState.submitting = false;
@@ -4814,7 +4864,7 @@ async function toggleBookmark() {
$('d-bookmark').classList.toggle('on', detailState.bookmarked);
$('d-bookmark').textContent = detailState.bookmarked ? '★' : '☆';
} catch (err) {
- console.error('[marketplace] bookmark', err);
+ log.error('[marketplace] bookmark', err);
}
}
@@ -4909,18 +4959,18 @@ function bindEvents() {
if (e.target.matches('.purchase-btn')) {
const skillName = e.target.dataset.skillName;
const agentId = e.target.dataset.agentId;
- if (agentId && skillName) openPurchaseFlow(agentId, skillName).catch((err) => console.error('[marketplace] purchase flow', err));
+ if (agentId && skillName) openPurchaseFlow(agentId, skillName).catch((err) => log.error('[marketplace] purchase flow', err));
}
if (e.target.matches('.trial-btn')) {
const skillName = e.target.dataset.skillName;
const agentId = e.target.dataset.agentId;
- if (agentId && skillName) openTrialFlow(agentId, skillName, e.target).catch((err) => console.error('[marketplace] trial flow', err));
+ if (agentId && skillName) openTrialFlow(agentId, skillName, e.target).catch((err) => log.error('[marketplace] trial flow', err));
}
if (e.target.matches('.time-pass-btn')) {
const skillName = e.target.dataset.skillName;
const agentId = e.target.dataset.agentId;
const duration = Number(e.target.dataset.duration);
- if (agentId && skillName && duration) openTimePassFlow(agentId, skillName, duration, e.target).catch((err) => console.error('[marketplace] time-pass flow', err));
+ if (agentId && skillName && duration) openTimePassFlow(agentId, skillName, duration, e.target).catch((err) => log.error('[marketplace] time-pass flow', err));
}
});
@@ -5754,7 +5804,7 @@ async function handleAssetPurchase() {
primaryLabel: target.label,
});
} catch (e) {
- console.error('[marketplace] asset purchase failed', e);
+ log.error('[marketplace] asset purchase failed', e);
// Differentiate "tx already sent, server lookup failing" from
// "tx never built". If we have a txid, the user already paid and
// must NOT be told to retry — surface the verify-again card.
@@ -5871,7 +5921,7 @@ async function handlePurchase() {
await onUnlocked();
} catch (e) {
- console.error('[marketplace] purchase failed', e);
+ log.error('[marketplace] purchase failed', e);
if (txid) {
renderPaymentVerifyAgain({
txid,
@@ -6416,7 +6466,10 @@ async function loadPlugins(reset = false) {
pluginState.items = [];
pluginState.cursor = null;
const grid = $('plugin-grid');
- if (grid) grid.innerHTML = '<div class="market-empty">Loading…</div>';
+ if (grid) {
+ grid.setAttribute('aria-busy', 'true');
+ grid.innerHTML = renderSkeletons(6);
+ }
}
try {
const url = new URL(PLUGIN_API + '/list', location.origin);
@@ -6432,7 +6485,7 @@ async function loadPlugins(reset = false) {
renderPluginGrid();
} catch {
const grid = $('plugin-grid');
- if (grid) grid.innerHTML = '<div class="market-empty">Failed to load plugins.</div>';
+ if (grid) grid.innerHTML = renderErrorState('plugins');
} finally {
pluginState.loading = false;
}
@@ -6574,7 +6627,7 @@ async function loadToolDetail(id) {
plugin = j?.data?.plugin || null;
}
} catch (err) {
- console.error('[marketplace] tool detail fetch', err);
+ log.error('[marketplace] tool detail fetch', err);
}
}
@@ -6709,7 +6762,7 @@ function renderToolDetail(p) {
shareBtn.classList.add('copied');
setTimeout(() => { shareBtn.textContent = original; shareBtn.classList.remove('copied'); }, 1800);
} catch (err) {
- console.error('[marketplace] tool share copy', err);
+ log.error('[marketplace] tool share copy', err);
}
};
}
diff --git a/src/memory/index.js b/src/memory/index.js
index 4d706884c..a06d0c8ab 100644
--- a/src/memory/index.js
+++ b/src/memory/index.js
@@ -13,6 +13,7 @@
// or typo'd config never breaks <agent-3d> boot.
import { encryptBlob, bytesToBase64, base64ToBytes } from './crypto.js';
+import { log } from '../shared/log.js';
const FRONTMATTER_RE = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/;
@@ -77,7 +78,7 @@ export class Memory {
throw new Error('encrypted-ipfs mode requires a deriveKey function');
return Memory._loadIPFS({ mode, namespace, manifestURI, fetchFn, deriveKey });
}
- console.warn(`[memory] unknown mode "${mode}"; falling back to "local"`);
+ log.warn(`[memory] unknown mode "${mode}"; falling back to "local"`);
return Memory._loadLocal(namespace);
}
@@ -277,7 +278,7 @@ export class Memory {
try {
localStorage.setItem(key, JSON.stringify(data));
} catch (e) {
- console.warn('[memory] persist failed', e);
+ log.warn('[memory] persist failed', e);
}
}
diff --git a/src/mocap-studio.js b/src/mocap-studio.js
index de23f62ab..85b50241b 100644
--- a/src/mocap-studio.js
+++ b/src/mocap-studio.js
@@ -12,6 +12,7 @@
import { Viewer } from './viewer.js';
import { FaceMocap } from './face-mocap.js';
import { IdleAnimation } from './idle-animation.js';
+import { log } from './shared/log.js';
const $ = (sel) => document.querySelector(sel);
@@ -442,7 +443,7 @@ function formatTime(seconds) {
}
function showErr(err) {
- console.error('[mocap-studio]', err);
+ log.error('[mocap-studio]', err);
alert(err?.message || String(err));
startCamBtn.disabled = false;
startCamBtn.textContent = 'Start camera';
diff --git a/src/nich-agent.js b/src/nich-agent.js
index cebc2fa50..72204577b 100644
--- a/src/nich-agent.js
+++ b/src/nich-agent.js
@@ -10,6 +10,7 @@
*/
import { ACTION_TYPES } from './agent-protocol.js';
+import { log } from './shared/log.js';
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
@@ -315,7 +316,7 @@ export class NichAgent {
return;
}
} catch (err) {
- console.warn('[NichAgent] Runtime error, falling back:', err.message);
+ log.warn('[NichAgent] Runtime error, falling back:', err.message);
}
}
@@ -432,7 +433,7 @@ export class NichAgent {
return { ok: false, reason: 'stream_incomplete' };
} catch (err) {
streamEl.remove();
- console.warn('[NichAgent] /api/chat failed:', err.message);
+ log.warn('[NichAgent] /api/chat failed:', err.message);
return { ok: false, reason: 'network' };
}
}
@@ -467,7 +468,7 @@ export class NichAgent {
try {
await this._executeAction(action);
} catch (err) {
- console.warn('[NichAgent] action failed:', action?.type, err.message);
+ log.warn('[NichAgent] action failed:', action?.type, err.message);
}
}
}
@@ -594,7 +595,7 @@ export class NichAgent {
}
break;
default:
- console.warn('[NichAgent] unknown action:', action.type);
+ log.warn('[NichAgent] unknown action:', action.type);
}
}
diff --git a/src/notifications.js b/src/notifications.js
new file mode 100644
index 000000000..ec93b7079
--- /dev/null
+++ b/src/notifications.js
@@ -0,0 +1,346 @@
+// Site-wide notifications inbox: unread badge in the nav + a popover panel.
+//
+// Loaded by public/nav.js after the nav HTML is injected (so #nav-notifications-btn
+// is guaranteed to exist). Auth-aware: silently skips polling when no session
+// hint is found; shows a sign-in prompt when the panel is opened while logged out.
+//
+// All API calls are fire-and-forget with credentials: 'include'. A 401 just
+// means the user is not signed in — the badge stays hidden.
+
+const POLL_INTERVAL = 30_000;
+const AUTH_HINT_KEY = '3dagent:auth-hint';
+
+const TYPE_ICON = {
+ skill_purchased: '💵',
+ skill_purchase_confirmed: '✅',
+ asset_purchased: '💵',
+ asset_purchase_confirmed: '✅',
+ asset_payment_mismatch: '⚠️',
+ skill_payment_mismatch: '⚠️',
+ referral_earned: '💰',
+ 'payment-earned': '💸',
+ sale: '🛒',
+ embed: '🔗',
+ remix: '🔄',
+ reply: '💬',
+};
+
+function notifLabel(n) {
+ const p = n.payload || {};
+ switch (n.type) {
+ case 'skill_purchased':
+ return `Payment received for skill "${p.skill || 'unknown'}"`;
+ case 'skill_purchase_confirmed':
+ return `Your purchase of "${p.skill || 'unknown'}" is confirmed`;
+ case 'asset_purchased':
+ return `Someone purchased your ${p.item_type || 'asset'}`;
+ case 'asset_purchase_confirmed':
+ return `Your asset purchase is confirmed`;
+ case 'asset_payment_mismatch':
+ case 'skill_payment_mismatch':
+ return `Payment mismatch — check your agent settings`;
+ case 'referral_earned':
+ return `Referral commission earned`;
+ case 'payment-earned':
+ return `Payment received${p.actor ? ` from ${p.actor}` : ''}`;
+ case 'sale':
+ return `Your agent made a sale`;
+ case 'embed':
+ return `Your creation was embedded`;
+ case 'remix':
+ return `Someone remixed your creation`;
+ case 'reply':
+ return `New reply on your agent`;
+ default:
+ return n.type.replace(/_/g, ' ');
+ }
+}
+
+function notifLink(n) {
+ const p = n.payload || {};
+ const raw = p.link
+ || (p.tx_signature ? `https://solscan.io/tx/${encodeURIComponent(p.tx_signature)}` : null)
+ || (p.agent_id ? `/agent/${encodeURIComponent(p.agent_id)}` : null);
+ return safeNavUrl(raw);
+}
+
+// Permit only same-origin relative paths or absolute http(s) URLs. Anything
+// else — javascript:, data:, vbscript:, or a protocol-relative //evil.com — is
+// dropped, so a hostile notification payload can't drive navigation into a
+// script execution or an off-site redirect.
+function safeNavUrl(raw) {
+ if (!raw || typeof raw !== 'string') return null;
+ const s = raw.trim();
+ if (s.startsWith('/') && !s.startsWith('//')) return s;
+ if (/^https?:\/\//i.test(s)) return s;
+ return null;
+}
+
+// HTML-escape untrusted notification text before it goes into innerHTML/attrs.
+// Notification payloads carry other users' actor/skill/item names, so every
+// interpolated value is treated as hostile.
+function escNotif(s) {
+ return String(s == null ? '' : s)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
+
+function relTime(dateStr) {
+ const diff = Date.now() - new Date(dateStr).getTime();
+ const m = Math.floor(diff / 60_000);
+ if (m < 1) return 'just now';
+ if (m < 60) return `${m}m ago`;
+ const h = Math.floor(m / 60);
+ if (h < 24) return `${h}h ago`;
+ return `${Math.floor(h / 24)}d ago`;
+}
+
+function isAuthed() {
+ try {
+ const raw = localStorage.getItem(AUTH_HINT_KEY);
+ return raw ? JSON.parse(raw)?.authed === true : false;
+ } catch { return false; }
+}
+
+class NotificationInbox {
+ constructor(btn) {
+ this._btn = btn;
+ this._badge = btn.querySelector('.nav-notif-badge');
+ this._panel = null;
+ this._notifications = [];
+ this._unread = 0;
+ this._open = false;
+ this._timer = null;
+
+ btn.addEventListener('click', (e) => { e.stopPropagation(); this._toggle(); });
+ document.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape' && this._open) this._close();
+ });
+ }
+
+ start() {
+ if (!isAuthed()) return;
+ this._poll();
+ this._schedulePoll();
+ document.addEventListener('visibilitychange', () => {
+ if (document.hidden) {
+ clearTimeout(this._timer);
+ } else {
+ this._poll();
+ this._schedulePoll();
+ }
+ });
+ }
+
+ _schedulePoll() {
+ clearTimeout(this._timer);
+ this._timer = setTimeout(() => {
+ this._poll();
+ this._schedulePoll();
+ }, POLL_INTERVAL);
+ }
+
+ async _poll() {
+ try {
+ const resp = await fetch('/api/notifications?limit=20', { credentials: 'include' });
+ if (!resp.ok) return;
+ const data = await resp.json();
+ this._notifications = data.notifications || [];
+ this._unread = data.unread_count || 0;
+ this._updateBadge();
+ if (this._open) this._renderBody();
+ } catch { /* network blip — silently ignore */ }
+ }
+
+ _updateBadge() {
+ const badge = this._badge;
+ if (!badge) return;
+ if (this._unread > 0) {
+ badge.textContent = this._unread > 99 ? '99+' : String(this._unread);
+ badge.removeAttribute('hidden');
+ } else {
+ badge.setAttribute('hidden', '');
+ }
+ this._btn.setAttribute(
+ 'aria-label',
+ this._unread > 0 ? `Notifications — ${this._unread} unread` : 'Notifications',
+ );
+ // aria-live on the badge for screen reader announcements
+ badge.setAttribute('aria-live', 'polite');
+ }
+
+ _toggle() {
+ this._open ? this._close() : this._openPanel();
+ }
+
+ _openPanel() {
+ this._open = true;
+ this._btn.setAttribute('aria-expanded', 'true');
+ if (!this._panel) this._panel = this._buildPanel();
+ document.body.appendChild(this._panel);
+ this._positionPanel();
+
+ if (isAuthed()) {
+ this._renderBody();
+ if (this._unread > 0) this._markAllRead();
+ } else {
+ this._renderLoggedOut();
+ }
+
+ // Close on outside click (deferred so the open click doesn't immediately close)
+ setTimeout(() => {
+ document.addEventListener('click', this._outsideHandler = (e) => {
+ if (!this._panel?.contains(e.target) && e.target !== this._btn) this._close();
+ }, { once: false });
+ }, 0);
+ }
+
+ _close() {
+ this._open = false;
+ this._btn.setAttribute('aria-expanded', 'false');
+ this._panel?.remove();
+ if (this._outsideHandler) {
+ document.removeEventListener('click', this._outsideHandler);
+ this._outsideHandler = null;
+ }
+ }
+
+ _buildPanel() {
+ const el = document.createElement('div');
+ el.className = 'notif-panel';
+ el.setAttribute('role', 'dialog');
+ el.setAttribute('aria-label', 'Notifications');
+ el.setAttribute('aria-modal', 'false');
+ el.innerHTML = `
+ <div class="notif-panel-head">
+ <span class="notif-panel-title">Notifications</span>
+ <button type="button" class="notif-mark-all btn-ghost" aria-label="Mark all as read">Mark all read</button>
+ </div>
+ <div class="notif-panel-body" aria-live="polite" aria-atomic="false"></div>
+ `;
+ el.querySelector('.notif-mark-all').addEventListener('click', (e) => {
+ e.stopPropagation();
+ this._markAllRead();
+ });
+ return el;
+ }
+
+ _positionPanel() {
+ if (!this._panel || !this._btn) return;
+ const rect = this._btn.getBoundingClientRect();
+ const W = 360;
+ let left = rect.right - W;
+ left = Math.max(8, Math.min(window.innerWidth - W - 8, left));
+ this._panel.style.top = `${rect.bottom + 6}px`;
+ this._panel.style.left = `${left}px`;
+ }
+
+ _renderBody() {
+ const body = this._panel?.querySelector('.notif-panel-body');
+ if (!body) return;
+
+ if (!this._notifications.length) {
+ body.innerHTML = `
+ <div class="notif-empty">
+ <div class="notif-empty-icon" aria-hidden="true">🔔</div>
+ <div class="notif-empty-title">No notifications yet</div>
+ <div class="notif-empty-sub">When your agent earns, sells, or gets remixed, you'll see it here.</div>
+ </div>
+ `;
+ return;
+ }
+
+ body.innerHTML = this._notifications.map((n) => {
+ const icon = TYPE_ICON[n.type] || '📣';
+ const msg = notifLabel(n);
+ const link = notifLink(n);
+ const time = relTime(n.created_at);
+ const unread = !n.read_at;
+ return `
+ <div class="notif-row${unread ? ' is-unread' : ''}"
+ data-id="${escNotif(n.id)}"
+ data-link="${escNotif(link || '')}"
+ tabindex="0"
+ role="button"
+ aria-label="${escNotif(msg)}${unread ? ' (unread)' : ''}">
+ <span class="notif-type-icon" aria-hidden="true">${icon}</span>
+ <div class="notif-row-body">
+ <div class="notif-row-msg">${escNotif(msg)}</div>
+ <div class="notif-row-time">${escNotif(time)}</div>
+ </div>
+ ${unread ? '<span class="notif-unread-dot" aria-hidden="true"></span>' : ''}
+ </div>
+ `;
+ }).join('');
+
+ body.querySelectorAll('.notif-row').forEach((row) => {
+ const activate = () => {
+ const id = row.dataset.id;
+ const link = row.dataset.link;
+ if (id && row.classList.contains('is-unread')) this._markOneRead(id, row);
+ if (link) {
+ if (link.startsWith('http')) {
+ window.open(link, '_blank', 'noopener');
+ } else {
+ window.location.href = link;
+ }
+ }
+ this._close();
+ };
+ row.addEventListener('click', activate);
+ row.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); activate(); } });
+ });
+ }
+
+ _renderLoggedOut() {
+ const body = this._panel?.querySelector('.notif-panel-body');
+ if (!body) return;
+ body.innerHTML = `
+ <div class="notif-empty">
+ <div class="notif-empty-icon" aria-hidden="true">🔔</div>
+ <div class="notif-empty-title">Sign in to see your notifications</div>
+ <div class="notif-empty-sub">Track payments, sales, and activity on your agents.</div>
+ <a href="/login" class="notif-signin-btn">Sign in →</a>
+ </div>
+ `;
+ }
+
+ _markOneRead(id, rowEl) {
+ const n = this._notifications.find((x) => x.id === id);
+ if (!n || n.read_at) return;
+ n.read_at = new Date().toISOString();
+ this._unread = Math.max(0, this._unread - 1);
+ this._updateBadge();
+ rowEl?.classList.remove('is-unread');
+ rowEl?.querySelector('.notif-unread-dot')?.remove();
+ fetch(`/api/notifications/${encodeURIComponent(id)}/read`, { method: 'POST', credentials: 'include' }).catch(() => {});
+ }
+
+ async _markAllRead() {
+ const markAllBtn = this._panel?.querySelector('.notif-mark-all');
+ if (markAllBtn) { markAllBtn.disabled = true; markAllBtn.textContent = 'Done ✓'; }
+ this._notifications.forEach((n) => { n.read_at = n.read_at || new Date().toISOString(); });
+ this._unread = 0;
+ this._updateBadge();
+ this._renderBody();
+ try {
+ await fetch('/api/notifications/read-all', { method: 'POST', credentials: 'include' });
+ } catch { /* fire-and-forget */ }
+ }
+}
+
+function mount() {
+ const btn = document.getElementById('nav-notifications-btn');
+ if (!btn) return;
+ const inbox = new NotificationInbox(btn);
+ inbox.start();
+ window.__notifInbox = inbox;
+}
+
+if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', mount);
+} else {
+ mount();
+}
diff --git a/src/payment-modal.js b/src/payment-modal.js
index 39f516886..8e7ff1693 100644
--- a/src/payment-modal.js
+++ b/src/payment-modal.js
@@ -9,6 +9,11 @@
* if (purchased) runtime.skillAccess = refreshedChecker;
*/
+import { formatUsdcEq, formatSolEq } from './shared/usd-price.js';
+import { buildReceiptHTML, buildReceiptText } from './shared/payment-receipt.js';
+import { showAddFunds } from './shared/add-funds.js';
+import { log } from './shared/log.js';
+
const USDC_DECIMALS = 6;
// Lazy-load Solana modules via bundled npm deps. Dynamic import keeps the
@@ -24,24 +29,25 @@ async function loadSolana() {
const STYLE = `
.pay-chip {
- background: rgba(167,139,250,.08);
- border: 1px solid rgba(167,139,250,.22);
+ background: rgba(255,255,255,.04);
+ border: 1px solid rgba(255,255,255,.11);
border-radius: 12px; padding: 12px 14px; margin: 2px 0;
}
.pay-chip-head { display: flex; align-items: center; gap: 6px; margin-bottom: 6px; }
.pay-chip-label { font-size: 12px; font-weight: 600; color: rgba(255,255,255,.55); text-transform: uppercase; letter-spacing: .06em; }
.pay-chip-skill { font-size: 13px; color: #ffffff; font-family: monospace; margin-bottom: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pay-chip-price { font-size: 15px; color: #34d399; font-weight: 700; margin-bottom: 10px; }
+.pay-chip-price .usd-eq { font-size: 12px; color: rgba(255,255,255,.45); font-weight: 400; margin-left: 5px; }
.pay-chip-actions { display: flex; gap: 8px; }
.pay-chip-btn {
flex: 1; padding: 8px 12px; border-radius: 8px; border: none;
font-size: 13px; font-weight: 600; cursor: pointer;
- background: linear-gradient(135deg, #7c3aed, #6d28d9); color: #fff;
+ background: rgba(255,255,255,0.12); color: #fff; border: 1px solid rgba(255,255,255,0.18);
transition: opacity .15s; letter-spacing: .02em;
}
.pay-chip-btn:hover:not(:disabled) { opacity: .85; }
.pay-chip-btn:disabled { opacity: .4; cursor: default; }
-.pay-chip-btn-pay { background: linear-gradient(135deg, #059669, #047857); }
+.pay-chip-btn-pay { background: linear-gradient(135deg, #059669, #047857); border: none; }
.pay-chip-btn-cancel { flex: 0 0 auto; background: rgba(255,255,255,.08); color: rgba(255,255,255,.45); }
.pay-chip-status { font-size: 12px; color: rgba(255,255,255,.45); margin-top: 7px; min-height: 15px; }
.pay-chip-status.err { color: #f87171; }
@@ -69,7 +75,7 @@ const STYLE = `
.skill-pay-close:hover { color: #fff; }
.skill-pay-skill {
font-size: 15px; font-weight: 600; color: #ffffff;
- background: rgba(167,139,250,.1); border-radius: 8px;
+ background: rgba(255,255,255,.05); border-radius: 8px;
padding: 8px 12px; margin: 0 0 8px; font-family: monospace;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
@@ -80,11 +86,12 @@ const STYLE = `
background: rgba(255,255,255,.05); border-radius: 10px;
}
.skill-pay-price strong { font-size: 20px; color: #34d399; }
+.skill-pay-price .usd-eq { font-size: 13px; color: rgba(255,255,255,.45); margin-left: 6px; }
.skill-pay-wallet-area { margin-bottom: 12px; }
.skill-pay-btn {
width: 100%; padding: 12px; border-radius: 10px; border: none;
font-size: 14px; font-weight: 600; cursor: pointer;
- background: linear-gradient(135deg, #7c3aed, #6d28d9); color: #fff;
+ background: rgba(255,255,255,0.12); color: #fff; border: 1px solid rgba(255,255,255,0.18);
transition: opacity .15s; letter-spacing: .02em;
}
.skill-pay-btn:hover:not(:disabled) { opacity: .88; }
@@ -145,7 +152,7 @@ export class SkillPaymentModal {
<p class="skill-pay-desc">This skill requires a one-time payment to unlock.</p>
<div class="skill-pay-price">
<span>Total</span>
- <strong></strong>
+ <strong><span class="skill-pay-amount"></span><span class="usd-eq" hidden></span></strong>
</div>
<div class="skill-pay-wallet-area">
<button class="skill-pay-btn" id="skill-pay-connect">Connect Phantom</button>
@@ -181,7 +188,14 @@ export class SkillPaymentModal {
const currency = price.chain === 'solana' ? 'USDC' : price.currency_mint?.slice(0, 8) || 'USDC';
this._el.querySelector('.skill-pay-skill').textContent = skill;
- this._el.querySelector('.skill-pay-price strong').textContent = `${amountUsdc} ${currency}`;
+ const amountEl = this._el.querySelector('.skill-pay-amount');
+ const usdEqEl = this._el.querySelector('.skill-pay-price .usd-eq');
+ amountEl.textContent = `${amountUsdc} ${currency}`;
+ usdEqEl.textContent = '';
+ usdEqEl.hidden = true;
+ const humanAmount = Number(price.amount || 0) / 10 ** USDC_DECIMALS;
+ const eqPromise = currency === 'USDC' ? Promise.resolve(formatUsdcEq(humanAmount)) : formatSolEq(humanAmount);
+ eqPromise.then((eq) => { if (eq) { usdEqEl.textContent = eq; usdEqEl.hidden = false; } });
this._el.querySelector('.skill-pay-open-link').href =
`/marketplace/agents/${this._agentId}?buy=${encodeURIComponent(skill)}`;
@@ -208,6 +222,40 @@ export class SkillPaymentModal {
el.className = 'skill-pay-status' + (kind ? ' ' + kind : '');
}
+ _setStatusHTML(html, kind = '') {
+ const el = this._el.querySelector('.skill-pay-status');
+ el.innerHTML = html;
+ el.className = 'skill-pay-status' + (kind ? ' ' + kind : '');
+ }
+
+ _showInsufficientFunds(walletAddress, requiredAtomic, currentAtomic, confirmBtn) {
+ const requiredUsdc = requiredAtomic ? (requiredAtomic / 1e6).toFixed(2) : null;
+ const currentUsdc = currentAtomic != null ? (currentAtomic / 1e6).toFixed(2) : null;
+ const needed = requiredUsdc
+ ? (currentUsdc != null ? `Need ${requiredUsdc} USDC, have ${currentUsdc}.` : `Need ${requiredUsdc} USDC.`)
+ : '';
+ this._setStatus(`Not enough USDC. ${needed}`, 'err');
+
+ const statusEl = this._el.querySelector('.skill-pay-status');
+ const addBtn = document.createElement('button');
+ addBtn.className = 'skill-pay-add-funds';
+ addBtn.textContent = 'Add funds →';
+ addBtn.addEventListener('click', async () => {
+ const result = await showAddFunds({
+ walletAddress: walletAddress || '',
+ requiredUsdc: requiredAtomic ? requiredAtomic / 1e6 : undefined,
+ container: this._root.host?.getRootNode?.()?.body || document.body,
+ });
+ if (result?.usdc) {
+ this._setStatus(`Balance updated: ${result.usdc.toFixed(2)} USDC — try again.`, 'ok');
+ if (confirmBtn) confirmBtn.disabled = false;
+ }
+ });
+ statusEl.appendChild(document.createTextNode(' '));
+ statusEl.appendChild(addBtn);
+ if (confirmBtn) confirmBtn.disabled = false;
+ }
+
_updateWalletArea() {
const area = this._el.querySelector('.skill-pay-wallet-area');
const confirm = this._el.querySelector('.skill-pay-confirm');
@@ -235,14 +283,23 @@ export class SkillPaymentModal {
await window.solana.connect();
this._wallet = window.solana;
} else {
- this._setStatus('Phantom not detected. Install Phantom wallet to purchase.', 'err');
- if (btn) { btn.textContent = 'Connect Phantom'; btn.disabled = false; }
+ this._setStatus('Phantom isn\'t installed. Get it at phantom.app — takes about a minute, then come back.', 'err');
+ if (btn) {
+ btn.textContent = 'Get Phantom';
+ btn.disabled = false;
+ btn.onclick = () => window.open('https://phantom.app/', '_blank', 'noopener');
+ }
return;
}
this._setStatus('');
this._updateWalletArea();
} catch (e) {
- this._setStatus(e.message || 'Connection failed', 'err');
+ log.warn('[three.ws] payment-modal connect error:', e);
+ if (/reject|denied|cancel|user.*declin/i.test(e.message || '')) {
+ this._setStatus('Connection cancelled — try again when you\'re ready.', 'err');
+ } else {
+ this._setStatus('Couldn\'t connect to your wallet — try again.', 'err');
+ }
if (btn) { btn.textContent = 'Connect Phantom'; btn.disabled = false; }
}
}
@@ -288,10 +345,11 @@ export class SkillPaymentModal {
// Step 2: Build + sign + send the SPL transfer
this._setStatus('Building transaction…');
+ const txStartMs = Date.now();
try {
const { web3, spl } = await loadSolana();
const { Connection, PublicKey, Transaction } = web3;
- const { getAssociatedTokenAddressSync, createTransferInstruction } = spl;
+ const { getAssociatedTokenAddressSync, createTransferInstruction, getAccount } = spl;
if (!this._connection) {
const rpc = window.__solanaRpc || `${window.location.origin}/api/solana-rpc`;
@@ -309,6 +367,19 @@ export class SkillPaymentModal {
const fromAta = getAssociatedTokenAddressSync(mintKey, payerKey);
const toAta = getAssociatedTokenAddressSync(mintKey, recipientKey);
+ // Pre-flight balance check: surface "Add funds" before wallet prompt
+ try {
+ const ataInfo = await getAccount(this._connection, fromAta, 'confirmed');
+ const balance = BigInt(ataInfo.amount);
+ const required = BigInt(purchase.amount);
+ if (balance < required) {
+ this._showInsufficientFunds(payerKey.toBase58(), Number(required), Number(balance), confirm);
+ return;
+ }
+ } catch {
+ // ATA may not exist yet — let sendTransaction surface the real error
+ }
+
const ix = createTransferInstruction(fromAta, toAta, payerKey, BigInt(purchase.amount));
ix.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });
@@ -324,15 +395,39 @@ export class SkillPaymentModal {
this._setStatus('Verifying with server…');
const ok = await this._pollConfirm(purchase.reference);
- if (!ok) throw new Error('Server could not verify the transaction — contact support with tx: ' + txid);
+ if (!ok) {
+ log.warn('[three.ws] payment-modal: verification failed, tx:', txid);
+ throw new Error('verification_failed');
+ }
- this._setStatus('✓ Skill unlocked!', 'ok');
- await delay(1200);
+ const receiptHtml = buildReceiptHTML({
+ usdcAtomic: purchase.amount,
+ recipientLabel: 'creator',
+ elapsedMs: Date.now() - txStartMs,
+ explorerUrl: `https://solscan.io/tx/${txid}`,
+ signature: txid,
+ });
+ this._setStatusHTML(receiptHtml, 'ok');
+ await delay(1800);
this.hide();
this._resolve?.(true);
this._resolve = null;
} catch (e) {
- this._setStatus(e.message || 'Purchase failed', 'err');
+ log.warn('[three.ws] payment-modal purchase error:', e);
+ const msg = e.message || '';
+ const payerAddr = (this._wallet?.publicKey || window.solana?.publicKey)?.toBase58?.() || null;
+ if (/reject|denied|cancel|user.*declin/i.test(msg)) {
+ this._setStatus('Transaction cancelled — try again whenever you\'re ready.', 'err');
+ } else if (msg === 'verification_failed') {
+ this._setStatus('Payment may have gone through but couldn\'t be verified. Contact support if funds were deducted.', 'err');
+ } else if (/insufficient|balance|funds/i.test(msg)) {
+ this._showInsufficientFunds(payerAddr, purchase?.amount, null, confirm);
+ return;
+ } else if (/network|fetch|econnrefused/i.test(msg)) {
+ this._setStatus('Connection problem — check your internet and try again.', 'err');
+ } else {
+ this._setStatus('Purchase didn\'t go through — try again.', 'err');
+ }
confirm.disabled = false;
}
}
@@ -394,12 +489,16 @@ export class PaymentChip {
<span class="pay-chip-label">Payment required</span>
</div>
<div class="pay-chip-skill">${skill}</div>
- <div class="pay-chip-price">${amountUsdc} ${currency}</div>
+ <div class="pay-chip-price">${amountUsdc} ${currency}<span class="usd-eq" hidden></span></div>
<div class="pay-chip-actions"></div>
<div class="pay-chip-status"></div>
</div>
</div>
`;
+ const chipUsdEq = wrapper.querySelector('.pay-chip-price .usd-eq');
+ const humanAmountChip = Number(price.amount || 0) / 10 ** USDC_DECIMALS;
+ const chipEqPromise = currency === 'USDC' ? Promise.resolve(formatUsdcEq(humanAmountChip)) : formatSolEq(humanAmountChip);
+ chipEqPromise.then((eq) => { if (eq) { chipUsdEq.textContent = eq; chipUsdEq.hidden = false; } });
const setStatus = (msg, kind = '') => {
const el = wrapper.querySelector('.pay-chip-status');
@@ -440,10 +539,20 @@ export class PaymentChip {
setStatus('');
updateActions();
} else {
- setStatus('Phantom not detected. Install Phantom to pay.', 'err');
+ setStatus('Phantom isn\'t installed. Get it at phantom.app — takes about a minute.', 'err');
+ const connectBtn = wrapper.querySelector('.pay-chip-btn-connect');
+ if (connectBtn) {
+ connectBtn.textContent = 'Get Phantom';
+ connectBtn.onclick = () => window.open('https://phantom.app/', '_blank', 'noopener');
+ }
}
} catch (e) {
- setStatus(e.message || 'Connection failed', 'err');
+ log.warn('[three.ws] payment-chip connect error:', e);
+ if (/reject|denied|cancel|user.*declin/i.test(e.message || '')) {
+ setStatus('Connection cancelled — try again when you\'re ready.', 'err');
+ } else {
+ setStatus('Couldn\'t connect to your wallet — try again.', 'err');
+ }
}
};
@@ -476,10 +585,41 @@ export class PaymentChip {
}
setStatus('Building transaction…');
+ const chipTxStart = Date.now();
+ const chipPayerAddr = (this._wallet?.publicKey || window.solana?.publicKey)?.toBase58?.() || '';
+
+ const showChipAddFunds = (requiredAtomic, currentAtomic) => {
+ const requiredUsdc = requiredAtomic ? (requiredAtomic / 1e6).toFixed(2) : null;
+ const currentUsdc = currentAtomic != null ? (currentAtomic / 1e6).toFixed(2) : null;
+ const needed = requiredUsdc
+ ? (currentUsdc != null ? `Need ${requiredUsdc} USDC, have ${currentUsdc}.` : `Need ${requiredUsdc} USDC.`)
+ : '';
+ setStatus(`Not enough USDC. ${needed}`, 'err');
+
+ // Inject "Add funds" button after the status text
+ const statusEl = wrapper.querySelector('.pay-chip-status');
+ const btn = document.createElement('button');
+ btn.className = 'pay-chip-add-funds';
+ btn.textContent = 'Add funds →';
+ btn.addEventListener('click', async () => {
+ const result = await showAddFunds({
+ walletAddress: chipPayerAddr,
+ requiredUsdc: requiredAtomic ? requiredAtomic / 1e6 : undefined,
+ });
+ if (result?.usdc) {
+ setStatus(`Balance updated: ${result.usdc.toFixed(2)} USDC — try again.`, 'ok');
+ if (payBtn) payBtn.disabled = false;
+ }
+ });
+ statusEl.appendChild(document.createTextNode(' '));
+ statusEl.appendChild(btn);
+ if (payBtn) payBtn.disabled = false;
+ };
+
try {
const { web3, spl } = await loadSolana();
const { Connection, PublicKey, Transaction } = web3;
- const { getAssociatedTokenAddressSync, createTransferInstruction } = spl;
+ const { getAssociatedTokenAddressSync, createTransferInstruction, getAccount } = spl;
if (!this._connection) {
const rpc = window.__solanaRpc || `${window.location.origin}/api/solana-rpc`;
@@ -497,6 +637,17 @@ export class PaymentChip {
const fromAta = getAssociatedTokenAddressSync(mintKey, payerKey);
const toAta = getAssociatedTokenAddressSync(mintKey, recipientKey);
+ // Pre-flight balance check before showing the wallet prompt
+ try {
+ const ataInfo = await getAccount(this._connection, fromAta, 'confirmed');
+ if (BigInt(ataInfo.amount) < BigInt(purch.amount)) {
+ showChipAddFunds(purch.amount, Number(ataInfo.amount));
+ return;
+ }
+ } catch {
+ // ATA not yet created — proceed; sendTransaction will surface the error
+ }
+
const ix = createTransferInstruction(fromAta, toAta, payerKey, BigInt(purch.amount));
ix.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });
@@ -512,13 +663,40 @@ export class PaymentChip {
setStatus('Verifying…');
const ok = await this._pollConfirm(purch.reference);
- if (!ok) throw new Error('Verification failed — contact support. tx: ' + txid);
+ if (!ok) {
+ log.warn('[three.ws] payment-chip: verification failed, tx:', txid);
+ throw new Error('verification_failed');
+ }
- setStatus('Unlocked!', 'ok');
- await delay(900);
+ const chipReceiptHtml = buildReceiptHTML({
+ usdcAtomic: purch.amount,
+ recipientLabel: 'creator',
+ elapsedMs: Date.now() - chipTxStart,
+ explorerUrl: `https://solscan.io/tx/${txid}`,
+ signature: txid,
+ });
+ const statusEl = wrapper.querySelector('.pay-chip-status');
+ if (statusEl) {
+ statusEl.innerHTML = chipReceiptHtml;
+ statusEl.className = 'pay-chip-status ok';
+ }
+ await delay(1400);
dismiss(true);
} catch (e) {
- setStatus(e.message || 'Purchase failed', 'err');
+ log.warn('[three.ws] payment-chip purchase error:', e);
+ const msg = e.message || '';
+ if (/reject|denied|cancel|user.*declin/i.test(msg)) {
+ setStatus('Transaction cancelled — try again whenever you\'re ready.', 'err');
+ } else if (msg === 'verification_failed') {
+ setStatus('Payment may have gone through but couldn\'t be verified. Contact support if funds were deducted.', 'err');
+ } else if (/insufficient|balance|funds/i.test(msg)) {
+ showChipAddFunds(purch?.amount, null);
+ return;
+ } else if (/network|fetch|econnrefused/i.test(msg)) {
+ setStatus('Connection problem — check your internet and try again.', 'err');
+ } else {
+ setStatus("Purchase didn't go through — try again.", 'err');
+ }
if (payBtn) payBtn.disabled = false;
}
};
diff --git a/src/permissions/manage-panel.js b/src/permissions/manage-panel.js
index 3332660c6..e512d073b 100644
--- a/src/permissions/manage-panel.js
+++ b/src/permissions/manage-panel.js
@@ -12,6 +12,7 @@ import { BrowserProvider, Contract } from 'ethers';
import { CHAIN_META, addressExplorerUrl, txExplorerUrl } from '../erc8004/chain-meta.js';
import { DELEGATION_MANAGER_DEPLOYMENTS, DELEGATION_MANAGER_ABI } from '../erc7710/abi.js';
import { GrantPermissionsModal } from './grant-modal.js';
+import { log } from '../shared/log.js';
// ── Public API ────────────────────────────────────────────────────────────────
@@ -135,7 +136,7 @@ class ManagePanel {
if (!this._agentWalletAddress) {
// Defensive: button shouldn't be visible without an agent wallet,
// but fail loud just in case.
- console.warn('[manage-panel] cannot grant: agent has no wallet address');
+ log.warn('[manage-panel] cannot grant: agent has no wallet address');
return;
}
@@ -320,7 +321,7 @@ class ManagePanel {
if (!data.ok) throw new Error(data.message || 'revoke mirror failed');
} catch (err) {
// Server mirror failure is non-fatal — on-chain is source of truth.
- console.warn('[manage-panel] server mirror failed:', err.message);
+ log.warn('[manage-panel] server mirror failed:', err.message);
}
// Flip card to revoked optimistically
diff --git a/src/pinning/index.js b/src/pinning/index.js
index 4867d371d..e02a0071e 100644
--- a/src/pinning/index.js
+++ b/src/pinning/index.js
@@ -11,6 +11,7 @@ import { Web3StoragePinner } from './web3-storage.js';
import { FilebasePinner } from './filebase.js';
import { PinataPinner } from './pinata.js';
import { MemoryPinner, NullDevPinner } from './null-dev.js';
+import { log } from '../shared/log.js';
const PROVIDERS = ['web3-storage', 'filebase', 'pinata', 'memory'];
@@ -72,7 +73,7 @@ export function getPinner() {
if (!_autoFallbackWarned) {
_autoFallbackWarned = true;
- console.warn(
+ log.warn(
'[pinning] No pinner configured — falling back to in-memory pinner. ' +
'CIDs are real but content is local-only. ' +
'Set window.__agent3dPinner or call setPinner() with a real provider for production.',
diff --git a/src/pose-library.js b/src/pose-library.js
index 34dfc4ad8..f055c5c27 100644
--- a/src/pose-library.js
+++ b/src/pose-library.js
@@ -7,6 +7,7 @@
// avatar helpers) so this module never reaches into the scene directly.
import { Quaternion } from 'three';
+import { log } from './shared/log.js';
const SESSION_KEY = 'pose:pendingDoc';
@@ -254,7 +255,7 @@ export class PoseLibrary {
});
}
} catch (err) {
- console.warn('[pose-library] thumbnail upload failed:', err.message);
+ log.warn('[pose-library] thumbnail upload failed:', err.message);
}
return saved;
}
diff --git a/src/pose-studio.js b/src/pose-studio.js
index 17b1f6247..cf68bb923 100644
--- a/src/pose-studio.js
+++ b/src/pose-studio.js
@@ -58,6 +58,7 @@ import {
DEFAULT_EASING,
} from './pose-animation.js';
import { PoseLibrary } from './pose-library.js';
+import { log } from './shared/log.js';
// ─── DOM helpers ────────────────────────────────────────────────────────
const $ = (sel) => document.querySelector(sel);
@@ -310,7 +311,7 @@ function boot() {
const canvas = $('#pose-canvas');
const hudStatus = $('#pose-status');
if (!canvas) {
- console.error('[pose] missing #pose-canvas');
+ log.error('[pose] missing #pose-canvas');
return;
}
diff --git a/src/reputation-ui.js b/src/reputation-ui.js
index 99e1a6742..273b3e9c5 100644
--- a/src/reputation-ui.js
+++ b/src/reputation-ui.js
@@ -10,6 +10,7 @@ import { JsonRpcProvider } from 'ethers';
import { getReputation, getRecentReviews, submitReputation, getTotalStake } from './erc8004/reputation.js';
import { ensureWallet } from './erc8004/agent-registry.js';
import { REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';
+import { log } from './shared/log.js';
const CHAIN_NAMES = {
1: 'Ethereum',
@@ -89,7 +90,7 @@ export class ReputationDashboard {
await this._fetchReputation();
this._render();
} catch (err) {
- console.error('[ReputationDashboard] load failed:', err);
+ log.error('[ReputationDashboard] load failed:', err);
this._renderError(err);
}
}
@@ -239,7 +240,7 @@ export class ReputationDashboard {
this._stopPolling();
}
} catch (err) {
- console.warn('[ReputationDashboard] poll failed:', err.message);
+ log.warn('[ReputationDashboard] poll failed:', err.message);
}
}
diff --git a/src/selfie-capture.js b/src/selfie-capture.js
index f7c4081e2..d2ca17555 100644
--- a/src/selfie-capture.js
+++ b/src/selfie-capture.js
@@ -14,6 +14,7 @@
*/
import { createQualitySession, preload, SLOT_PRESETS } from './face-quality.js';
+import { log } from './shared/log.js';
const REQUIRED_SLOT = 'frontal';
const OPTIONAL_SLOTS = /** @type {const} */ (['left', 'right']);
@@ -388,7 +389,7 @@ async function openCamera(slot) {
});
camVideo.srcObject = cam.stream;
} catch (err) {
- console.warn('[selfie] camera error:', err);
+ log.warn('[selfie] camera error:', err);
const denied = err?.name === 'NotAllowedError' || err?.name === 'PermissionDeniedError';
showCamError(
denied
@@ -429,7 +430,7 @@ async function startFaceQuality(slot) {
cam.qualitySession.start();
camOval?.setAttribute('hidden', '');
} catch (err) {
- console.warn('[selfie] face-quality init failed, falling back:', err);
+ log.warn('[selfie] face-quality init failed, falling back:', err);
setShutterEnabled(true);
}
}
diff --git a/src/selfie-pipeline.js b/src/selfie-pipeline.js
index ded1cd057..ccf5705a6 100644
--- a/src/selfie-pipeline.js
+++ b/src/selfie-pipeline.js
@@ -16,6 +16,7 @@
*/
import { detectFaceIdentity } from './avatar-face-capture.js';
+import { log } from './shared/log.js';
const SUBMIT_ENDPOINT = '/api/avatars/reconstruct';
const STATUS_ENDPOINT = '/api/avatars/regenerate-status';
@@ -34,7 +35,7 @@ document.addEventListener('selfie:submit', (event) => {
const ev = /** @type {CustomEvent} */ (event);
_building = false;
run(ev.detail).catch((err) => {
- console.error('[selfie-pipeline]', err);
+ log.error('[selfie-pipeline]', err);
if (err?.redirect) {
window.location.assign(err.redirect);
return;
@@ -74,7 +75,7 @@ document.addEventListener('selfie:submit', (event) => {
}));
}
}).catch((err) => {
- console.error('[selfie-pipeline] resume failed:', err);
+ log.error('[selfie-pipeline] resume failed:', err);
if (err?.redirect) {
window.location.assign(err.redirect);
return;
@@ -241,7 +242,7 @@ async function pollUntilDone(jobId) {
consecutiveErrors = 0;
} catch (err) {
consecutiveErrors += 1;
- console.warn('[selfie-pipeline] poll fetch failed (%d):', consecutiveErrors, err);
+ log.warn('[selfie-pipeline] poll fetch failed (%d):', consecutiveErrors, err);
if (consecutiveErrors >= 5) {
throw withMessage(
new Error('poll network failure'),
diff --git a/src/share-panel.css b/src/share-panel.css
index b5ac996f3..600450a55 100644
--- a/src/share-panel.css
+++ b/src/share-panel.css
@@ -10,14 +10,14 @@
}
.share-panel-modal {
- background: #1a1a1a;
+ background: var(--bg-1);
border: 1px solid #333;
border-radius: 12px;
width: min(560px, calc(100vw - 32px));
max-height: calc(100vh - 64px);
overflow-y: auto;
padding: 24px;
- color: #e8e8e8;
+ color: var(--ink);
font-family: system-ui, sans-serif;
font-size: 14px;
}
diff --git a/src/start.js b/src/start.js
index e08a8b0f3..bdf234f39 100644
--- a/src/start.js
+++ b/src/start.js
@@ -5,26 +5,39 @@
* State is persisted in sessionStorage so users can navigate away and back.
*/
+import { formatUsdcEq } from './shared/usd-price.js';
+import { TEMPLATES, TEMPLATES_BY_ID } from './templates.js';
+import { log } from './shared/log.js';
+
const STORAGE_KEY = 'wz:state';
const TOTAL_STEPS = 5;
// ── Personality presets ────────────────────────────────────────────────────
const PRESETS = {
- crypto: {
- bio: 'A crypto-savvy assistant that monitors Solana token launches, tracks whale movements on pump.fun, and helps users make informed trading decisions in real time.',
+ researcher: {
+ bio: 'A sharp web researcher who digs into any topic, synthesizes sources, and delivers clear, well-organized insights on demand.',
+ },
+ support: {
+ bio: 'A calm, helpful customer support agent who answers questions thoroughly, resolves issues efficiently, and keeps users feeling heard.',
+ },
+ podcast: {
+ bio: 'A conversational podcast host with a knack for storytelling. Brainstorms episode ideas, drafts interview questions, and writes engaging show notes.',
},
artist: {
bio: 'A creative collaborator with a bold visual aesthetic. Helps brainstorm concepts, generate ideas, and develop artistic projects across any medium.',
},
+ assistant: {
+ bio: 'A helpful, honest assistant. Clear and concise answers. No filler. Gets things done.',
+ },
+ crypto: {
+ bio: 'A crypto-savvy assistant that monitors Solana token launches, tracks whale movements on pump.fun, and helps users make informed trading decisions in real time.',
+ },
community: {
bio: 'An engaging community manager who greets members, answers questions, moderates discussions, and keeps the community thriving 24/7.',
},
defi: {
- bio: 'A DeFi expert fluent in liquidity pools, yield strategies, on-chain analytics, and protocol mechanics across Solana and EVM chains.',
- },
- assistant: {
- bio: 'A helpful, honest assistant. Clear and concise answers. No filler. Gets things done.',
+ bio: 'A DeFi expert fluent in liquidity pools, yield strategies, blockchain analytics, and protocol mechanics across Solana and EVM networks.',
},
};
@@ -41,6 +54,8 @@ const SKILL_MAP = {
web: ['web-search'],
};
+const CRYPTO_SKILLS = new Set(['pumpfun', 'solana', 'x402']);
+
// ── State ─────────────────────────────────────────────────────────────────
function loadState() {
@@ -75,12 +90,14 @@ function initState() {
description: '',
model: 'claude-sonnet-4-5',
enabledSkills: ['memory', 'think'],
+ cryptoMode: false,
price: '',
wallet: '',
deployed: false,
embedCode: '',
liveUrl: '',
};
+ if (base.cryptoMode === undefined) base.cryptoMode = false;
if (avatarId) {
base.avatarId = avatarId;
@@ -98,6 +115,90 @@ function initState() {
return base;
}
+// ── Templates gallery ─────────────────────────────────────────────────────
+
+const templatesScreen = document.getElementById('templates-screen');
+const wizardEl = document.getElementById('wizard');
+
+function showWizard() {
+ if (templatesScreen) {
+ templatesScreen.classList.add('tpl-exit');
+ setTimeout(() => {
+ templatesScreen.classList.add('tpl-hidden');
+ templatesScreen.classList.remove('tpl-exit');
+ }, 200);
+ }
+ if (wizardEl) wizardEl.classList.remove('wz-offstage');
+}
+
+function applyTemplate(tpl) {
+ state.description = tpl.bio;
+ state.enabledSkills = [...tpl.skills];
+ if (tpl.model) state.model = tpl.model;
+ state.cryptoMode = Boolean(tpl.cryptoMode);
+ // Jump to step 2 (Name & Brain) so the user immediately sees the prefilled persona
+ state.step = 2;
+ saveState(state);
+ showWizard();
+ renderStep();
+}
+
+function renderTemplateCard(tpl) {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'tpl-card';
+ btn.setAttribute('role', 'listitem');
+ btn.setAttribute('aria-label', `Use template: ${tpl.name}`);
+ btn.dataset.templateId = tpl.id;
+
+ btn.innerHTML = `
+ <span class="tpl-card-icon" aria-hidden="true">${tpl.icon}</span>
+ <div class="tpl-card-name">${tpl.name}</div>
+ <div class="tpl-card-tagline">${tpl.tagline}</div>
+ <div class="tpl-card-cta" aria-hidden="true">Use template <span>→</span></div>
+ ${tpl.cryptoMode ? '<span class="tpl-card-badge">Crypto</span>' : ''}
+ `;
+
+ btn.addEventListener('click', () => applyTemplate(tpl));
+ return btn;
+}
+
+function initTemplateGallery() {
+ if (!templatesScreen) return false;
+
+ const url = new URL(location.href);
+ const tplParam = url.searchParams.get('template');
+ const hasSavedState = Boolean(loadState());
+
+ // If a specific template is requested via ?template=id, apply it immediately.
+ // applyTemplate() calls renderStep() — return true so caller skips its own call.
+ if (tplParam && TEMPLATES_BY_ID[tplParam]) {
+ applyTemplate(TEMPLATES_BY_ID[tplParam]);
+ return true;
+ }
+
+ // If there's an in-progress wizard session, skip the gallery and let caller renderStep.
+ if (hasSavedState) {
+ showWizard();
+ return false;
+ }
+
+ // Show the gallery — renderStep still runs so wizard state is primed behind the overlay.
+ templatesScreen.classList.remove('tpl-hidden');
+
+ const grid = document.getElementById('tpl-grid');
+ if (grid) {
+ TEMPLATES.forEach((tpl) => grid.appendChild(renderTemplateCard(tpl)));
+ }
+
+ const blankBtn = document.getElementById('btn-blank-start');
+ if (blankBtn) {
+ blankBtn.addEventListener('click', () => showWizard());
+ }
+
+ return false;
+}
+
// ── CSRF helper ───────────────────────────────────────────────────────────
let _csrf = null;
@@ -147,6 +248,46 @@ const dots = Array.from(document.querySelectorAll('.wz-dot'));
let state = initState();
+// ── Crypto mode helpers ───────────────────────────────────────────────────
+
+function hasCryptoSkills() {
+ return state.enabledSkills.some(s => CRYPTO_SKILLS.has(s));
+}
+
+function updateCryptoUI() {
+ const on = state.cryptoMode;
+
+ const toggleBtn = $('crypto-toggle');
+ if (toggleBtn) toggleBtn.setAttribute('aria-expanded', String(on));
+
+ const personalitySection = $('crypto-personality-section');
+ if (personalitySection) personalitySection.hidden = !on;
+
+ const skillsSection = $('crypto-skills-section');
+ if (skillsSection) skillsSection.hidden = !on;
+
+ const revealBtn = $('crypto-skills-reveal');
+ if (revealBtn) revealBtn.hidden = on;
+}
+
+function setCryptoMode(on) {
+ state.cryptoMode = on;
+ if (!on) {
+ state.enabledSkills = state.enabledSkills.filter(s => !CRYPTO_SKILLS.has(s));
+ document.querySelectorAll('[data-skill]').forEach((card) => {
+ if (CRYPTO_SKILLS.has(card.dataset.skill)) {
+ card.classList.remove('active');
+ card.setAttribute('aria-pressed', 'false');
+ const check = card.querySelector('.wz-skill-check');
+ if (check) check.textContent = '';
+ }
+ });
+ }
+ updateCryptoUI();
+ if (state.step === 5) renderStep5();
+ saveState(state);
+}
+
// ── Render current step ───────────────────────────────────────────────────
function renderStep() {
@@ -165,12 +306,11 @@ function renderStep() {
});
$('btn-back').hidden = state.step <= 1;
- $('btn-skip-step').hidden = state.step !== 1 && state.step !== 5;
$('btn-next').hidden = state.step === 4 && !state.deployed;
const nextBtn = $('btn-next');
if (state.step === 5) {
- nextBtn.textContent = 'Go to dashboard';
+ nextBtn.textContent = hasCryptoSkills() ? 'Save & finish' : 'Go to dashboard';
} else if (state.step === 4) {
nextBtn.textContent = 'Continue';
nextBtn.hidden = !state.deployed;
@@ -178,12 +318,16 @@ function renderStep() {
nextBtn.textContent = state.step === 3 ? 'Continue to deploy' : 'Continue';
}
+ // Skip button: show on step 1 always; on step 5 only when crypto skills selected (skip wallet setup)
+ $('btn-skip-step').hidden = state.step !== 1 && !(state.step === 5 && hasCryptoSkills());
+
// Step-specific renders
if (state.step === 1) renderStep1();
- if (state.step === 2) renderStep2();
- if (state.step === 3) renderStep3();
+ if (state.step === 2) { renderStep2(); updateCryptoUI(); }
+ if (state.step === 3) { renderStep3(); updateCryptoUI(); }
if (state.step === 4 && !state.deployed) startDeploy();
if (state.step === 4 && state.deployed) showDeploySuccess();
+ if (state.step === 5) renderStep5();
// Announce progress to screen readers
const aria = $('wz-progress');
@@ -228,12 +372,16 @@ function renderStep2() {
if (bioEl && state.description) bioEl.value = state.description;
document.querySelectorAll('[data-model]').forEach((btn) => {
- btn.classList.toggle('active', btn.dataset.model === state.model);
+ const on = btn.dataset.model === state.model;
+ btn.classList.toggle('active', on);
+ btn.setAttribute('aria-pressed', String(on));
});
document.querySelectorAll('[data-preset]').forEach((btn) => {
const preset = PRESETS[btn.dataset.preset];
- btn.classList.toggle('active', preset && preset.bio === state.description);
+ const on = Boolean(preset && preset.bio === state.description);
+ btn.classList.toggle('active', on);
+ btn.setAttribute('aria-pressed', String(on));
});
}
@@ -249,6 +397,22 @@ function renderStep3() {
});
}
+// ── Step 5: Conditional earn/skip ─────────────────────────────────────────
+
+function renderStep5() {
+ const hasCrypto = hasCryptoSkills();
+ const skipPanel = $('step5-skip');
+ const earnPanel = $('step5-earn');
+ if (skipPanel) skipPanel.hidden = hasCrypto;
+ if (earnPanel) earnPanel.hidden = !hasCrypto;
+
+ const skipBtn = $('btn-skip-step');
+ if (skipBtn) skipBtn.hidden = !hasCrypto;
+
+ const nextBtn = $('btn-next');
+ if (nextBtn) nextBtn.textContent = hasCrypto ? 'Save & finish' : 'Go to dashboard';
+}
+
// ── Step 4: Deploy ─────────────────────────────────────────────────────────
async function startDeploy() {
@@ -303,13 +467,10 @@ async function startDeploy() {
state.deployed = true;
saveState(state);
- // Small pause so the "Building…" label is visible
- await new Promise((r) => setTimeout(r, 400));
-
showDeploySuccess();
} catch (err) {
- console.error('[wizard/deploy]', err);
+ log.error('[wizard/deploy]', err);
$('deploy-label').textContent = err.message || 'Deployment failed. Please try again.';
$('deploy-label').style.color = '#f87171';
const spinner = document.querySelector('.wz-deploy-spinner');
@@ -408,10 +569,11 @@ async function goNext() {
if (!validateStep()) return;
if (state.step === 5) {
- // Save earn settings and go to dashboard
$('btn-next').disabled = true;
$('btn-next').textContent = 'Saving…';
- await saveEarnSettings().catch(() => {});
+ if (hasCryptoSkills()) {
+ await saveEarnSettings().catch(() => {});
+ }
sessionStorage.removeItem(STORAGE_KEY);
location.href = '/dashboard?welcome=1';
return;
@@ -514,7 +676,7 @@ $('glb-file-input').addEventListener('change', async (e) => {
renderStep1();
} catch (err) {
- console.error('[wizard/upload]', err);
+ log.error('[wizard/upload]', err);
showError(err.message || 'Upload failed. Please try again.');
} finally {
btn.querySelector('.wz-avatar-card-label').textContent = origLabel;
@@ -532,8 +694,10 @@ $('agent-name').addEventListener('input', () => {
$('agent-bio').addEventListener('input', () => {
state.description = $('agent-bio').value;
- // Deselect preset chips if manually edited
- document.querySelectorAll('[data-preset]').forEach((btn) => btn.classList.remove('active'));
+ document.querySelectorAll('[data-preset]').forEach((btn) => {
+ btn.classList.remove('active');
+ btn.setAttribute('aria-pressed', 'false');
+ });
saveState(state);
});
@@ -543,16 +707,24 @@ document.querySelectorAll('[data-preset]').forEach((btn) => {
if (!preset) return;
$('agent-bio').value = preset.bio;
state.description = preset.bio;
- document.querySelectorAll('[data-preset]').forEach((b) => b.classList.remove('active'));
+ document.querySelectorAll('[data-preset]').forEach((b) => {
+ b.classList.remove('active');
+ b.setAttribute('aria-pressed', 'false');
+ });
btn.classList.add('active');
+ btn.setAttribute('aria-pressed', 'true');
saveState(state);
});
});
document.querySelectorAll('[data-model]').forEach((btn) => {
btn.addEventListener('click', () => {
- document.querySelectorAll('[data-model]').forEach((b) => b.classList.remove('active'));
+ document.querySelectorAll('[data-model]').forEach((b) => {
+ b.classList.remove('active');
+ b.setAttribute('aria-pressed', 'false');
+ });
btn.classList.add('active');
+ btn.setAttribute('aria-pressed', 'true');
state.model = btn.dataset.model;
saveState(state);
});
@@ -596,6 +768,23 @@ $('copy-embed').addEventListener('click', () => {
});
});
+// ── Crypto toggle event bindings ──────────────────────────────────────────
+
+const cryptoToggleBtn = $('crypto-toggle');
+if (cryptoToggleBtn) {
+ cryptoToggleBtn.addEventListener('click', () => setCryptoMode(!state.cryptoMode));
+}
+
+const cryptoSkillsRevealBtn = $('crypto-skills-reveal');
+if (cryptoSkillsRevealBtn) {
+ cryptoSkillsRevealBtn.addEventListener('click', () => setCryptoMode(true));
+}
+
+const cryptoSkillsHideBtn = $('crypto-skills-hide');
+if (cryptoSkillsHideBtn) {
+ cryptoSkillsHideBtn.addEventListener('click', () => setCryptoMode(false));
+}
+
// ── Step 5: Wallet chain detection ────────────────────────────────────────
$('earn-wallet').addEventListener('input', () => {
@@ -603,6 +792,25 @@ $('earn-wallet').addEventListener('input', () => {
$('earn-chain').textContent = detectChain(addr);
});
+// ── Step 5: Earn price USD equivalent ────────────────────────────────────
+// USDC is pegged 1:1 to USD — show "≈ $X.XXX per call" so users know
+// exactly what they're charging in dollars.
+
+function updateEarnPriceHint() {
+ const hint = $('earn-price-usd-hint');
+ if (!hint) return;
+ const raw = parseFloat($('earn-price')?.value);
+ if (!raw || raw <= 0) { hint.textContent = ''; return; }
+ const eq = formatUsdcEq(raw);
+ hint.textContent = eq ? `${eq} per call` : '';
+}
+
+$('earn-price').addEventListener('input', updateEarnPriceHint);
+updateEarnPriceHint();
+
// ── Initial render ─────────────────────────────────────────────────────────
-renderStep();
+// initTemplateGallery may call renderStep() itself (template apply or ?template= param).
+// Only call renderStep() here if the gallery didn't already do it.
+const _galleryRendered = initTemplateGallery();
+if (!_galleryRendered) renderStep();
diff --git a/src/templates.js b/src/templates.js
new file mode 100644
index 000000000..21815ee10
--- /dev/null
+++ b/src/templates.js
@@ -0,0 +1,95 @@
+/**
+ * Agent template definitions — each template is a rich preset that pre-fills
+ * the create wizard with a persona (bio), skill set, AI model, and a crypto
+ * routing flag.
+ *
+ * "look" is expressed as an emoji icon for the gallery card; avatar selection
+ * is still user-driven in Step 1. The crypto flag tells the wizard whether
+ * to enable the conditional-crypto earn flow (Step 5 / C04 branch).
+ */
+
+export const TEMPLATES = [
+ {
+ id: 'assistant',
+ name: 'Personal Assistant',
+ tagline: 'Clear answers, no filler — gets things done',
+ bio: 'A helpful, honest assistant. Clear and concise answers. No filler. Gets things done.',
+ skills: ['memory', 'think', 'web'],
+ model: 'claude-sonnet-4-5',
+ icon: '✅',
+ cryptoMode: false,
+ },
+ {
+ id: 'researcher',
+ name: 'Web Researcher',
+ tagline: 'Digs into any topic and delivers sourced insights',
+ bio: 'A sharp web researcher who digs into any topic, synthesizes sources, and delivers clear, well-organized insights on demand.',
+ skills: ['memory', 'think', 'web'],
+ model: 'claude-sonnet-4-5',
+ icon: '🔍',
+ cryptoMode: false,
+ },
+ {
+ id: 'support',
+ name: 'Customer Support',
+ tagline: 'Answers questions, resolves issues, keeps users happy',
+ bio: 'A calm, helpful customer support agent who answers questions thoroughly, resolves issues efficiently, and keeps users feeling heard.',
+ skills: ['memory', 'think'],
+ model: 'claude-sonnet-4-5',
+ icon: '💬',
+ cryptoMode: false,
+ },
+ {
+ id: 'tutor',
+ name: 'Tutor',
+ tagline: 'Explains complex topics in plain, engaging language',
+ bio: 'A patient, knowledgeable tutor who breaks down complex subjects into clear explanations, adapts to any skill level, and uses examples to make ideas stick.',
+ skills: ['memory', 'think', 'web'],
+ model: 'claude-sonnet-4-5',
+ icon: '📚',
+ cryptoMode: false,
+ },
+ {
+ id: 'artist',
+ name: 'Creative Collaborator',
+ tagline: 'Brainstorms concepts, develops ideas across any medium',
+ bio: 'A creative collaborator with a bold visual aesthetic. Helps brainstorm concepts, generate ideas, and develop artistic projects across any medium.',
+ skills: ['memory', 'think'],
+ model: 'claude-sonnet-4-5',
+ icon: '🎨',
+ cryptoMode: false,
+ },
+ {
+ id: 'podcast',
+ name: 'Podcast Host',
+ tagline: 'Episode ideas, interview questions, polished show notes',
+ bio: 'A conversational podcast host with a knack for storytelling. Brainstorms episode ideas, drafts interview questions, and writes engaging show notes.',
+ skills: ['memory', 'think'],
+ model: 'claude-sonnet-4-5',
+ icon: '🎙️',
+ cryptoMode: false,
+ },
+ {
+ id: 'crypto',
+ name: 'Crypto Advisor',
+ tagline: 'Monitors Solana launches, tracks whale moves in real time',
+ bio: 'A crypto-savvy assistant that monitors Solana token launches, tracks whale movements, and helps users make informed trading decisions in real time.',
+ skills: ['memory', 'think', 'pumpfun', 'solana'],
+ model: 'claude-sonnet-4-5',
+ icon: '◎',
+ cryptoMode: true,
+ },
+ {
+ id: 'defi',
+ name: 'DeFi Expert',
+ tagline: 'Liquidity pools, yield strategies, cross-chain analytics',
+ bio: 'A DeFi expert fluent in liquidity pools, yield strategies, blockchain analytics, and protocol mechanics across Solana and EVM networks.',
+ skills: ['memory', 'think', 'pumpfun', 'solana', 'x402'],
+ model: 'claude-sonnet-4-5',
+ icon: '💹',
+ cryptoMode: true,
+ },
+];
+
+/** Map from template id → template object for O(1) lookup. */
+export const TEMPLATES_BY_ID = Object.fromEntries(TEMPLATES.map((t) => [t.id, t]));
diff --git a/src/walk-companion.js b/src/walk-companion.js
index 4c9e755cd..1f43d90b7 100644
--- a/src/walk-companion.js
+++ b/src/walk-companion.js
@@ -38,6 +38,7 @@ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { AnimationManager } from './animation-manager.js';
import { getMeshoptDecoder } from './viewer/internal.js';
import { reserveWebGLContext, releaseWebGLContext } from './webgl-budget.js';
+import { log } from './shared/log.js';
// ── Config ──────────────────────────────────────────────────────────────────
const ENABLED_KEY = 'walk:companion:enabled';
@@ -313,7 +314,7 @@ class WalkCompanion {
try {
await this._buildScene();
} catch (err) {
- console.warn('[walk-companion] failed to load avatar:', err?.message || err);
+ log.warn('[walk-companion] failed to load avatar:', err?.message || err);
this._teardownScene();
this._showError();
return;
diff --git a/src/walk-embed-preview.js b/src/walk-embed-preview.js
index db77ee908..293147c86 100644
--- a/src/walk-embed-preview.js
+++ b/src/walk-embed-preview.js
@@ -29,6 +29,7 @@ import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import nipplejs from 'nipplejs';
import { AnimationManager } from './animation-manager.js';
import { reserveWebGLContext } from './webgl-budget.js';
+import { log } from './shared/log.js';
const AVATAR_URL = '/avatars/default.glb';
const ANIMATIONS_MANIFEST_URL = '/animations/manifest.json';
@@ -456,7 +457,7 @@ export function initWalkPreview(container) {
for (const entry of entries) {
if (entry.isIntersecting && !started) {
started = true;
- loadAvatar().catch((err) => console.warn('[walk-preview] load failed', err));
+ loadAvatar().catch((err) => log.warn('[walk-preview] load failed', err));
syncRunning();
observer.disconnect();
}
diff --git a/src/walk-embed.js b/src/walk-embed.js
index 9f575dc9b..6dd674244 100644
--- a/src/walk-embed.js
+++ b/src/walk-embed.js
@@ -37,6 +37,7 @@ import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import nipplejs from 'nipplejs';
import { AnimationManager } from './animation-manager.js';
+import { log } from './shared/log.js';
const AVATAR_URL_DEFAULT = '/avatars/default.glb';
@@ -659,7 +660,7 @@ loadAvatar()
requestAnimationFrame(tick);
})
.catch((err) => {
- console.error('[walk-embed] failed to load avatar:', err);
+ log.error('[walk-embed] failed to load avatar:', err);
if (statusEl) {
statusEl.textContent = `failed to load avatar: ${err?.message ?? err}`;
statusEl.classList.add('is-error');
diff --git a/src/walk-net.js b/src/walk-net.js
index 5c21af30d..3c136d33d 100644
--- a/src/walk-net.js
+++ b/src/walk-net.js
@@ -14,6 +14,7 @@
import { Client, getStateCallbacks } from 'colyseus.js';
import { WalkState } from '../multiplayer/src/schemas.js';
+import { log } from './shared/log.js';
const ROOM_NAME = 'walk_world';
const SEND_HZ = 15;
@@ -23,10 +24,14 @@ const YAW_EPSILON = 0.01; // rad
function defaultServerUrl() {
// Resolution priority:
- // 1. window.WALK_SERVER_URL (test override)
- // 2. <meta name="walk-server" content="...">
- // 3. Codespaces / Gitpod port-subdomain forwarding (-3000 → -2567)
- // 4. Same host on :2567 (dev convenience)
+ // 1. window.WALK_SERVER_URL (runtime / test override)
+ // 2. <meta name="walk-server" content> (per-page production config)
+ // 3. VITE_WALK_SERVER_URL (build-time production config)
+ // 4. Codespaces / Gitpod port-subdomain forwarding (-3000 → -2567)
+ // 5. Same host on :2567 (DEV ONLY convenience)
+ // In production with none of the above set we return '' so the caller stays
+ // in graceful offline mode — the public domain does not expose :2567, so a
+ // same-host fallback would only produce a doomed connect + reconnect storm.
if (typeof window !== 'undefined' && window.WALK_SERVER_URL) {
return window.WALK_SERVER_URL;
}
@@ -35,6 +40,10 @@ function defaultServerUrl() {
const v = meta?.getAttribute('content')?.trim();
if (v) return v;
}
+ try {
+ const envUrl = import.meta?.env?.VITE_WALK_SERVER_URL;
+ if (envUrl) return String(envUrl).trim().replace(/\/$/, '');
+ } catch (_) {}
if (typeof location !== 'undefined') {
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
const host = location.hostname;
@@ -43,9 +52,16 @@ function defaultServerUrl() {
// on -3000; the walk server is the same name on -2567.
const fwd = host.match(/^(.*)-(\d+)\.(app\.github\.dev|githubpreview\.dev|gitpod\.io)$/);
if (fwd) return `${proto}//${fwd[1]}-2567.${fwd[3]}`;
- return `${proto}//${host}:2567`;
+ // Same-host:2567 is a dev convenience only. In production the walk server
+ // is a separately-deployed Colyseus host addressed via the meta tag or
+ // VITE_WALK_SERVER_URL above; never assume it lives on the public domain.
+ let isProd = false;
+ try { isProd = import.meta?.env?.PROD === true; } catch (_) {}
+ const isLocalHost = host === 'localhost' || host === '127.0.0.1';
+ if (!isProd || isLocalHost) return `${proto}//${host}:2567`;
+ return '';
}
- return 'ws://localhost:2567';
+ return '';
}
export class WalkNet {
@@ -104,7 +120,7 @@ export class WalkNet {
_emit(event, ...args) {
for (const fn of this._handlers[event]) {
- try { fn(...args); } catch (e) { console.error(`[walk-net] ${event} handler threw:`, e); }
+ try { fn(...args); } catch (e) { log.error(`[walk-net] ${event} handler threw:`, e); }
}
}
@@ -131,6 +147,15 @@ export class WalkNet {
async connect() {
if (this._destroyed) return;
this._closeRoom();
+ // No multiplayer server resolved for this environment (e.g. production
+ // with no walk-server meta/env configured). Surface a distinct, honest
+ // 'unavailable' state — the page still works solo — instead of throwing
+ // in `new Client('')`, looping on a dead endpoint, or showing a
+ // "reconnecting…" pill that will never reconnect (no server exists).
+ if (!this.url) {
+ this._setStatus('unavailable');
+ return;
+ }
// Bump a generation token so a slower in-flight connect (e.g. a manual
// retry racing the auto-reconnect timer) can detect it's been superseded
// after its await resolves and discard the room it joined, rather than
@@ -188,12 +213,12 @@ export class WalkNet {
if (!this._destroyed && code !== 1000) this._scheduleReconnect();
});
this.room.onError((code, message) => {
- console.warn('[walk-net] room.onError', code, message);
+ log.warn('[walk-net] room.onError', code, message);
});
this._setStatus('online');
} catch (err) {
- console.warn('[walk-net] connect failed:', err?.message ?? err);
+ log.warn('[walk-net] connect failed:', err?.message ?? err);
this._setStatus('failed', err?.message ?? String(err));
// Single retry after ~3s — most failures here are "server not
// running yet" during local dev. After that we go offline until
diff --git a/src/walk.js b/src/walk.js
index 3be4bc792..82ae21333 100644
--- a/src/walk.js
+++ b/src/walk.js
@@ -51,6 +51,7 @@ import { getPresenceTicket, friendsClient } from './friends.js';
import { FriendsPanel } from './game/friends-panel.js';
import { PhysicsWorld } from './physics/physics-world.js';
import { createTerrain } from './game/terrain.js';
+import { log } from './shared/log.js';
const AVATAR_URL_DEFAULT = '/avatars/default.glb';
@@ -1077,11 +1078,15 @@ async function loadAvatar() {
setStatus('Ready — drag to look around');
buildEmoteTray();
- // Auto-hide help hints after 5 seconds.
+ // Auto-hide help hints after 5 seconds — fade first, then remove from layout
+ // so the transition in walk.html's #walk-help { transition: opacity } plays.
if (helpEl) {
helpAutoHideTimer = setTimeout(() => {
- helpEl.style.display = 'none';
- helpAutoHideTimer = null;
+ helpEl.style.opacity = '0';
+ helpAutoHideTimer = setTimeout(() => {
+ helpEl.style.display = 'none';
+ helpAutoHideTimer = null;
+ }, 400);
}, 5000);
}
}
@@ -1315,6 +1320,31 @@ const IS_TOUCH = (() => {
const CAMERA_SUPPORTED = !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
const AR_CTA_DISMISS_KEY = 'walk:ar-cta-dismissed';
+// ── AR button capability state ────────────────────────────────────────────
+// Run once at load time: if the camera API is absent the button is marked
+// disabled immediately so the user never encounters a dead click.
+// On supported devices the button stays active and any getUserMedia failure
+// (permission denied, no camera attached) is surfaced at click time by
+// enableAR() with a clear error message.
+(function initArButtonState() {
+ if (!arBtn) return;
+ if (CAMERA_SUPPORTED) return; // all good — leave the button as-is
+
+ // Camera API unavailable: mark the button as disabled and explain why.
+ arBtn.disabled = true;
+ arBtn.setAttribute('aria-disabled', 'true');
+ arBtn.title = 'AR requires a browser with camera access (try Chrome or Safari on a phone)';
+ const dot = arBtn.querySelector('.dot');
+ if (dot) dot.style.background = 'rgba(255,255,255,0.2)';
+ const label = arBtn.querySelector('[data-label]');
+ if (label) label.textContent = 'AR (unavailable)';
+ // Prevent the click handler from firing via the disabled attribute, and
+ // style it as inert so it doesn't look interactive.
+ arBtn.style.opacity = '0.4';
+ arBtn.style.cursor = 'not-allowed';
+ arBtn.style.pointerEvents = 'none';
+})();
+
function showArCta() {
if (!arCta) return;
if (arActive) return;
@@ -1459,7 +1489,7 @@ async function startRecording() {
} catch (err) {
// User cancelled or share failed — fall through to download.
if (err?.name !== 'AbortError') {
- console.warn('[walk] share failed, falling back to download:', err);
+ log.warn('[walk] share failed, falling back to download:', err);
} else {
setStatus('share cancelled');
return;
@@ -1480,7 +1510,7 @@ async function startRecording() {
};
recorder.onerror = (e) => {
- console.error('[walk] recorder error:', e);
+ log.error('[walk] recorder error:', e);
recording = false;
recordBtn?.setAttribute('data-recording', 'false');
recordStatus?.classList.remove('is-visible');
@@ -2038,7 +2068,7 @@ class RemotePlayer {
try {
templateScene = await loadRemoteAvatarTemplate(url);
} catch (err) {
- console.warn('[walk] remote avatar load failed, keeping stand-in:', url, err?.message ?? err);
+ log.warn('[walk] remote avatar load failed, keeping stand-in:', url, err?.message ?? err);
return;
}
if (token !== this._avatarLoadToken || !this.rig) return; // superseded or disposed
@@ -2176,7 +2206,9 @@ function setOnlineStatus(status) {
? 'offline — tap to retry'
: status === 'offline'
? 'reconnecting…'
- : 'solo';
+ : status === 'unavailable'
+ ? 'multiplayer unavailable'
+ : 'solo';
}
}
@@ -3127,7 +3159,7 @@ async function initWalkPhysics() {
} catch (err) {
// Solver failed to load — the legacy movement path keeps the scene fully
// playable, so degrade quietly rather than blocking the experience.
- console.warn('[walk] physics unavailable, using legacy movement:', err);
+ log.warn('[walk] physics unavailable, using legacy movement:', err);
physics = null;
physicsReady = false;
character = null;
@@ -3155,7 +3187,7 @@ loadAvatar()
setTimeout(showArCta, 900);
})
.catch((err) => {
- console.error('[walk] failed to load avatar:', err);
+ log.error('[walk] failed to load avatar:', err);
// Tear down the full-screen loading overlay so the error is readable and
// the scene (default ground/lighting) is visible behind the message.
dismissLoading();
@@ -3277,7 +3309,7 @@ if (import.meta.env?.DEV) {
setStatus('Avatar switched');
} catch (err) {
setStatus('Failed to load avatar', { error: true });
- console.error('[walk] avatar switch failed:', err);
+ log.error('[walk] avatar switch failed:', err);
}
togglePicker();
});
diff --git a/src/wallet-auth.js b/src/wallet-auth.js
index fb40233a6..777f1a0e6 100644
--- a/src/wallet-auth.js
+++ b/src/wallet-auth.js
@@ -1,5 +1,6 @@
import { ensureWallet } from './erc8004/agent-registry.js';
import { identifyUser, resetIdentity } from './analytics.js';
+import { resolveError } from './shared/error-messages.js';
// ─── Public API ─────────────────────────────────────────────────────────────
@@ -145,9 +146,9 @@ function _wireClickHandler(buttonEl) {
if (_busy) return;
if (!window.ethereum) {
- statusEl.style.display = 'inline';
- statusEl.textContent =
- 'No wallet detected — install a wallet extension (MetaMask, Coinbase Wallet, etc.) and refresh.';
+ // No wallet extension — route to the email sign-in path instead of dead-ending.
+ try { sessionStorage.setItem('login_redirect', location.href); } catch { /* ignore */ }
+ location.href = '/login?from=no-wallet';
return;
}
@@ -161,9 +162,51 @@ function _wireClickHandler(buttonEl) {
statusEl.textContent = 'Signed in — reloading…';
location.reload();
} catch (err) {
- statusEl.textContent = err.message || 'Sign-in failed.';
+ const entry = resolveError(err, 'wallet-auth sign-in');
+ _renderInlineError(statusEl, entry, {
+ retry: () => {
+ buttonEl.disabled = false;
+ _busy = false;
+ statusEl.style.display = 'none';
+ buttonEl.click();
+ },
+ });
buttonEl.disabled = false;
_busy = false;
}
});
}
+
+/**
+ * Render a compact inline error with action links/buttons into a status span.
+ *
+ * @param {HTMLElement} el
+ * @param {{ title: string, body: string, actions: Array }} entry
+ * @param {Record<string, () => void>} handlers
+ */
+function _renderInlineError(el, entry, handlers = {}) {
+ el.innerHTML = '';
+ el.setAttribute('role', 'alert');
+
+ const text = document.createTextNode(`${entry.title} — ${entry.body} `);
+ el.appendChild(text);
+
+ for (const action of (entry.actions || [])) {
+ if (action.href) {
+ const a = document.createElement('a');
+ a.href = action.href;
+ if (action.href.startsWith('http')) { a.target = '_blank'; a.rel = 'noopener noreferrer'; }
+ a.textContent = action.label;
+ a.style.cssText = 'margin-left:.4em;text-decoration:underline;cursor:pointer;';
+ el.appendChild(a);
+ } else if (action.onClick) {
+ const handler = handlers[action.onClick];
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.textContent = action.label;
+ btn.style.cssText = 'margin-left:.4em;background:none;border:none;padding:0;cursor:pointer;text-decoration:underline;font-size:inherit;color:inherit;';
+ if (handler) btn.addEventListener('click', handler);
+ el.appendChild(btn);
+ }
+ }
+}
diff --git a/src/wallet.js b/src/wallet.js
index ed0fa7df8..097595012 100644
--- a/src/wallet.js
+++ b/src/wallet.js
@@ -4,6 +4,7 @@
// window.solana that signs through the on-device Seed Vault. On every other
// platform the import is a no-op (it checks display-mode + UA + referrer).
import '../solana-mobile/src/index.js';
+import { log } from './shared/log.js';
let connectedWalletAddress = null;
let listenersBound = false;
@@ -45,7 +46,7 @@ async function onConnectWallet() {
connectedWalletAddress = res?.publicKey?.toString?.() || null;
updateWalletState(connectedWalletAddress);
} catch (err) {
- console.error('Wallet connection failed:', err);
+ log.error('Wallet connection failed:', err);
}
}
diff --git a/src/xr.js b/src/xr.js
index abdadf272..3039d4672 100644
--- a/src/xr.js
+++ b/src/xr.js
@@ -25,6 +25,7 @@ import { AnimationManager } from './animation-manager.js';
import { WebXRSession } from './ar/webxr.js';
import { canUseQuickLook } from './ar/quick-look.js';
import { canUseSceneViewer, openSceneViewer } from './ar/scene-viewer.js';
+import { log } from './shared/log.js';
// ── DOM ──────────────────────────────────────────────────────────────────────
@@ -458,7 +459,7 @@ window.addEventListener('resize', () => {
await loadAvatar();
} catch (err) {
setStatus('Failed to load avatar', 'error');
- console.error('[xr] avatar load failed:', err);
+ log.error('[xr] avatar load failed:', err);
}
if (loadingEl) loadingEl.hidden = true;