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.

50.7 KB
Raw Blame
// dashboard-next — Account page.
//
// Consolidates profile, linked wallets, SNS domains, delegation entry,
// and the audit trail behind a single sidebar destination.

import { mountShell } from '../shell.js';
import { requireUser, get, post, patch, del, esc, relTime, initialsOf } from '../api.js';
import { skeletonHTML, errorStateHTML, ensureStateKitStyles } from '../../shared/state-kit.js';
import { toast } from '../../shared/toast.js';
import { loadLinkedDevices, loadPayoutWallets } from './account-linking.js';
import { shortAddress } from '../../shared/address.js';

// Loading placeholder — a stack of shimmer rows sized for a table/list slot.
function skelStack(count) {
	return `<div style="display:flex;flex-direction:column;gap:8px">${skeletonHTML(count, 'row')}</div>`;
}

// Recoverable error slot — real Retry button wired to the caller's loader.
// The button is recreated on every render, so no listener ever stacks.
function showLoadError(host, { title, body }, retry) {
	host.innerHTML = errorStateHTML({ title, body });
	const btn = host.querySelector('[data-sk-retry]');
	if (btn && typeof retry === 'function') btn.addEventListener('click', () => retry());
}

const CHAIN_STYLES = {
	solana:   { label: 'Solana',   bg: 'rgba(200, 202, 208, 0.14)', border: 'rgba(200, 202, 208, 0.28)', ink: '#c5c7cc' },
	base:     { label: 'Base',     bg: 'rgba(180, 184, 192, 0.14)', border: 'rgba(180, 184, 192, 0.28)', ink: '#b4b8c0' },
	ethereum: { label: 'Ethereum', bg: 'rgba(150, 160, 175, 0.14)', border: 'rgba(150, 160, 175, 0.28)', ink: '#c5cbd5' },
	polygon:  { label: 'Polygon',  bg: 'rgba(170, 174, 182, 0.14)', border: 'rgba(170, 174, 182, 0.28)', ink: '#bbbfc6' },
	optimism: { label: 'Optimism', bg: 'rgba(160, 164, 172, 0.14)', border: 'rgba(160, 164, 172, 0.28)', ink: '#b0b4bc' },
	evm:      { label: 'EVM',      bg: 'rgba(150, 160, 175, 0.14)', border: 'rgba(150, 160, 175, 0.28)', ink: '#c5cbd5' },
};

const MONO = `'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace`;

const CATEGORY_BY_ACTION = [
	[/^(link_wallet|unlink_wallet|set_primary_wallet|password_|email_|login|logout|session|revoke_oauth_token|link_|unlink_|reauth|register)/, 'Auth'],
	[/^(avatar_|create_avatar|delete_avatar|upload_avatar)/,             'Avatar'],
	[/^(widget_|embed_)/,                                                'Widget'],
	[/^(payment_|invoice_|payout_|withdraw_|stripe_|x402_)/,             'Payment'],
	[/^(api_key|key_|revoke_api_key|delegate_|delegation_)/,             'Auth'],
];

function categoryOf(action) {
	const a = String(action || '');
	for (const [re, cat] of CATEGORY_BY_ACTION) if (re.test(a)) return cat;
	return 'Settings';
}

function chainKey(w) {
	const t = String(w.chain_type || '').toLowerCase();
	if (t === 'solana') return 'solana';
	const id = Number(w.chain_id);
	if (id === 8453 || id === 84532) return 'base';
	if (id === 1 || id === 11155111) return 'ethereum';
	if (id === 137 || id === 80001 || id === 80002) return 'polygon';
	if (id === 10 || id === 11155420) return 'optimism';
	return 'evm';
}

function chainChip(w) {
	const style = CHAIN_STYLES[chainKey(w)] || CHAIN_STYLES.evm;
	return `<span class="dn-tag" style="background:${style.bg};border-color:${style.border};color:${style.ink}">${style.label}</span>`;
}

function truncMid(s, head = 6, tail = 4) { return shortAddress(s, head, tail); }


async function copyToClipboard(text) {
	try {
		await navigator.clipboard.writeText(text);
		toast('Copied');
	} catch {
		const t = document.createElement('textarea');
		t.value = text;
		t.style.position = 'fixed';
		t.style.opacity = '0';
		document.body.appendChild(t);
		t.select();
		try { document.execCommand('copy'); toast('Copied'); } catch { toast('Copy failed'); }
		document.body.removeChild(t);
	}
}

