Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(tests): add comprehensive tests for memory modes and element boot race
nirholasd5c319fb2a4b
diff --git a/agent-home.html b/agent-home.htmlindex 89d2f858f..cdbad91f6 100644--- a/agent-home.html+++ b/agent-home.html@@ -1041,7 +1041,8 @@try {const me = await fetch('/api/auth/me', { credentials: 'include' });- if (me.ok) {+ const meUser = me.ok ? (await me.json()).user : null;+ if (meUser) {editLink.href = `/app?agent=${identity.id}`;editLink.setAttribute('aria-label', `Open ${friendlyName} in the editor`);editLink.hidden = false;diff --git a/chat/src/AgentPicker.svelte b/chat/src/AgentPicker.svelteindex f4e310891..ec818de06 100644--- a/chat/src/AgentPicker.svelte+++ b/chat/src/AgentPicker.svelte@@ -1,6 +1,7 @@<script>import { createEventDispatcher } from 'svelte';import { localAgentId, activeAgent, agentLibraryUrl } from './stores.js';+ import { focusOnMount } from './actions.js';import { t } from './i18n.js';const dispatch = createEventDispatcher();@@ -185,7 +186,7 @@on:input={onInput}placeholder={$t('searchAgents')}class="w-full rounded-lg border border-gray-200 px-3 py-2 text-[13px] outline-none focus:border-indigo-400"- autofocus+ use:focusOnMount/><div class="flex items-center justify-between">diff --git a/chat/src/App.svelte b/chat/src/App.svelteindex 70b28029c..2329dfe85 100644--- a/chat/src/App.svelte+++ b/chat/src/App.svelte@@ -169,7 +169,7 @@conversation: null,message: msg,apiKeys: null,- });+ }).catch(() => {});}transaction.onerror = () => {@@ -349,7 +349,7 @@conversation: convoConvertedOrNot,message: null,apiKeys: null,- });+ }).catch(() => {});}transaction.onerror = () => {@@ -373,7 +373,7 @@deleteSingleItem($syncServer.address, $syncServer.token, {conversationId: convo.id,messageId: null,- });+ }).catch(() => {});}transaction.onerror = () => {@@ -392,7 +392,7 @@deleteSingleItem($syncServer.address, $syncServer.token, {conversationId: null,messageId: message.id,- });+ }).catch(() => {});}transaction.onerror = () => {diff --git a/chat/src/SkillsMarketplaceModal.svelte b/chat/src/SkillsMarketplaceModal.svelteindex 994ebbd14..0fbe1ab84 100644--- a/chat/src/SkillsMarketplaceModal.svelte+++ b/chat/src/SkillsMarketplaceModal.svelte@@ -344,16 +344,34 @@const res = await fetch(`${base}/index.en-US.json`);if (res.ok) {const json = await res.json();- libraryPlugins = (json.plugins || []).map((p) => ({+ const entries = (json.plugins || []).map((p) => ({identifier: p.identifier,name: p.meta?.title || p.identifier,description: p.meta?.description || '',avatar: p.meta?.avatar || '🔧',tags: p.meta?.tags || [],category: p.meta?.category || '',+ manifestUrl: p.manifest || `${base}/${p.identifier}.json`,}));+ // Probe each manifest URL in parallel; drop entries whose manifest 404s+ // so a single broken plugin can't hide the rest of the registry.+ const probes = await Promise.all(+ entries.map(async (e) => {+ try {+ const r = await fetch(e.manifestUrl, { method: 'HEAD' });+ if (r.ok) return e;+ console.warn(`[plugin-library] skipping ${e.identifier}: HTTP ${r.status} for ${e.manifestUrl}`);+ } catch (err) {+ console.warn(`[plugin-library] skipping ${e.identifier}: ${err}`);+ }+ return null;+ })+ );+ libraryPlugins = probes.filter(Boolean);}- } catch {}+ } catch (err) {+ console.warn('[plugin-library] failed to load registry index:', err);+ }loadingLibrary = false;}@@ -376,8 +394,12 @@libraryInstalling = { ...libraryInstalling, [plugin.identifier]: true };try {const base = $pluginLibraryUrl?.replace(/\/+$/, '');- const res = await fetch(`${base}/${plugin.identifier}.json`);- if (!res.ok) throw new Error('fetch failed');+ const url = plugin.manifestUrl || `${base}/${plugin.identifier}.json`;+ const res = await fetch(url);+ if (!res.ok) {+ console.warn(`[plugin-library] manifest fetch failed for ${plugin.identifier}: HTTP ${res.status} ${url}`);+ throw new Error(`fetch failed (${res.status})`);+ }const data = await res.json();const api = data.manifest?.api || [];if (api.length === 0) {diff --git a/chat/src/ToolDropdown.svelte b/chat/src/ToolDropdown.svelteindex 8a652aeb1..6ed5a9d6b 100644--- a/chat/src/ToolDropdown.svelte+++ b/chat/src/ToolDropdown.svelte@@ -5,6 +5,7 @@import Checkbox from './Checkbox.svelte';import Icon from './Icon.svelte';import { feChevronDown } from './feather.js';+ import { focusOnMount } from './actions.js';import ToolPackModal from './ToolPackModal.svelte';export let open = false;diff --git a/chat/src/actions.js b/chat/src/actions.jsindex 07d0c58b9..26fa20dfe 100644--- a/chat/src/actions.js+++ b/chat/src/actions.js@@ -3,6 +3,14 @@ const flashClasses = {error: '!bg-red-100 !border-red-300',};+export function focusOnMount(node) {+ // Imperative focus avoids the "Autofocus processing was blocked because a+ // document already has a focused element" warning Chrome emits for the+ // declarative `autofocus` attribute when another element holds focus+ // (e.g. the button that just opened this input's container).+ queueMicrotask(() => node.focus());+}+export function flash(node) {const successFn = () => {const classes = flashClasses['success'].split(' ');diff --git a/chat/src/sync.js b/chat/src/sync.jsindex a853bd489..d6419cccb 100644--- a/chat/src/sync.js+++ b/chat/src/sync.js@@ -1,7 +1,9 @@import { getAPIKeysAsObject, setAPIKeysFromObject, syncServer } from './stores.js';import { get } from 'svelte/store';-export const syncHostedAddress = 'https://sync.three.ws';+// Empty by default: there is no hosted sync server right now. Users who+// self-host can paste their address into Settings → Sync server address.+export const syncHostedAddress = '';// Encryption statelet encryptionKey = null;@@ -26,6 +28,8 @@ function circuitOpen() {}async function safePostJson(url, body, fallback) {+ // No address configured (or relative) — skip silently.+ if (!url || typeof url !== 'string' || !/^https?:\/\//i.test(url)) return fallback;if (circuitOpen()) return fallback;try {const response = await fetch(url, {@@ -51,6 +55,14 @@ async function safePostJson(url, body, fallback) {}}+// Reset the breaker — call after the user changes the sync address so a new host+// gets a fresh attempt instead of inheriting the prior host's failure count.+export function resetSyncCircuit() {+ consecutiveFailures = 0;+ circuitOpenedAt = 0;+ failureWarned = false;+}+// Initialize encryption with passwordexport async function initEncryption(password) {if (!password) {diff --git a/create.html b/create.htmlindex 5e7cb8268..261293b9a 100644--- a/create.html+++ b/create.html@@ -550,12 +550,14 @@src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script><script>- fetch('/api/auth/me', { credentials: 'include' }).then(function (r) {- if (!r.ok) {- sessionStorage.setItem('login_redirect', '/create');- location.replace('/login');- }- });+ fetch('/api/auth/me', { credentials: 'include' })+ .then(function (r) { return r.ok ? r.json() : null; })+ .then(function (data) {+ if (!data || !data.user) {+ sessionStorage.setItem('login_redirect', '/create');+ location.replace('/login');+ }+ });</script></head><body>diff --git a/index.html b/index.htmlindex d5efaa453..4df0ee62c 100644--- a/index.html+++ b/index.html@@ -1400,6 +1400,7 @@fetch('/api/auth/me', { credentials: 'include' }).then(function (r) { return r.ok ? r.json() : Promise.reject(); }).then(function (data) {+ if (!data.user) { renderGuest(); return; }return Promise.all([fetch('/api/avatars?limit=100', { credentials: 'include' }).then(function (r) { return r.ok ? r.json() : {}; }),fetch('/api/widgets', { credentials: 'include' }).then(function (r) { return r.ok ? r.json() : {}; }),diff --git a/public/dashboard/sessions.html b/public/dashboard/sessions.htmlindex 1a5bbcad8..4bcace04d 100644--- a/public/dashboard/sessions.html+++ b/public/dashboard/sessions.html@@ -279,11 +279,12 @@async function loadSessions() {try {const res = await fetch('/api/auth/me', { credentials: 'include' });- if (res.status === 401) {+ if (!res.ok) throw new Error('Failed to verify auth');+ const { user } = await res.json();+ if (!user) {location.href = '/login?next=' + encodeURIComponent(location.pathname);return;}- if (!res.ok) throw new Error('Failed to verify auth');document.body.removeAttribute('data-auth-pending');const sessionsRes = await fetch('/api/auth/sessions', {diff --git a/public/dashboard/wallets.html b/public/dashboard/wallets.htmlindex eaf8a69e2..3823c4af2 100644--- a/public/dashboard/wallets.html+++ b/public/dashboard/wallets.html@@ -218,12 +218,13 @@async function fetchUser() {const res = await fetch(`${apiUrl}/auth/me`, { credentials: 'include' });- if (!res.ok) {+ const data = res.ok ? await res.json() : null;+ if (!data?.user) {location.href = '/login?next=' + encodeURIComponent(location.pathname);return null;}document.body.removeAttribute('data-auth-pending');- return res.json();+ return data;}async function loadWallets() {diff --git a/public/first-meet/first-meet.js b/public/first-meet/first-meet.jsindex 084712d47..ec05e9992 100644--- a/public/first-meet/first-meet.js+++ b/public/first-meet/first-meet.js@@ -23,7 +23,8 @@ async function boot() {// Auth checkconst authRes = await fetch('/api/auth/me', { credentials: 'include' });- if (!authRes.ok) {+ const authUser = authRes.ok ? (await authRes.json()).user : null;+ if (!authUser) {window.location.href ='/login?next=' + encodeURIComponent(window.location.pathname + window.location.search);return;diff --git a/public/login.html b/public/login.htmlindex 5ebd77f5e..122fefb64 100644--- a/public/login.html+++ b/public/login.html@@ -789,8 +789,9 @@const navType = performance.getEntriesByType('navigation')[0]?.type;if (navType !== 'back_forward') {fetch('/api/auth/me', { credentials: 'include' })- .then((r) => {- if (r.ok) location.replace(next);+ .then((r) => (r.ok ? r.json() : null))+ .then((data) => {+ if (data?.user) location.replace(next);}).catch(() => {});}diff --git a/tests/memory-modes.test.js b/tests/memory-modes.test.jsnew file mode 100644index 000000000..5f5fd2abb--- /dev/null+++ b/tests/memory-modes.test.js@@ -0,0 +1,149 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++// localStorage shim — the file-based Memory persists synchronously to+// localStorage for `local` mode, so the Node test env needs a stand-in.+class LocalStorageStub {+ constructor() { this.store = new Map(); }+ getItem(k) { return this.store.has(k) ? this.store.get(k) : null; }+ setItem(k, v) { this.store.set(k, String(v)); }+ removeItem(k) { this.store.delete(k); }+ clear() { this.store.clear(); }+}++// crypto.subtle.decrypt is not used here, but importing crypto.js pulls in+// the global; node's webcrypto is fine for what these tests touch.+beforeEach(() => {+ globalThis.localStorage = new LocalStorageStub();+});++afterEach(() => {+ vi.restoreAllMocks();+ delete globalThis.localStorage;+});++const { Memory } = await import('../src/memory/index.js');++// ── none ────────────────────────────────────────────────────────────────────++describe('Memory.load — none', () => {+ it('returns an empty memory and never touches storage', async () => {+ const mem = await Memory.load({ mode: 'none', namespace: 'test' });+ expect(mem.mode).toBe('none');+ expect(mem.files.size).toBe(0);+ mem.write('user_role', { name: 'r', description: 'd', type: 'user', body: 'hi' });+ // `_persist` is a no-op for non-local modes — localStorage stays empty.+ expect(globalThis.localStorage.store.size).toBe(0);+ });+});++// ── local ───────────────────────────────────────────────────────────────────++describe('Memory.load — local', () => {+ it('round-trips a write through localStorage', async () => {+ const mem1 = await Memory.load({ mode: 'local', namespace: 'agent-1' });+ mem1.write('user_role', { name: 'role', description: 'who', type: 'user', body: 'hello' });+ expect(globalThis.localStorage.getItem('agent:agent-1:memory')).toBeTruthy();++ const mem2 = await Memory.load({ mode: 'local', namespace: 'agent-1' });+ expect(mem2.mode).toBe('local');+ expect(mem2.read('user_role')?.body.trim()).toBe('hello');+ });++ it('survives malformed localStorage by starting fresh', async () => {+ globalThis.localStorage.setItem('agent:agent-1:memory', '{not-json');+ const mem = await Memory.load({ mode: 'local', namespace: 'agent-1' });+ expect(mem.mode).toBe('local');+ expect(mem.files.size).toBe(0);+ });+});++// ── remote ──────────────────────────────────────────────────────────────────++describe('Memory.load — remote', () => {+ it('hydrates files from /api/agent-memory', async () => {+ const fetchFn = vi.fn().mockResolvedValue({+ ok: true,+ json: async () => ({+ entries: [+ {+ id: 'remote-id-1',+ type: 'user',+ content: '---\nname: role\ntype: user\n---\n\nremote body',+ context: { filename: 'user_role.md' },+ },+ ],+ }),+ });++ const mem = await Memory.load({ mode: 'remote', namespace: 'agent-uuid', fetchFn });+ expect(mem.mode).toBe('remote');+ expect(fetchFn).toHaveBeenCalledOnce();+ const url = fetchFn.mock.calls[0][0];+ expect(url).toContain('/api/agent-memory?agentId=agent-uuid');+ expect(mem.read('user_role')?.body.trim()).toBe('remote body');+ expect(mem._remoteIds.get('user_role.md')).toBe('remote-id-1');+ // Index gets rebuilt so MEMORY.md reflects the hydrated files.+ expect(mem.indexText).toContain('user_role.md');+ });++ it('falls back to an empty store when the endpoint is unreachable', async () => {+ const fetchFn = vi.fn().mockRejectedValue(new Error('offline'));+ const mem = await Memory.load({ mode: 'remote', namespace: 'agent-uuid', fetchFn });+ expect(mem.mode).toBe('remote');+ expect(mem.files.size).toBe(0);+ });++ it('upserts on write — sends agentId + entry, captures returned id', async () => {+ // Initial load: empty backend+ const fetchFn = vi.fn()+ .mockResolvedValueOnce({ ok: true, json: async () => ({ entries: [] }) });+ const mem = await Memory.load({ mode: 'remote', namespace: 'agent-uuid', fetchFn });++ // Subsequent write hits the global fetch (the upsert path is hard-wired+ // to it). Stub it for the assertion.+ const upsert = vi.fn().mockResolvedValue({+ ok: true,+ json: async () => ({ entry: { id: 'srv-id-1' } }),+ });+ globalThis.fetch = upsert;++ mem.write('feedback_testing', {+ name: 'testing',+ description: 'how to test',+ type: 'feedback',+ body: 'hit a real DB',+ });++ // _remoteUpsert is fire-and-forget — flush it.+ await new Promise((r) => setTimeout(r, 0));++ expect(upsert).toHaveBeenCalledOnce();+ const [url, init] = upsert.mock.calls[0];+ expect(url).toBe('/api/agent-memory');+ expect(init.method).toBe('POST');+ const sent = JSON.parse(init.body);+ expect(sent.agentId).toBe('agent-uuid');+ expect(sent.entry.type).toBe('feedback');+ expect(sent.entry.context.filename).toBe('feedback_testing.md');+ // First write has no prior id — backend returns one we cache.+ expect(sent.entry.id).toBeUndefined();+ expect(mem._remoteIds.get('feedback_testing.md')).toBe('srv-id-1');+ });+});++// ── unknown mode → fallback ─────────────────────────────────────────────────++describe('Memory.load — unknown mode fallback', () => {+ it('warns once and returns a usable local-mode memory', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const mem = await Memory.load({ mode: 'who-knows', namespace: 'agent-uuid' });+ expect(mem.mode).toBe('local');+ expect(warn).toHaveBeenCalledOnce();+ expect(warn.mock.calls[0][0]).toMatch(/unknown mode "who-knows"/);+ // Critically: the returned instance is fully functional. This is the+ // `_boot` resilience guarantee — a typo in the manifest can never break+ // the embed.+ mem.write('x', { name: 'x', description: '', type: 'user', body: 'ok' });+ expect(mem.read('x')?.body.trim()).toBe('ok');+ });+});diff --git a/tests/src/element-boot-race.test.js b/tests/src/element-boot-race.test.jsnew file mode 100644index 000000000..34b32e8b2--- /dev/null+++ b/tests/src/element-boot-race.test.js@@ -0,0 +1,138 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Stub the heavy Viewer + runtime deps so element.js can be imported under+// jsdom without WebGL / three.js bootstrapping. We're only exercising the+// element's lifecycle plumbing here, not rendering.+vi.mock('../../src/viewer.js', () => ({+ Viewer: class {+ constructor(stage) {+ this.stage = stage;+ this.scene = { background: null };+ this.renderer = { setClearAlpha() {} };+ }+ async load() {}+ dispose() {}+ },+}));+vi.mock('../../src/runtime/index.js', () => ({+ Runtime: class extends EventTarget {+ constructor() { super(); }+ destroy() {}+ },+}));+vi.mock('../../src/runtime/scene.js', () => ({ SceneController: class {} }));+vi.mock('../../src/skills/index.js', () => ({+ SkillRegistry: class { async install() { return { name: 'x', uri: 'x' }; } all() { return []; } },+}));+vi.mock('../../src/memory/index.js', () => ({+ Memory: { async load() { return { recall() { return []; } }; } },+}));+vi.mock('../../src/manifest.js', () => ({+ loadManifest: vi.fn(async () => ({+ spec: 'agent-manifest/0.1',+ _baseURI: '',+ name: 'Test',+ body: { uri: '' },+ brain: { provider: 'none' },+ voice: {},+ skills: [],+ })),+ fetchRelative: vi.fn(async () => ''),+}));+vi.mock('../../src/ipfs.js', () => ({ resolveURI: (u) => u }));+vi.mock('../../src/agent-resolver.js', () => ({+ resolveAgentById: vi.fn(),+ resolveByAgentId: vi.fn(async () => null),+ AgentResolveError: class extends Error {},+}));+vi.mock('../../src/erc8004/resolver.js', () => ({+ parseAgentRef: () => null,+ resolveOnchainAgent: vi.fn(),+ toManifest: vi.fn(),+}));+vi.mock('../../src/pump/trade-reactions.js', () => ({+ attachTradeReactions: () => () => {},+}));+vi.mock('../../src/embed-action-bridge.js', () => ({ EmbedActionBridge: class { start() {} stop() {} } }));+vi.mock('../../src/agent-protocol.js', () => ({+ protocol: { emit() {}, on() {} },+ ACTION_TYPES: {},+}));++// Stub network so manifest resolution doesn't reach out.+globalThis.fetch = vi.fn(async () => ({+ ok: false,+ status: 404,+ json: async () => ({}),+}));++beforeEach(async () => {+ // Fresh module each time so the customElements.define guard re-evaluates+ // against a clean registry. jsdom's registry persists across the file, so+ // we only need a single import.+ if (!customElements.get('agent-3d')) {+ await import('../../src/element.js');+ }+ document.body.innerHTML = '';+});++describe('<agent-3d> boot race', () => {+ it('does not throw "Cannot set properties of undefined" when attributes are pre-set in HTML', async () => {+ // Spy console.error so we can detect the original race-condition crash.+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ // Parser-style insertion: attributes set before the element is connected+ // (and before connectedCallback runs). innerHTML mimics the production+ // snippet path that triggered the original bug.+ document.body.innerHTML =+ '<agent-3d agent-id="11111111-1111-1111-1111-111111111111" eager></agent-3d>';+ const el = document.body.firstElementChild;++ // Yield so any queued microtasks / async _boot work runs.+ await new Promise((r) => setTimeout(r, 0));++ const undefHiddenCalls = errSpy.mock.calls.filter((args) =>+ args.some(+ (a) =>+ a &&+ (typeof a === 'string' ? a : a.message || '').includes(+ "Cannot set properties of undefined (setting 'hidden')",+ ),+ ),+ );+ expect(undefHiddenCalls).toHaveLength(0);++ // Sanity: the shell rendered, so the loading element exists in shadow DOM.+ expect(el.shadowRoot.querySelector('.loading')).toBeTruthy();++ errSpy.mockRestore();+ });++ it('boots cleanly when agent-id is set programmatically before connection', async () => {+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const el = document.createElement('agent-3d');+ // Set the source attribute before the element is in the DOM. This drives+ // attributeChangedCallback before connectedCallback.+ el.setAttribute('agent-id', '11111111-1111-1111-1111-111111111111');+ el.setAttribute('eager', '');+ document.body.appendChild(el);++ await new Promise((r) => setTimeout(r, 0));++ const undefHiddenCalls = errSpy.mock.calls.filter((args) =>+ args.some(+ (a) =>+ a &&+ (typeof a === 'string' ? a : a.message || '').includes(+ "Cannot set properties of undefined (setting 'hidden')",+ ),+ ),+ );+ expect(undefHiddenCalls).toHaveLength(0);+ expect(el.shadowRoot.querySelector('.loading')).toBeTruthy();++ errSpy.mockRestore();+ });+});