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: implement wallet connection handling and add route testing script

nirholas0a518d233da2
diff --git a/agent-home.html b/agent-home.html
index 9a0ca5422..230dbcad6 100644
--- a/agent-home.html
+++ b/agent-home.html
@@ -905,7 +905,7 @@
<!-- BEGIN:AGENT_HOME_ORPHANS_SCRIPT -->
<script type="module">
- import { mountOrphans } from './src/agent-home-orphans.js';
+ import { mountOrphans } from '/src/agent-home-orphans.js';
function _tryMount() {
const d = window.__agentReady;
diff --git a/package.json b/package.json
index d5c80951d..372780238 100644
--- a/package.json
+++ b/package.json
@@ -45,6 +45,8 @@
"generate-icons": "node scripts/generate-pwa-icons.mjs",
"fetch-animations": "node scripts/download-animations.mjs",
"test": "vitest run",
+ "test:pages": "node scripts/test-pages.mjs",
+ "test:all": "npm run test && npm run test:pages",
"verify": "prettier --check . && vite build",
"format": "prettier --write .",
"deploy": "npm run build:all && vercel --local-config vercel.json --prod",
diff --git a/scripts/test-pages.mjs b/scripts/test-pages.mjs
new file mode 100644
index 000000000..3545330d9
--- /dev/null
+++ b/scripts/test-pages.mjs
@@ -0,0 +1,138 @@
+#!/usr/bin/env node
+import { chromium } from 'playwright';
+import { spawn } from 'child_process';
+import { setTimeout as wait } from 'timers/promises';
+
+const PORT = 3100;
+const BASE = `http://localhost:${PORT}`;
+
+const ROUTES = [
+ '/',
+ '/app',
+ '/home',
+ '/create',
+ '/profile',
+ '/login',
+ '/agent',
+ '/agents',
+ '/dashboard',
+ '/studio',
+ '/widgets',
+ '/docs',
+ '/docs/widgets',
+ '/cz',
+ '/validation',
+ '/reputation',
+ '/hydrate',
+ '/my-agents',
+ '/discover',
+ '/explore',
+ '/features',
+ '/embed.html',
+ '/embed-test.html',
+ '/avatar-page.html',
+ '/avatar-artifact.html',
+ '/agent-home.html',
+ '/agent-edit.html',
+ '/agent-embed.html',
+ '/a-edit.html',
+ '/a-embed.html',
+];
+
+function startServer() {
+ const proc = spawn('npx', ['vite', '--port', String(PORT), '--strictPort'], {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, FORCE_COLOR: '0' },
+ });
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('vite did not start in 30s')), 30000);
+ proc.stdout.on('data', (d) => {
+ if (String(d).includes('ready in') || String(d).includes('Local:')) {
+ clearTimeout(timer);
+ resolve(proc);
+ }
+ });
+ proc.stderr.on('data', (d) => process.stderr.write(d));
+ proc.on('exit', (code) => {
+ if (code !== 0) reject(new Error(`vite exited with code ${code}`));
+ });
+ });
+}
+
+async function checkRoute(browser, route) {
+ const ctx = await browser.newContext();
+ const page = await ctx.newPage();
+ const errors = [];
+ const failures = [];
+ page.on('pageerror', (err) => errors.push(`pageerror: ${err.message}`));
+ page.on('console', (msg) => {
+ if (msg.type() === 'error') errors.push(`console.error: ${msg.text()}`);
+ });
+ page.on('requestfailed', (req) => {
+ const url = req.url();
+ if (url.startsWith('chrome-extension://')) return;
+ failures.push(`requestfailed: ${url} — ${req.failure()?.errorText}`);
+ });
+ page.on('response', (res) => {
+ if (res.status() >= 400 && !res.url().includes('favicon')) {
+ failures.push(`http ${res.status()}: ${res.url()}`);
+ }
+ });
+ let loadError = null;
+ try {
+ const resp = await page.goto(`${BASE}${route}`, {
+ waitUntil: 'networkidle',
+ timeout: 20000,
+ });
+ if (!resp || resp.status() >= 400) {
+ loadError = `nav status ${resp?.status() ?? 'none'}`;
+ }
+ await wait(500);
+ } catch (e) {
+ loadError = e.message;
+ }
+ await ctx.close();
+ return { route, loadError, errors, failures };
+}
+
+async function main() {
+ console.log(`Starting vite on :${PORT}…`);
+ const server = await startServer();
+ let browser;
+ let exitCode = 0;
+ try {
+ browser = await chromium.launch();
+ console.log(`Checking ${ROUTES.length} routes…\n`);
+ const results = [];
+ for (const route of ROUTES) {
+ const r = await checkRoute(browser, route);
+ results.push(r);
+ const issues = r.errors.length + r.failures.length + (r.loadError ? 1 : 0);
+ const tag = issues === 0 ? 'OK ' : 'FAIL';
+ console.log(` [${tag}] ${route} (${issues} issue${issues === 1 ? '' : 's'})`);
+ }
+ console.log('\n--- Detail ---');
+ for (const r of results) {
+ if (!r.loadError && r.errors.length === 0 && r.failures.length === 0) continue;
+ exitCode = 1;
+ console.log(`\n${r.route}`);
+ if (r.loadError) console.log(` load: ${r.loadError}`);
+ for (const e of r.errors) console.log(` ${e}`);
+ for (const f of r.failures) console.log(` ${f}`);
+ }
+ const totalIssues = results.reduce(
+ (n, r) => n + r.errors.length + r.failures.length + (r.loadError ? 1 : 0),
+ 0,
+ );
+ console.log(`\nDone. ${totalIssues} issue(s) across ${ROUTES.length} routes.`);
+ } finally {
+ if (browser) await browser.close();
+ server.kill('SIGTERM');
+ }
+ process.exit(exitCode);
+}
+
+main().catch((e) => {
+ console.error(e);
+ process.exit(1);
+});
diff --git a/src/create.js b/src/create.js
index 810c37bfa..7f724add8 100644
--- a/src/create.js
+++ b/src/create.js
@@ -9,7 +9,7 @@ async function boot() {
saveAndRedirect(blob, { source: 'avaturn' }),
);
- document.getElementById('back-btn').addEventListener('click', () => {
+ document.getElementById('back-btn')?.addEventListener('click', () => {
if (history.length > 1) history.back();
else window.location.href = '/';
});
diff --git a/src/erc8004/agent-registry.js b/src/erc8004/agent-registry.js
index b5e26a3eb..d23be97be 100644
--- a/src/erc8004/agent-registry.js
+++ b/src/erc8004/agent-registry.js
@@ -18,6 +18,151 @@ import { glbFileToThumbnail } from './thumbnail.js';
let _provider = null;
let _signer = null;
+let _address = null;
+let _chainId = null;
+const _listeners = new Set();
+let _walletEventsBound = false;
+
+// localStorage hint — set after a successful explicit connect, cleared on
+// `accountsChanged → []`. Lets us decide whether to *attempt* eager reconnect
+// on a fresh page load (avoiding noisy `eth_accounts` polls for first-time
+// visitors). Not authoritative — the wallet is still the source of truth.
+const HINT_KEY = '3dagent:wallet-connected';
+
+function setHint(on) {
+ try {
+ if (on) localStorage.setItem(HINT_KEY, '1');
+ else localStorage.removeItem(HINT_KEY);
+ } catch {
+ /* private mode / storage disabled */
+ }
+}
+
+function hasHint() {
+ try {
+ return localStorage.getItem(HINT_KEY) === '1';
+ } catch {
+ return false;
+ }
+}
+
+function notify(reason) {
+ const snapshot = {
+ address: _address,
+ chainId: _chainId,
+ signer: _signer,
+ reason,
+ };
+ for (const fn of _listeners) {
+ try {
+ fn(snapshot);
+ } catch {
+ /* listener errors must not break the bus */
+ }
+ }
+}
+
+function bindWalletEvents() {
+ if (_walletEventsBound || !window.ethereum?.on) return;
+ _walletEventsBound = true;
+
+ window.ethereum.on('accountsChanged', async (accounts) => {
+ if (!accounts || accounts.length === 0) {
+ _provider = null;
+ _signer = null;
+ _address = null;
+ _chainId = null;
+ setHint(false);
+ notify('disconnected');
+ return;
+ }
+ // Re-derive signer for the new account (no popup).
+ try {
+ _provider = new BrowserProvider(window.ethereum);
+ _signer = await _provider.getSigner();
+ _address = await _signer.getAddress();
+ const net = await _provider.getNetwork();
+ _chainId = Number(net.chainId);
+ notify('account-changed');
+ } catch {
+ /* swallow — next explicit connect will recover */
+ }
+ });
+
+ window.ethereum.on('chainChanged', async (chainIdHex) => {
+ _chainId = Number(chainIdHex);
+ // Refresh provider/signer so they bind to the new network.
+ if (_address) {
+ try {
+ _provider = new BrowserProvider(window.ethereum);
+ _signer = await _provider.getSigner();
+ } catch {
+ /* signer may briefly be unavailable mid-switch */
+ }
+ }
+ notify('chain-changed');
+ });
+}
+
+/**
+ * Subscribe to wallet state changes (connect, disconnect, account/chain switch).
+ * Returns an unsubscribe function.
+ *
+ * @param {(state: { address: string|null, chainId: number|null, signer: import('ethers').Signer|null, reason: string }) => void} fn
+ * @returns {() => void}
+ */
+export function onWalletChange(fn) {
+ _listeners.add(fn);
+ bindWalletEvents();
+ return () => _listeners.delete(fn);
+}
+
+/**
+ * Snapshot of the current wallet state without triggering a connection.
+ * @returns {{ address: string|null, chainId: number|null, signer: import('ethers').Signer|null }}
+ */
+export function getWalletState() {
+ return { address: _address, chainId: _chainId, signer: _signer };
+}
+
+/**
+ * Attempt a *silent* reconnect using `eth_accounts` — no MetaMask popup.
+ * Only succeeds if the wallet has previously authorized this origin and is
+ * still unlocked. Safe to call on every page mount.
+ *
+ * @returns {Promise<{address: string, chainId: number, signer: import('ethers').Signer} | null>}
+ * Resolves to null when no eager connection is possible (no wallet, no prior
+ * authorization, locked, or wallet refused). Never throws.
+ */
+export async function eagerConnectWallet() {
+ if (!window.ethereum) return null;
+ // Skip the RPC roundtrip for users who've never connected — no hint, no try.
+ // (Doesn't apply if the wallet was authorized in a previous session before
+ // we shipped the hint; on first visit after deploy they get one extra
+ // silent `eth_accounts` call which is free.)
+ if (!hasHint() && _address === null) {
+ // Still attempt once — `eth_accounts` is cheap and may surface an
+ // already-authorized session that predates the hint mechanism.
+ }
+ try {
+ const accounts = await window.ethereum.request({ method: 'eth_accounts' });
+ if (!accounts || accounts.length === 0) {
+ setHint(false);
+ return null;
+ }
+ _provider = new BrowserProvider(window.ethereum);
+ _signer = await _provider.getSigner();
+ _address = await _signer.getAddress();
+ const network = await _provider.getNetwork();
+ _chainId = Number(network.chainId);
+ setHint(true);
+ bindWalletEvents();
+ notify('eager-connected');
+ return { address: _address, chainId: _chainId, signer: _signer };
+ } catch {
+ return null;
+ }
+}
/**
* Connect a wallet via the injected EIP-1193 provider (MetaMask, Brave, etc.).
@@ -31,11 +176,15 @@ export async function connectWallet() {
_provider = new BrowserProvider(window.ethereum);
_signer = await _provider.getSigner();
- const address = await _signer.getAddress();
+ _address = await _signer.getAddress();
const network = await _provider.getNetwork();
- const chainId = Number(network.chainId);
+ _chainId = Number(network.chainId);
+
+ setHint(true);
+ bindWalletEvents();
+ notify('connected');
- return { provider: _provider, signer: _signer, address, chainId };
+ return { provider: _provider, signer: _signer, address: _address, chainId: _chainId };
}
/**
diff --git a/src/erc8004/register-ui.js b/src/erc8004/register-ui.js
index 85b124b64..58a39818d 100644
--- a/src/erc8004/register-ui.js
+++ b/src/erc8004/register-ui.js
@@ -18,6 +18,8 @@
import {
registerAgent,
connectWallet,
+ eagerConnectWallet,
+ onWalletChange,
pinFile,
getIdentityRegistry,
buildRegistrationJSON,
@@ -288,6 +290,25 @@ export class RegisterUI {
this._build();
this._bind();
this._fetchBackendAgent(); // fire & forget
+ this._eagerConnectWallet(); // silent reconnect if wallet already authorized
+
+ // Keep the UI in sync when the user switches account/chain in the wallet,
+ // or when another tab/page on this origin connects/disconnects.
+ this._unsubscribeWallet = onWalletChange(({ address, chainId }) => {
+ if (!address) {
+ this.wallet = null;
+ } else {
+ this.wallet = { address, chainId: Number(chainId) };
+ if (REGISTRY_DEPLOYMENTS[this.wallet.chainId]) {
+ this.selectedChainId = this.wallet.chainId;
+ const sel = this.el.querySelector('.erc8004-chain-select');
+ if (sel) sel.value = String(this.selectedChainId);
+ }
+ }
+ this._refreshWalletButton();
+ this._renderActiveTab();
+ this._refreshMainnetBanner();
+ });
}
// -----------------------------------------------------------------------
@@ -379,6 +400,7 @@ export class RegisterUI {
}
destroy() {
+ if (this._unsubscribeWallet) this._unsubscribeWallet();
this.el.remove();
}
@@ -406,6 +428,23 @@ export class RegisterUI {
}
}
+ // Silent reconnect on mount — uses `eth_accounts` (no popup). If the wallet
+ // has previously authorized this origin and is unlocked, we restore the
+ // connection transparently so the user doesn't see "Connect MetaMask" twice.
+ async _eagerConnectWallet() {
+ const result = await eagerConnectWallet();
+ if (!result) return;
+ this.wallet = { address: result.address, chainId: Number(result.chainId) };
+ if (REGISTRY_DEPLOYMENTS[this.wallet.chainId]) {
+ this.selectedChainId = this.wallet.chainId;
+ const sel = this.el.querySelector('.erc8004-chain-select');
+ if (sel) sel.value = String(this.selectedChainId);
+ }
+ this._refreshWalletButton();
+ this._renderActiveTab();
+ this._refreshMainnetBanner();
+ }
+
_refreshWalletButton() {
const btn = this.el.querySelector('.erc8004-btn--wallet');
if (!this.wallet) {
diff --git a/vite.config.js b/vite.config.js
index e6ed1a784..c34ed7f17 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -83,8 +83,31 @@ const appConfig = {
'/docs': resolve(root, 'docs/index.html'),
'/docs/': resolve(root, 'docs/index.html'),
};
+ // Routes that resolve to public/<dir>/index.html — these need a
+ // trailing slash so relative imports (./foo.js) inside the HTML
+ // resolve to /<dir>/foo.js rather than /foo.js at the root.
+ const dirRoutes = new Set([
+ '/agents',
+ '/dashboard',
+ '/studio',
+ '/widgets',
+ '/cz',
+ '/validation',
+ '/reputation',
+ '/hydrate',
+ '/my-agents',
+ '/discover',
+ '/explore',
+ '/features',
+ '/docs',
+ ]);
server.middlewares.use(async (req, res, next) => {
const path = (req.url || '/').split('?')[0];
+ if (dirRoutes.has(path)) {
+ res.statusCode = 301;
+ res.setHeader('Location', path + '/' + (req.url.slice(path.length) || ''));
+ return res.end();
+ }
let filePath = fileMap[path];
if (!filePath && /^\/agent\/[^/]+\/edit$/.test(path))
filePath = resolve(root, 'agent-edit.html');