(async function boot() {
	const main = await mountShell();
	const me = await requireUser();
	ensureStateKitStyles();

	main.innerHTML = `
		<h1 class="dn-h1">Account</h1>
		<p class="dn-h1-sub">Profile, wallets, and the audit trail.</p>

		<div style="display:grid;grid-template-columns:minmax(0,1fr);gap:16px">
			<section class="dn-panel" data-section="profile">
				<div data-slot="profile"></div>
			</section>

			<section class="dn-panel" data-section="provider-keys">
				<div style="margin-bottom:14px">
					<div class="dn-panel-title">AI Provider Keys</div>
					<div class="dn-panel-sub" style="margin:0">Bring your own API key to unlock AI models. Your keys are encrypted and never shared.</div>
				</div>
				<div data-slot="provider-keys">${skelStack(3)}</div>
			</section>

			<section class="dn-panel" id="wallets" data-section="wallets">
				<div style="display:flex;justify-content:space-between;align-items:start;gap:16px;margin-bottom:14px;flex-wrap:wrap">
					<div>
						<div class="dn-panel-title">Linked wallets</div>
						<div class="dn-panel-sub" style="margin:0">Addresses that can claim royalties, pay for subscriptions, or sign as you.</div>
					</div>
					<button class="dn-btn primary" type="button" data-action="link-wallet">+ Link wallet</button>
				</div>
				<div data-slot="wallets">${skelStack(3)}</div>
			</section>

			<section class="dn-panel" id="payout-wallets" data-section="payout-wallets">
				<div style="margin-bottom:14px">
					<div class="dn-panel-title">Payout wallets</div>
					<div class="dn-panel-sub" style="margin:0">Where earnings go, for the whole account or one agent. Proved with a signed message; changes to a live wallet need step-up and a cooldown.</div>
				</div>
				<div data-slot="payout-wallets">${skelStack(2)}</div>
			</section>

			<section class="dn-panel" id="linked-devices" data-section="linked-devices">
				<div style="margin-bottom:14px">
					<div class="dn-panel-title">Linked devices</div>
					<div class="dn-panel-sub" style="margin:0">Phones, desktop apps, terminals and Telegram chats signed in with a one-time link code. Revoke any of them with one click.</div>
				</div>
				<div data-slot="linked-devices">${skelStack(3)}</div>
			</section>

			<section class="dn-panel" data-section="vanity">
				<div style="display:flex;justify-content:space-between;align-items:start;gap:16px;margin-bottom:14px;flex-wrap:wrap">
					<div>
						<div class="dn-panel-title">Vanity wallets</div>
						<div class="dn-panel-sub" style="margin:0">Generate wallet addresses with a custom prefix — Solana vanity keypair or Ethereum CREATE2 contract address.</div>
					</div>
				</div>
				<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:10px">
					<a class="dn-btn" href="/vanity-wallet" target="_blank" rel="noopener" style="justify-content:center">Solana vanity ✦ ↗</a>
					<a class="dn-btn" href="/eth-vanity" target="_blank" rel="noopener" style="justify-content:center">ETH vanity (CREATE2) ✦ ↗</a>
				</div>
			</section>

			<section class="dn-panel" data-section="sns">
				<div style="display:flex;justify-content:space-between;align-items:start;gap:16px;margin-bottom:14px;flex-wrap:wrap">
					<div>
						<div class="dn-panel-title">SNS &amp; handle domains</div>
						<div class="dn-panel-sub" style="margin:0">.sol domains you own that point at one of your linked wallets.</div>
					</div>
					<a class="dn-btn" href="/vanity-wallet">+ Register a domain</a>
				</div>
				<div data-slot="sns">${skelStack(2)}</div>
			</section>

			<section class="dn-panel" id="delegation" data-section="delegation">
				<div style="display:flex;justify-content:space-between;align-items:start;gap:16px;margin-bottom:14px;flex-wrap:wrap">
					<div>
						<div class="dn-panel-title">Delegation</div>
						<div class="dn-panel-sub" style="margin:0">Let one of your agents answer on behalf of another, or hand off to a partner agent.</div>
					</div>
					<button class="dn-btn" type="button" data-action="open-delegation-console">Open delegation console →</button>
				</div>
				<div data-slot="delegation">${skelStack(3)}</div>
				<div data-slot="delegation-console" hidden></div>
			</section>

			<section class="dn-panel" data-section="actions">
				<div style="display:flex;justify-content:space-between;align-items:start;gap:16px;margin-bottom:14px;flex-wrap:wrap">
					<div>
						<div class="dn-panel-title">Action log</div>
						<div class="dn-panel-sub" style="margin:0">Sensitive operations on your account — wallet links, key issuance, sign-ins.</div>
					</div>
					<button class="dn-btn" data-action="export-csv">Export CSV</button>
				</div>
				<div data-slot="actions">${skelStack(6)}</div>
			</section>

			<section class="dn-panel" data-section="quick-links">
				<div class="dn-panel-title" style="margin-bottom:12px">More settings</div>
				<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:10px">
					<a class="dn-btn" href="/dashboard/settings" style="justify-content:center">Sessions &amp; notifications →</a>
					<a class="dn-btn" href="/dashboard/settings" style="justify-content:center">Storage &amp; LLM usage →</a>
					<a class="dn-btn" href="/dashboard/settings" style="justify-content:center">Preferences →</a>
					<a class="dn-btn" href="/reputation" target="_blank" rel="noopener" style="justify-content:center">ERC-8004 registry ↗</a>
				</div>
			</section>
		</div>
	`;

	renderProfile(main.querySelector('[data-slot="profile"]'), me);
	loadProviderKeys(main.querySelector('[data-slot="provider-keys"]'));

	const walletsHost = main.querySelector('[data-slot="wallets"]');
	const snsHost = main.querySelector('[data-slot="sns"]');
	const delegationHost = main.querySelector('[data-slot="delegation"]');
	const actionsHost = main.querySelector('[data-slot="actions"]');

	// The section-header "+ Link wallet" sits outside the wallets slot, so it
	// survives every re-render of that slot and is wired once here.
	main.querySelector('#wallets [data-action="link-wallet"]')
		.addEventListener('click', (e) => startWalletLink(walletsHost, e.currentTarget));

	snsPanelHost = snsHost;
	await loadWallets(walletsHost);

	loadLinkedDevices(main.querySelector('[data-slot="linked-devices"]'));
	get('/api/agents?limit=100').then((r) => (Array.isArray(r?.agents) ? r.agents : Array.isArray(r) ? r : [])).catch(() => [])
		.then((agents) => loadPayoutWallets(main.querySelector('[data-slot="payout-wallets"]'), agents));

	const delegationConsoleHost = main.querySelector('[data-slot="delegation-console"]');
	const delegationSection = main.querySelector('#delegation');
	await loadDelegations(delegationHost, delegationConsoleHost);

	// "Open delegation console →" (section header) and per-agent "Configure →"
	// both open the real console below the table — no more dead self-anchors.
	delegationSection.addEventListener('click', (e) => {
		const opener = e.target.closest('[data-action="open-delegation-console"]');
		const configure = e.target.closest('[data-action="configure-delegation"]');
		if (!opener && !configure) return;
		e.preventDefault();
		openDelegationConsole(
			delegationConsoleHost,
			configure ? configure.getAttribute('data-agent-id') : null,
		);
	});

	loadActions(actionsHost);

	main.querySelector('[data-action="export-csv"]').addEventListener('click', async (e) => {
		const btn = e.currentTarget;
		const originalText = btn.textContent;
		btn.disabled = true;
		btn.textContent = 'Exporting…';
		try {
			const res = await fetch('/api/audit-log?format=csv', { credentials: 'include' });
			if (!res.ok) {
				if (res.status === 404) toast('Audit log endpoint not deployed yet');
				else if (res.status === 401) toast('Sign in required');
				else toast(`Export failed: HTTP ${res.status}`);
				return;
			}
			const blob = await res.blob();
			const url = URL.createObjectURL(blob);
			const a = document.createElement('a');
			a.href = url;
			a.download = `audit-log-${new Date().toISOString().slice(0, 10)}.csv`;
			document.body.appendChild(a);
			a.click();
			a.remove();
			URL.revokeObjectURL(url);
			toast('CSV downloaded');
		} catch (err) {
			toast(err?.message ? `Export failed: ${err.message}` : 'Export failed');
		} finally {
			btn.disabled = false;
			btn.textContent = originalText;
		}
	});
})();

// ── AI Provider Keys (BYOK) ───────────────────────────────────────────────

const PROVIDER_META = {
	anthropic: { label: 'Anthropic (Claude)',     placeholder: 'sk-ant-api03-…', url: 'https://console.anthropic.com/settings/keys' },
	openai:    { label: 'OpenAI (GPT-4)',          placeholder: 'sk-proj-…',      url: 'https://platform.openai.com/api-keys' },
	grok:      { label: 'Grok (xAI)',              placeholder: 'xai-…',          url: 'https://console.x.ai' },
	meshy:     { label: 'Meshy AI (3D gen)',       placeholder: 'msy_…',          url: 'https://www.meshy.ai/settings/api' },
	tripo:     { label: 'Tripo AI (3D gen)',       placeholder: 'tsk_…',          url: 'https://platform.tripo3d.ai/api-keys' },
	rodin:     { label: 'Rodin · Hyper3D (3D gen)', placeholder: 'your Rodin key', url: 'https://developer.hyper3d.ai' },
	stability: { label: 'Stability AI (3D gen)',   placeholder: 'sk-…',           url: 'https://platform.stability.ai/account/keys' },
	replicate: { label: 'Replicate (3D gen)',      placeholder: 'r8_…',           url: 'https://replicate.com/account/api-tokens' },
};

async function loadProviderKeys(host) {
	try {
		const r = await get('/api/user/provider-keys');
		renderProviderKeys(host, r?.keys || {});
	} catch (err) {
		showLoadError(host, {
			title: 'Couldn’t load provider keys',
			body: esc(err?.message || 'Check your connection and try again.'),
		}, () => loadProviderKeys(host));
	}
}

function renderProviderKeys(host, keyStatus) {
	const rows = Object.entries(PROVIDER_META).map(([provider, meta]) => {
		const isSet = !!keyStatus[provider]?.set;
		return `
			<div style="display:flex;align-items:center;gap:12px;padding:12px 0;border-bottom:1px solid var(--nxt-stroke);flex-wrap:wrap" data-provider="${esc(provider)}">
				<div style="flex:1 1 180px;min-width:0">
					<div style="font-size:13.5px;font-weight:500;color:var(--nxt-ink)">${esc(meta.label)}</div>
					<a href="${esc(meta.url)}" target="_blank" rel="noopener" style="font-size:12px;color:var(--nxt-ink-fade);overflow-wrap:anywhere">${esc(meta.url)}</a>
				</div>
				<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;min-width:0">
					${isSet
						? `<span class="dn-tag success">Key set</span>
						   <button class="dn-btn danger" data-action="clear-key" data-provider="${esc(provider)}" style="padding:5px 10px;font-size:12px">Remove</button>`
						: `<input type="password" data-key-input data-provider="${esc(provider)}"
							   placeholder="${esc(meta.placeholder)}"
							   aria-label="${esc(meta.label)} API key"
							   style="background:rgba(255,255,255,0.04);border:1px solid var(--nxt-stroke-strong);border-radius:6px;
							          padding:6px 10px;color:var(--nxt-ink);font-size:12.5px;
						          flex:1 1 200px;min-width:0;max-width:260px;font-family:${MONO}"
							   autocomplete="off" spellcheck="false" />
						   <button class="dn-btn primary" data-action="save-key" data-provider="${esc(provider)}" style="padding:6px 12px;font-size:12.5px">Save</button>`
					}
				</div>
			</div>
		`;
	}).join('');

	host.innerHTML = `
		<div style="padding:0 2px">
			${rows}
			<div style="padding-top:10px;font-size:12px;color:var(--nxt-ink-fade)">
				Keys are encrypted at rest. OpenRouter and Groq are provided free — no key needed.
			</div>
		</div>
	`;

	host.querySelectorAll('[data-action="save-key"]').forEach((btn) => {
		btn.addEventListener('click', async () => {
			const provider = btn.dataset.provider;
			const input = host.querySelector(`[data-key-input][data-provider="${provider}"]`);
			const val = input?.value?.trim();
			if (!val) { toast('Enter a key first'); return; }
			btn.disabled = true;
			btn.textContent = 'Saving…';
			try {
				const r = await patch('/api/user/provider-keys', { [provider]: val });
				renderProviderKeys(host, r?.keys || {});
				toast('Key saved');
			} catch (err) {
				toast(err?.message ? `Failed: ${err.message}` : 'Save failed');
				btn.disabled = false;
				btn.textContent = 'Save';
			}
		});
	});

	host.querySelectorAll('[data-action="clear-key"]').forEach((btn) => {
		btn.addEventListener('click', async () => {
			const provider = btn.dataset.provider;
			if (!confirm(`Remove your ${PROVIDER_META[provider]?.label} key?`)) return;
			btn.disabled = true;
			btn.textContent = 'Removing…';
			try {
				const r = await patch('/api/user/provider-keys', { [provider]: null });
				renderProviderKeys(host, r?.keys || {});
				toast('Key removed');
			} catch (err) {
				toast(err?.message ? `Failed: ${err.message}` : 'Remove failed');
				btn.disabled = false;
				btn.textContent = 'Remove';
			}
		});
	});
}

// ── Profile ───────────────────────────────────────────────────────────────

function renderProfile(host, me) {
	const initials = initialsOf(me);
	const handle = me.username || me.handle || (me.email ? me.email.split('@')[0] : '');
	// Wallet sign-ups get a synthetic `…@wallet.local` address — never surface it as a real email.
	const realEmail = me.email && !/@wallet\.local$/i.test(me.email) ? me.email : '';
	const verified = me.email_verified
		? `<span class="dn-tag success" style="margin-left:8px">verified</span>`
		: `<span class="dn-tag warn" style="margin-left:8px">unverified</span>`;
	const memberSince = me.created_at ? relTime(me.created_at) : '—';
	const planName = me.plan || 'free';

	host.innerHTML = `
		<div style="display:flex;gap:18px;align-items:center;flex-wrap:wrap">
			<div style="
				width:72px;height:72px;border-radius:50%;
				display:grid;place-items:center;
				background:linear-gradient(135deg, rgba(140,143,150,0.4), rgba(100,103,110,0.3));
				color:#fff;font-size:24px;font-weight:600;letter-spacing:-0.01em;
				border:1px solid rgba(255,255,255,0.12);
				flex-shrink:0;
			">${esc(initials)}</div>

			<div style="flex:1;min-width:240px">
				<div style="display:flex;align-items:center;gap:6px;margin-bottom:4px" data-slot="name-row">
					<span data-slot="name-text" style="font-size:20px;font-weight:600;letter-spacing:-0.01em">${esc(me.display_name || handle || 'Unnamed')}</span>
					<button class="dn-btn ghost" data-action="edit-name" title="Edit display name" style="padding:4px 6px;color:var(--nxt-ink-fade)" aria-label="Edit display name">
						<svg width="14" height="14" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M14 3l3 3-9 9H5v-3l9-9z"/></svg>
					</button>
				</div>
				<div style="color:var(--nxt-ink-dim);font-size:13px;display:flex;align-items:center;gap:6px;flex-wrap:wrap" data-slot="username-row">
					${me.username
						? `<span>@${esc(me.username)}</span>
							<button class="dn-btn ghost" data-action="edit-username" title="Edit username" style="padding:2px 5px;color:var(--nxt-ink-fade)" aria-label="Edit username">
								<svg width="12" height="12" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M14 3l3 3-9 9H5v-3l9-9z"/></svg>
							</button>`
						: `<button class="dn-btn ghost" data-action="edit-username" style="padding:2px 8px;font-size:12.5px;color:var(--nxt-accent)">+ Set a username</button>`}
					${realEmail ? `<span style="color:var(--nxt-ink-fade)">·</span><span>${esc(realEmail)}</span>${verified}` : ''}
				</div>
				<div style="color:var(--nxt-ink-fade);font-size:12.5px;margin-top:6px">
					Member since ${esc(memberSince)} · Plan: <a href="/dashboard/monetize" style="color:var(--nxt-accent)">${esc(planName)}</a>
				</div>
			</div>

			<button class="dn-btn ghost" data-action="signout" style="align-self:flex-start">Sign out</button>
		</div>
	`;

	host.querySelector('[data-action="edit-name"]').addEventListener('click', () => {
		startEditName(host, me);
	});
	host.querySelector('[data-action="edit-username"]').addEventListener('click', () => {
		startEditUsername(host, me);
	});
	host.querySelector('[data-action="signout"]').addEventListener('click', async (e) => {
		const btn = e.currentTarget;
		btn.disabled = true;
		btn.textContent = 'Signing out…';
		try {
			await post('/api/auth/logout', {});
		} catch { /* destroy session is best-effort */ }
		window.location.href = '/';
	});
}

function startEditName(host, me) {
	const row = host.querySelector('[data-slot="name-row"]');
	const current = me.display_name || '';
	row.innerHTML = `
		<input type="text" value="${esc(current)}" maxlength="60" aria-label="Display name" style="
			background:rgba(255,255,255,0.04);
			border:1px solid var(--nxt-stroke-strong);
			border-radius:6px;padding:6px 10px;color:var(--nxt-ink);
			font-size:19px;font-weight:600;letter-spacing:-0.01em;
			min-width:200px;max-width:420px;
		" />
		<button class="dn-btn primary" data-action="save-name" style="padding:6px 12px">Save</button>
		<button class="dn-btn ghost" data-action="cancel-name" style="padding:6px 10px">Cancel</button>
	`;
	const input = row.querySelector('input');
	input.focus();
	input.select();

	const cancel = () => renderProfile(host, me);
	const save = async () => {
		const next = input.value.trim();
		if (!next || next === current) return cancel();
		const saveBtn = row.querySelector('[data-action="save-name"]');
		saveBtn.disabled = true;
		saveBtn.textContent = 'Saving…';
		try {
			const r = await patch('/api/auth/profile', { display_name: next });
			const updated = r?.user || { ...me, display_name: next };
			renderProfile(host, { ...me, ...updated, display_name: updated.display_name ?? next });
			toast('Saved');
		} catch (err) {
			toast(err?.message ? `Save failed: ${err.message}` : 'Save failed');
			saveBtn.disabled = false;
			saveBtn.textContent = 'Save';
		}
	};

	row.querySelector('[data-action="save-name"]').addEventListener('click', save);
	row.querySelector('[data-action="cancel-name"]').addEventListener('click', cancel);
	input.addEventListener('keydown', (e) => {
		if (e.key === 'Enter') save();
		else if (e.key === 'Escape') cancel();
	});
}

// Mirrors the server-side `username` validator in api/_lib/validate.js.
const USERNAME_RE = /^[a-zA-Z0-9_-]{3,30}$/;

function startEditUsername(host, me) {
	const row = host.querySelector('[data-slot="username-row"]');
	const current = me.username || '';
	row.innerHTML = `
		<span style="color:var(--nxt-ink-fade)">@</span>
		<input type="text" value="${esc(current)}" maxlength="30" placeholder="username" aria-label="Username"
			autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false" style="
			background:rgba(255,255,255,0.04);
			border:1px solid var(--nxt-stroke-strong);
			border-radius:6px;padding:5px 9px;color:var(--nxt-ink);
			font-size:13px;min-width:160px;max-width:260px;
		" />
		<button class="dn-btn primary" data-action="save-username" style="padding:5px 11px">Save</button>
		<button class="dn-btn ghost" data-action="cancel-username" style="padding:5px 9px">Cancel</button>
		<span data-slot="username-err" role="alert" style="color:var(--nxt-danger);font-size:12px;flex-basis:100%"></span>
	`;
	const input = row.querySelector('input');
	const errEl = row.querySelector('[data-slot="username-err"]');
	input.focus();
	input.select();

	const cancel = () => renderProfile(host, me);
	const save = async () => {
		const next = input.value.trim();
		if (next === current) return cancel();
		if (!USERNAME_RE.test(next)) {
			errEl.textContent = '3–30 characters — letters, numbers, _ or - only.';
			return;
		}
		const saveBtn = row.querySelector('[data-action="save-username"]');
		saveBtn.disabled = true;
		saveBtn.textContent = 'Saving…';
		errEl.textContent = '';
		try {
			const r = await patch('/api/auth/profile', { username: next });
			const updated = r?.user || { ...me, username: next };
			renderProfile(host, { ...me, ...updated, username: updated.username ?? next });
			toast('Username saved');
		} catch (err) {
			errEl.textContent = err?.status === 409
				? 'That username is already taken.'
				: (err?.message ? `Save failed: ${err.message}` : 'Save failed.');
			saveBtn.disabled = false;
			saveBtn.textContent = 'Save';
		}
	};

	row.querySelector('[data-action="save-username"]').addEventListener('click', save);
	row.querySelector('[data-action="cancel-username"]').addEventListener('click', cancel);
	input.addEventListener('keydown', (e) => {
		if (e.key === 'Enter') save();
		else if (e.key === 'Escape') cancel();
	});
}

// ── Wallets ───────────────────────────────────────────────────────────────

// The SNS panel is derived from the wallet list, so it has to re-render every
// time that list changes. Captured once at boot; every later loadWallets()
// (link, unlink, primary change) refreshes the domains through it, instead of
// leaving "No Solana wallets linked" on screen after the user just linked one.
let snsPanelHost = null;

async function loadWallets(host) {
	try {
		const r = await get('/api/auth/wallets');
		const wallets = Array.isArray(r?.wallets) ? r.wallets : [];
		renderWallets(host, wallets);
		if (snsPanelHost) renderSns(snsPanelHost, wallets);
		return wallets;
	} catch (err) {
		showLoadError(host, {
			title: 'Couldn’t load wallets',
			body: esc(err?.message || 'Check your connection and try again.'),
		}, () => loadWallets(host));
		return [];
	}
}

// Solana wallet providers, in the order the rest of the platform probes them
// (see public/studio/launch-panel.js).
function solanaProvider() {
	return window.phantom?.solana || window.solana || window.backpack || window.solflare || null;
}

// Link a Solana wallet to this account with SIWS: the wallet signs a server-issued
// message, so the link proves ownership without ever touching funds. `takeover`
// moves a link that currently sits on another account, which the server only
// allows once the same signature has proved ownership.
async function linkSolanaWallet(provider, { takeover = false } = {}) {
	const res = await provider.connect();
	const address = res?.publicKey?.toString?.();
	if (!address) throw new Error('Wallet did not return an address');

	const nonce = await post('/api/auth/wallets/nonce-solana', { address, chainId: 'mainnet' });
	const signed = await provider.signMessage(new TextEncoder().encode(nonce.message), 'utf8');
	const signature = btoa(String.fromCharCode(...signed.signature));

	await post('/api/auth/wallets/link-solana', { message: nonce.message, signature, takeover });
	return address;
}

// A user declining the wallet prompt is a choice, not a failure worth shouting about.
const isUserRejection = (err) => err?.code === 4001 || /reject|denied|cancel/i.test(err?.message || '');

async function startWalletLink(host, btn) {
	const provider = solanaProvider();
	if (!provider) {
		toast('No Solana wallet detected. Install Phantom, then try again.');
		window.open('https://phantom.app/', '_blank', 'noopener');
		return;
	}
	const label = btn.textContent;
	btn.disabled = true;
	btn.textContent = 'Check your wallet…';
	try {
		let address;
		try {
			address = await linkSolanaWallet(provider);
		} catch (err) {
			// The address is already linked elsewhere; the signature just proved it is
			// this user's, so offer the move rather than dead-ending on the error.
			if (err?.body?.takeover_available !== true) throw err;
			if (!confirm('That wallet is linked to another account. Move it to this one?')) return;
			address = await linkSolanaWallet(provider, { takeover: true });
		}
		toast(`Linked ${truncMid(address, 6, 4)}`);
		await loadWallets(host);
	} catch (err) {
		if (!isUserRejection(err)) toast(err?.message ? `Link failed: ${err.message}` : 'Wallet link failed');
	} finally {
		btn.disabled = false;
		btn.textContent = label;
	}
}

function renderWallets(host, wallets) {
	if (wallets.length === 0) {
		host.innerHTML = `
			<div class="dn-empty">
				<h3>No wallets linked</h3>
				<p>Link a wallet so you can claim royalties, pay for subscriptions, or sign as you.</p>
				<button class="dn-btn primary" type="button" data-action="link-wallet">+ Link wallet</button>
			</div>`;
		host.querySelector('[data-action="link-wallet"]').addEventListener('click', (e) => startWalletLink(host, e.currentTarget));
		return;
	}

	const rows = wallets.map((w) => {
		const isPrimary = !!w.is_primary;
		const star = isPrimary
			? `<svg width="13" height="13" viewBox="0 0 20 20" fill="#c8cad0" stroke="#9a9da4" stroke-width="1" style="margin-right:4px;flex-shrink:0"><path d="M10 2l2.4 5.4 5.9.6-4.4 4 1.3 5.9L10 14.7 4.8 17.9l1.3-5.9-4.4-4 5.9-.6L10 2z"/></svg>`
			: '';
		return `
			<tr data-address="${esc(w.address)}">
				<td style="padding:11px 12px;white-space:nowrap">
					<span style="display:inline-flex;align-items:center">${star}${chainChip(w)}</span>
				</td>
				<td style="padding:11px 12px">
					<button class="dn-copy" data-copy="${esc(w.address)}" title="${esc(w.address)} · click to copy" aria-label="Copy wallet address ${esc(w.address)}" style="
						font-family:${MONO};font-size:12.5px;
						background:transparent;border:none;color:var(--nxt-ink);
						padding:0;cursor:pointer;letter-spacing:0.01em;
					">${esc(truncMid(w.address, 8, 6))}</button>
				</td>
				<td style="padding:11px 12px;color:var(--nxt-ink-dim);font-size:12.5px;white-space:nowrap">${esc(w.created_at ? relTime(w.created_at) : '—')}</td>
				<td style="padding:11px 12px;color:var(--nxt-ink-dim);font-size:12.5px;white-space:nowrap">
					${isPrimary ? '<span class="dn-tag" style="background:rgba(200,202,208,0.12);border-color:rgba(200,202,208,0.28);color:#c8cad0">primary</span>' : ''}
				</td>
				<td style="padding:11px 12px;text-align:right;white-space:nowrap">
					<div style="display:inline-flex;gap:6px">
						${isPrimary ? '' : `<button class="dn-btn" data-action="make-primary" data-address="${esc(w.address)}" style="padding:5px 10px;font-size:12px">Make primary</button>`}
						<button class="dn-btn danger" data-action="unlink" data-address="${esc(w.address)}" style="padding:5px 10px;font-size:12px">Disconnect</button>
					</div>
				</td>
			</tr>
		`;
	}).join('');

	host.innerHTML = `
		<div style="overflow-x:auto;border:1px solid var(--nxt-stroke);border-radius:var(--nxt-radius-sm)">
			<table style="width:100%;border-collapse:collapse">
				<thead>
					<tr style="background:rgba(255,255,255,0.02);text-align:left">
						<th scope="col" style="padding:9px 12px;font-size:11.5px;color:var(--nxt-ink-fade);font-weight:500;text-transform:uppercase;letter-spacing:0.04em">Chain</th>
						<th scope="col" style="padding:9px 12px;font-size:11.5px;color:var(--nxt-ink-fade);font-weight:500;text-transform:uppercase;letter-spacing:0.04em">Address</th>
						<th scope="col" style="padding:9px 12px;font-size:11.5px;color:var(--nxt-ink-fade);font-weight:500;text-transform:uppercase;letter-spacing:0.04em">Linked</th>
						<th scope="col" style="padding:9px 12px;font-size:11.5px;color:var(--nxt-ink-fade);font-weight:500;text-transform:uppercase;letter-spacing:0.04em"></th>
						<th scope="col" style="padding:9px 12px"><span style="position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)">Actions</span></th>
					</tr>
				</thead>
				<tbody>${rows}</tbody>
			</table>
		</div>
	`;

	host.querySelectorAll('.dn-copy').forEach((btn) => {
		btn.addEventListener('click', () => copyToClipboard(btn.dataset.copy));
	});
	host.querySelectorAll('[data-action="unlink"]').forEach((btn) => {
		btn.addEventListener('click', async () => {
			const addr = btn.dataset.address;
			if (!confirm(`Disconnect ${truncMid(addr, 6, 4)} from this account?`)) return;
			btn.disabled = true;
			btn.textContent = 'Disconnecting…';
			try {
				await del(`/api/auth/wallets/${encodeURIComponent(addr)}`);
				toast('Wallet disconnected');
				// Re-read rather than splicing the row out: dropping a wallet can move
				// the primary flag and always changes what the SNS panel should show.
				await loadWallets(host);
			} catch (err) {
				toast(err?.message ? `Failed: ${err.message}` : 'Disconnect failed');
				btn.disabled = false;
				btn.textContent = 'Disconnect';
			}
		});
	});
	host.querySelectorAll('[data-action="make-primary"]').forEach((btn) => {
		btn.addEventListener('click', async () => {
			const addr = btn.dataset.address;
			btn.disabled = true;
			btn.textContent = 'Setting…';
			try {
				await post('/api/auth/wallets/primary', { address: addr });
				toast('Primary wallet updated');
				await loadWallets(host);
			} catch (err) {
				toast(err?.message ? `Failed: ${err.message}` : 'Couldn’t set primary');
				btn.disabled = false;
				btn.textContent = 'Make primary';
			}
		});
	});
}

// ── SNS ───────────────────────────────────────────────────────────────────

// A resolver that answered for some wallets and failed for others leaves the
// table honest but incomplete; name the gap and offer the retry rather than
// letting the unchecked wallets read as "no domain".
function appendSnsFailureNotice(rowsHost, failures, lookups, host, wallets) {
	if (!failures.length) return;
	rowsHost.insertAdjacentHTML(
		'beforeend',
		`<div role="status" style="padding:10px 2px 0;font-size:12px;color:var(--nxt-ink-fade)">
			${failures.length} of ${lookups.length} wallets could not be checked against the SNS resolver.
			<button class="dn-btn ghost" type="button" data-action="retry-sns" style="padding:2px 8px;font-size:12px">Retry</button>
		</div>`,
	);
	rowsHost.querySelector('[data-action="retry-sns"]')
		.addEventListener('click', () => renderSns(host, wallets));
}

async function renderSns(host, wallets) {
	const solanaWallets = wallets.filter((w) => chainKey(w) === 'solana');
	if (solanaWallets.length === 0) {
		host.innerHTML = `
			<div class="dn-empty" style="padding:32px 24px">
				<h3>No Solana wallets linked</h3>
				<p>SNS .sol domains live on Solana — link a Solana wallet to surface the domains it owns.</p>
			</div>`;
		return;
	}

	host.innerHTML = `<div data-slot="sns-rows">${skelStack(solanaWallets.length)}</div>`;
	const rowsHost = host.querySelector('[data-slot="sns-rows"]');

	const lookups = await Promise.all(
		solanaWallets.map(async (w) => {
			try {
				const r = await get(`/api/sns?address=${encodeURIComponent(w.address)}`);
				return { wallet: w, domain: r?.data?.name || null, failed: false };
			} catch (err) {
				return { wallet: w, domain: null, failed: true, error: err };
			}
		}),
	);

	const hits = lookups.filter((l) => l.domain);
	const failures = lookups.filter((l) => l.failed);

	// A resolver outage is not the same answer as "you own no domains". Saying
	// the second when we mean the first tells the user to go buy a domain they
	// may already have, so an all-failed lookup gets the retry, not the empty.
	if (hits.length === 0 && failures.length === lookups.length) {
		showLoadError(rowsHost, {
			title: 'Couldn’t check your .sol domains',
			body: esc(failures[0]?.error?.message || 'The SNS resolver did not answer. Try again in a moment.'),
		}, () => renderSns(host, wallets));
		return;
	}

	// Some wallets answered and none of them owns a domain. Say so, but never
	// let a wallet we failed to check pass silently as one with no domain.
	if (hits.length === 0) {
		rowsHost.innerHTML = `
			<div class="dn-empty" style="padding:32px 24px">
				<h3>No primary .sol domains found</h3>
				<p>Set one of your wallets' primary .sol domain on-chain and it shows up here automatically.</p>
				<a class="dn-btn" href="/vanity-wallet">+ Register a domain</a>
			</div>`;
		appendSnsFailureNotice(rowsHost, failures, lookups, host, wallets);
		return;
	}

	const rows = hits.map((h) => `
		<tr>
			<td style="padding:11px 12px">
				<span style="font-family:${MONO};font-size:13px;color:var(--nxt-ink)">${esc(h.domain)}</span>
			</td>
			<td style="padding:11px 12px">
				<button class="dn-copy" data-copy="${esc(h.wallet.address)}" title="${esc(h.wallet.address)}" aria-label="Copy wallet address ${esc(h.wallet.address)}" style="
					font-family:${MONO};font-size:12.5px;
					background:transparent;border:none;color:var(--nxt-ink-dim);
					padding:0;cursor:pointer;
				">${esc(truncMid(h.wallet.address, 6, 6))}</button>
			</td>
			<td style="padding:11px 12px">
				<span class="dn-tag success">Active</span>
			</td>
			<td style="padding:11px 12px;text-align:right">
				<a class="dn-btn ghost" href="https://www.sns.id/domain/${encodeURIComponent(h.domain.replace(/\\.sol$/, ''))}" target="_blank" rel="noopener" style="padding:5px 10px;font-size:12px">Manage ↗</a>
			</td>
		</tr>
	`).join('');

	rowsHost.innerHTML = `
		<div style="overflow-x:auto;border:1px solid var(--nxt-stroke);border-radius:var(--nxt-radius-sm)">
			<table style="width:100%;border-collapse:collapse">
				<thead>
					<tr style="background:rgba(255,255,255,0.02);text-align:left">
						<th scope="col" style="padding:9px 12px;font-size:11.5px;color:var(--nxt-ink-fade);font-weight:500;text-transform:uppercase;letter-spacing:0.04em">Domain</th>
						<th scope="col" style="padding:9px 12px;font-size:11.5px;color:var(--nxt-ink-fade);font-weight:500;text-transform:uppercase;letter-spacing:0.04em">Wallet</th>
						<th scope="col" style="padding:9px 12px;font-size:11.5px;color:var(--nxt-ink-fade);font-weight:500;text-transform:uppercase;letter-spacing:0.04em">Status</th>
						<th scope="col" style="padding:9px 12px"><span style="position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)">Actions</span></th>
					</tr>
				</thead>
				<tbody>${rows}</tbody>
			</table>
		</div>
	`;

	appendSnsFailureNotice(rowsHost, failures, lookups, host, wallets);

	rowsHost.querySelectorAll('.dn-copy').forEach((btn) => {
		btn.addEventListener('click', () => copyToClipboard(btn.dataset.copy));
	});
}

// ── Delegation ────────────────────────────────────────────────────────────

// Agents available as delegation targets — captured on load so the console can
// build its picker without a second fetch.
let delegationAgents = [];

async function loadDelegations(host, consoleHost) {
	try {
		const r = await get('/api/agents');
		const agents = Array.isArray(r?.agents) ? r.agents : [];
		delegationAgents = agents;
		if (consoleHost) consoleHost.hidden = true;
		if (agents.length === 0) {
			host.innerHTML = `
				<div class="dn-empty" style="padding:32px 24px">
					<h3>No agents to delegate</h3>
					<p>Create an agent first, then return here to let another agent answer on its behalf.</p>
					<a class="dn-btn" href="/dashboard/avatars">Create an agent →</a>
				</div>`;
			return;
		}

		// The table is a preview of the newest agents; the console's picker holds
		// every one of them, and the count below says so rather than letting the
		// cap read as "these are all the agents you have".
		const PREVIEW_LIMIT = 8;
		const rows = agents.slice(0, PREVIEW_LIMIT).map((a) => `
			<tr>
				<td style="padding:11px 12px">
					<div style="font-size:13.5px;color:var(--nxt-ink);font-weight:500">${esc(a.name || a.display_name || 'Unnamed agent')}</div>
					<div style="font-family:${MONO};font-size:11.5px;color:var(--nxt-ink-fade);margin-top:2px">${esc(truncMid(a.id, 8, 4))}</div>
				</td>
				<td style="padding:11px 12px;color:var(--nxt-ink-dim);font-size:12.5px">
					${a.wallet_address ? `<span style="font-family:${MONO}">${esc(truncMid(a.wallet_address, 6, 6))}</span>` : '<span style="color:var(--nxt-ink-fade)">no delegate</span>'}
				</td>
				<td style="padding:11px 12px;text-align:right">
					<button class="dn-btn ghost" type="button" data-action="configure-delegation" data-agent-id="${esc(a.id)}" style="padding:5px 10px;font-size:12px">Configure →</button>
				</td>
			</tr>
		`).join('');

		host.innerHTML = `
			<div style="overflow-x:auto;border:1px solid var(--nxt-stroke);border-radius:var(--nxt-radius-sm)">
				<table style="width:100%;border-collapse:collapse">
					<thead>
						<tr style="background:rgba(255,255,255,0.02);text-align:left">
							<th scope="col" style="padding:9px 12px;font-size:11.5px;color:var(--nxt-ink-fade);font-weight:500;text-transform:uppercase;letter-spacing:0.04em">Agent</th>
							<th scope="col" style="padding:9px 12px;font-size:11.5px;color:var(--nxt-ink-fade);font-weight:500;text-transform:uppercase;letter-spacing:0.04em">Delegate wallet</th>
							<th scope="col" style="padding:9px 12px"><span style="position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)">Actions</span></th>
						</tr>
					</thead>
					<tbody>${rows}</tbody>
				</table>
			</div>
			${agents.length > PREVIEW_LIMIT
				? `<div style="padding:10px 2px 0;font-size:12px;color:var(--nxt-ink-fade)">
						Showing the ${PREVIEW_LIMIT} most recent of ${agents.length} agents.
						<button class="dn-btn ghost" type="button" data-action="open-delegation-console" style="padding:2px 8px;font-size:12px">Pick another in the console</button>
					</div>`
				: ''}
		`;
	} catch (err) {
		showLoadError(host, {
			title: 'Couldn’t load agents',
			body: esc(err?.message || 'Check your connection and try again.'),
		}, () => loadDelegations(host, consoleHost));
	}
}

// ── Delegation console ──────────────────────────────────────────────────────
// Real, working delegation: pick one of your agents, send it a prompt, and the
// platform runs a live LLM turn AS that agent (POST /api/agent-delegate) and
// streams the answer back here. Replaces the old dead `#delegation` anchors.

function openDelegationConsole(host, preselectAgentId) {
	if (!host) return;
	if (host.dataset.built !== '1') {
		const options = delegationAgents
			.map(
				(a) =>
					`<option value="${esc(a.id)}">${esc(a.name || a.display_name || 'Unnamed agent')}</option>`,
			)
			.join('');
		host.innerHTML = `
			<form data-deleg-form style="margin-top:14px;border:1px solid var(--nxt-stroke);border-radius:var(--nxt-radius-sm);padding:16px;display:flex;flex-direction:column;gap:12px">
				<div style="display:flex;flex-direction:column;gap:6px">
					<label style="font-size:11.5px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.04em">Delegate to</label>
					<select data-deleg-agent style="width:100%;background:rgba(255,255,255,0.04);border:1px solid var(--nxt-stroke-strong);border-radius:6px;padding:8px 10px;color:var(--nxt-ink);font-size:13.5px;font-family:inherit">${options}</select>
				</div>
				<div style="display:flex;flex-direction:column;gap:6px">
					<label style="font-size:11.5px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.04em">Message</label>
					<textarea data-deleg-message rows="3" maxlength="8000" placeholder="What should this agent answer on your behalf?" style="width:100%;resize:vertical;background:rgba(255,255,255,0.04);border:1px solid var(--nxt-stroke-strong);border-radius:6px;padding:8px 10px;color:var(--nxt-ink);font-size:13.5px;font-family:inherit;line-height:1.55"></textarea>
				</div>
				<div style="display:flex;gap:10px;align-items:center">
					<button class="dn-btn primary" type="submit" data-deleg-run>Run delegation</button>
					<button class="dn-btn ghost" type="button" data-deleg-close>Close</button>
				</div>
				<div data-deleg-result></div>
			</form>`;
		const form = host.querySelector('[data-deleg-form]');
		form.addEventListener('submit', (e) => {
			e.preventDefault();
			runDelegation(host);
		});
		host.querySelector('[data-deleg-close]').addEventListener('click', () => {
			host.hidden = true;
		});
		host.dataset.built = '1';
	}

	host.hidden = false;
	const select = host.querySelector('[data-deleg-agent]');
	if (preselectAgentId && select) select.value = preselectAgentId;
	host.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
	host.querySelector('[data-deleg-message]')?.focus();
}

async function runDelegation(host) {
	const select = host.querySelector('[data-deleg-agent]');
	const messageEl = host.querySelector('[data-deleg-message]');
	const runBtn = host.querySelector('[data-deleg-run]');
	const result = host.querySelector('[data-deleg-result]');
	const toAgentId = select?.value;
	const message = (messageEl?.value || '').trim();

	if (!toAgentId) {
		result.innerHTML = `<div role="alert" style="color:var(--nxt-danger);font-size:13px">Pick an agent to delegate to.</div>`;
		return;
	}
	if (!message) {
		result.innerHTML = `<div role="alert" style="color:var(--nxt-danger);font-size:13px">Enter a message for the agent to answer.</div>`;
		messageEl?.focus();
		return;
	}

	runBtn.disabled = true;
	runBtn.textContent = 'Running…';
	result.innerHTML = `<div class="dn-skeleton" style="height:64px"></div>`;
	try {
		const out = await post('/api/agent-delegate', { toAgentId, message });
		result.innerHTML = `
			<div style="border:1px solid var(--nxt-stroke);border-radius:var(--nxt-radius-sm);padding:13px;background:rgba(255,255,255,0.02)">
				<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
					<span style="font-size:11.5px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.04em">Response</span>
					${out?.model ? `<span class="dn-tag" style="font-family:${MONO};font-size:11px">${esc(out.model)}</span>` : ''}
				</div>
				<div style="font-size:13.5px;color:var(--nxt-ink);line-height:1.6;white-space:pre-wrap">${esc(out?.response || '(empty response)')}</div>
			</div>`;
	} catch (err) {
		const status = err?.status;
		const msg =
			status === 429
				? 'Delegation rate limit reached — wait a moment and try again.'
				: status === 404
					? 'That agent could not be found. Pick another.'
					: status === 503
						? 'Delegation is temporarily unavailable. Try again shortly.'
						: err?.message || 'Delegation failed. Try again.';
		result.innerHTML = `<div role="alert" style="border:1px solid color-mix(in srgb, var(--nxt-danger) 40%, transparent);background:color-mix(in srgb, var(--nxt-danger) 12%, transparent);color:var(--nxt-danger);border-radius:var(--nxt-radius-sm);padding:12px;font-size:13px;line-height:1.5">${esc(msg)}</div>`;
	} finally {
		runBtn.disabled = false;
		runBtn.textContent = 'Run delegation';
	}
}

// ── Action log ────────────────────────────────────────────────────────────

let actionsCursor = null;

async function loadActions(host, append = false) {
	try {
		const qs = new URLSearchParams({ limit: '50' });
		if (append && actionsCursor) qs.set('cursor', actionsCursor);
		const r = await get(`/api/audit-log?${qs.toString()}`);
		const items = Array.isArray(r?.items) ? r.items
			: Array.isArray(r?.events) ? r.events
			: Array.isArray(r) ? r
			: [];
		actionsCursor = r?.next_cursor || r?.cursor || null;
		if (items.length === 0 && !append) {
			host.innerHTML = `
				<div class="dn-empty">
					<h3>Audit log is empty</h3>
					<p>Audit log will appear here as you make changes — wallet links, key issuance, sign-ins.</p>
				</div>`;
			return;
		}
		renderActions(host, items, append);
	} catch (err) {
		if (append) {
			// A failed "load older" shouldn't wipe the rows already on screen —
			// surface the failure on the load-more control instead.
			const more = host.querySelector('[data-slot="actions-more"]');
			if (more) {
				more.innerHTML = `<button class="dn-btn" data-action="load-more">Retry loading older</button>`;
				more.querySelector('[data-action="load-more"]').addEventListener('click', () => loadActions(host, true));
			}
			toast(err?.message ? `Couldn’t load older: ${err.message}` : 'Couldn’t load older entries');
			return;
		}
		showLoadError(host, {
			title: 'Couldn’t load audit log',
			body: esc(err?.message || 'Check your connection and try again.'),
		}, () => loadActions(host));
	}
}

function renderActions(host, items, append) {
	const rowsHtml = items.map((it) => {
		const when = it.created_at || it.ts || it.timestamp;
		const action = it.action || it.event || '';
		const desc = it.description || it.message || it.resource_id || it.resourceId || '';
		const ip = it.ip || it.client_ip || '';
		const ua = it.user_agent || it.agent || it.ua || '';
		const cat = it.category || categoryOf(action);
		return `
			<tr>
				<td style="padding:9px 12px;color:var(--nxt-ink-dim);font-size:12px;white-space:nowrap">${when ? esc(relTime(when)) : '—'}</td>
				<td style="padding:9px 12px"><span class="dn-tag">${esc(cat)}</span></td>
				<td style="padding:9px 12px;color:var(--nxt-ink);font-size:12.5px">
					<span style="font-family:${MONO};color:var(--nxt-ink-dim);font-size:11.5px">${esc(action)}</span>
					${desc ? `<div style="color:var(--nxt-ink-dim);font-size:12px;margin-top:2px">${esc(String(desc).slice(0, 120))}</div>` : ''}
				</td>
				<td style="padding:9px 12px;color:var(--nxt-ink-fade);font-size:11.5px;font-family:${MONO};white-space:nowrap">${esc(truncMid(ip, 8, 4))}</td>
				<td style="padding:9px 12px;color:var(--nxt-ink-fade);font-size:11.5px;max-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${esc(ua)}">${esc(String(ua).slice(0, 28))}</td>
			</tr>
		`;
	}).join('');

	if (append) {
		const tbody = host.querySelector('tbody');
		if (tbody) tbody.insertAdjacentHTML('beforeend', rowsHtml);
	} else {
		host.innerHTML = `
			<div style="overflow-x:auto;border:1px solid var(--nxt-stroke);border-radius:var(--nxt-radius-sm)">
				<table style="width:100%;border-collapse:collapse">
					<thead>
						<tr style="background:rgba(255,255,255,0.02);text-align:left">
							<th scope="col" style="padding:9px 12px;font-size:11.5px;color:var(--nxt-ink-fade);font-weight:500;text-transform:uppercase;letter-spacing:0.04em">When</th>
							<th scope="col" style="padding:9px 12px;font-size:11.5px;color:var(--nxt-ink-fade);font-weight:500;text-transform:uppercase;letter-spacing:0.04em">Category</th>
							<th scope="col" style="padding:9px 12px;font-size:11.5px;color:var(--nxt-ink-fade);font-weight:500;text-transform:uppercase;letter-spacing:0.04em">Event</th>
							<th scope="col" style="padding:9px 12px;font-size:11.5px;color:var(--nxt-ink-fade);font-weight:500;text-transform:uppercase;letter-spacing:0.04em">IP</th>
							<th scope="col" style="padding:9px 12px;font-size:11.5px;color:var(--nxt-ink-fade);font-weight:500;text-transform:uppercase;letter-spacing:0.04em">Agent</th>
						</tr>
					</thead>
					<tbody>${rowsHtml}</tbody>
				</table>
			</div>
			<div data-slot="actions-more" style="display:flex;justify-content:center;padding:14px 0 4px"></div>
		`;
	}

	const more = host.querySelector('[data-slot="actions-more"]');
	if (more) {
		if (actionsCursor) {
			more.innerHTML = `<button class="dn-btn" data-action="load-more">Load older</button>`;
			more.querySelector('[data-action="load-more"]').addEventListener('click', (e) => {
				e.currentTarget.disabled = true;
				e.currentTarget.textContent = 'Loading…';
				loadActions(host, true);
			});
		} else {
			more.innerHTML = '';
		}
	}
}