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(avatar-chat): implement thought bubble z-index layering and ensure it renders above UI elements

nirholasc106b03c13ea
diff --git a/specs/EMBED_SPEC.md b/specs/EMBED_SPEC.md
index adfe752b0..ea8aedbdd 100644
--- a/specs/EMBED_SPEC.md
+++ b/specs/EMBED_SPEC.md
@@ -278,6 +278,15 @@ agent-3d {
}
```
+**Transparent background theming** — when `background="transparent"`, the canvas composites over the host page. The thought bubble gains a subtle border and tighter shadow to stay visually distinct against both white and dark host pages (no override needed). The chat glass panel (`--agent-surface`) defaults to dark; on a light host page, override it to match your theme:
+
+```css
+agent-3d {
+ --agent-surface: rgba(255, 255, 255, 0.92);
+ --agent-on-surface: #1a1a2e;
+}
+```
+
## Shadow DOM
All chrome lives inside the element's shadow root. The host page's CSS cannot leak in (except via the custom properties above). The shadow root is open — DevTools can inspect, power users can `el.shadowRoot.querySelector(...)`.
diff --git a/src/CLAUDE.md b/src/CLAUDE.md
index c58629611..6584f257b 100644
--- a/src/CLAUDE.md
+++ b/src/CLAUDE.md
@@ -44,6 +44,9 @@ The viewer doesn't know about agents. The agent layer wraps the viewer through [
### Web component boundary
- [element.js](element.js) — `<agent-3d>` custom element. IntersectionObserver lazy boot unless `eager`. See attribute list in [specs/EMBED_SPEC.md](../specs/EMBED_SPEC.md).
+
+ **Avatar-chat mode** (default on): vertical chrome layout with `.avatar-anchor` transparent window. Thought bubble appears above the anchor. Walk animation (`walk` clip) plays during `brain:stream` events. Disabled via `avatar-chat="off"` attribute. New public methods: `enableAvatarChat()`, `disableAvatarChat()`.
+
#### Avatar-chat methods (element.js)
- `enableAvatarChat()` — re-enable inline avatar layout + walk + bubble (default on)
@@ -169,6 +172,8 @@ Z-rotation = `(curiosity*12 + empathy*9 + concern*4)` degrees. X-rotation (lean)
- **Skill `owned-only` trust** compares `manifest.author` with `ownerAddress` from element attr or backend. Mismatch → skill load throws.
- **[viewer.js](viewer.js) is the biggest file in `src/` (~1.2k lines).** Further module split is tracked in [prompts/scalability/03-module-split.md](../prompts/scalability/03-module-split.md). Don't start that refactor ad-hoc.
- **`memory.recall()` is substring search.** No embeddings yet.
+- **`_onStreamChunk()` debounce**: The walk animation uses a 600ms debounce. Calling `_stopWalkAnimation()` directly will interrupt it. Only call `_stopWalkAnimation()` in response to `brain:thinking { thinking: false }` or deliberate teardown.
+- **Thought bubble RAF queue**: `_streamToBubble()` buffers chunks and flushes on the next animation frame. Don't read `_thoughtTextEl.textContent` synchronously after calling `_streamToBubble()` — it won't reflect the latest buffer yet.
- **`brain:stream` fires per token** — at 50+ tokens/sec this is frequent. All handlers must be O(1) and RAF-batched. Never do synchronous network or heavy DOM work in a `brain:stream` handler.
- **Walk animation requires walk+idle clips preloaded** — if `animationManager.isLoaded('walk')` returns false, `_onStreamChunk()` silently skips the walk. Ensure the preload strategy (prompt 29) is implemented before relying on walk-on-stream.
- **Throttle policies on `protocol.emit()`.** Animation-driving events are shaped by default: `gesture` (leading-edge throttle, 600 ms), `emote` (coalesce by `payload.trigger` with max-weight merge, 150 ms window), `look-at` (trailing debounce, 100 ms). All other types pass through. Override per-instance with `protocol.setThrottlePolicy(type, policy)` where `policy` is `{ mode: 'passthrough' }`, `{ mode: 'throttle', leading: true, intervalMs }`, `{ mode: 'debounce', intervalMs }`, or `{ mode: 'coalesce', windowMs, key, merge }`. Inspect suppressed events via `protocol.droppedCount(type)`. Passthrough events still go through the burst rate-limiter as a last-resort cascade guard.
@@ -181,7 +186,7 @@ Z-rotation = `(curiosity*12 + empathy*9 + concern*4)` degrees. X-rotation (lean)
- [editor/](editor/) — GLB export + material editor exist, agent-system integration minimal
- ERC-8004 reputation/validation — hooked but no UI
- Memory `encrypted-ipfs` mode — stub
-- Chat streaming — implemented but not tested in all edge cases
+- `avatar-chat` inline layout — fully wired. Walk clip, thought bubble, stream events all connected. See `prompts/avatar-chat/` for remaining polish items.
- Privy integration — functions exist, no full auth flow in element.js
- Avatar Creator save-to-account — may not persist in all flows
- Avatar Creator now wraps the Ready Player Me iframe. Configure the subdomain via `VITE_RPM_SUBDOMAIN`; falls back to `demo.readyplayer.me`.
diff --git a/src/element.js b/src/element.js
index 621b6a1c7..452e11369 100644
--- a/src/element.js
+++ b/src/element.js
@@ -190,7 +190,7 @@ const BASE_STYLE = `
display: flex;
align-items: center;
gap: 5px;
- z-index: 4;
+ z-index: 16;
}
.thought-bubble::after {
content: '';
@@ -253,6 +253,9 @@ const BASE_STYLE = `
.msg.curiosity { border-left-color: rgba(59,130,246,0.7); background: rgba(59,130,246,0.05); }
.msg .role { opacity: 0.55; font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; }
.msg .body { white-space: pre-wrap; }
+ .msg .body code { font-family: monospace; background: rgba(255,255,255,0.08); padding: 1px 4px; border-radius: 4px; font-size: 12px; }
+ .msg .body strong { font-weight: 700; }
+ .msg .body em { font-style: italic; opacity: 0.9; }
.msg.streaming .body::after { content: '▋'; opacity: 1; animation: blink-cursor 0.7s step-end infinite; margin-left: 2px; }
@keyframes blink-cursor { 0%, 100% { opacity: 1; } 50% { opacity: 0; } }
/* Suggestion chips when the conversation is empty */
@@ -376,6 +379,10 @@ const BASE_STYLE = `
:host([name-plate="off"]) .name-plate { display: none; }
/* Background variants — set on :host so the canvas composites over them. */
:host([background="transparent"]) { background: transparent; }
+ :host([background="transparent"]) .thought-bubble {
+ border: 1px solid rgba(0, 0, 0, 0.08);
+ box-shadow: 0 4px 24px rgba(0, 0, 0, 0.18), 0 1px 3px rgba(0, 0, 0, 0.12);
+ }
:host([background="dark"]) { background: #0b0d10; }
:host([background="light"]) { background: #f5f5f5; }
:host([background="light"]) .name-plate {
@@ -458,6 +465,21 @@ const BASE_STYLE = `
:host([mode="floating"]) .avatar-anchor {
min-height: 60px;
}
+ /* Section mode — constrain chat width on wide containers */
+ :host([mode="section"]) .chat {
+ max-width: 600px;
+ }
+ :host([mode="section"]) .input-row {
+ max-width: 600px;
+ }
+ /* Fullscreen mode — centre the chrome column on large monitors */
+ :host([mode="fullscreen"]) .chrome {
+ max-width: 800px;
+ width: 800px;
+ left: 0;
+ right: 0;
+ margin: 0 auto;
+ }
`;
class Agent3DElement extends HTMLElement {
@@ -1690,6 +1712,7 @@ class Agent3DElement extends HTMLElement {
this._thoughtTextEl.textContent = t;
}
+ // Buffers chunk and flushes to DOM on the next animation frame (RAF-batched).
_streamToBubble(chunk) {
if (!this._thoughtBubbleEl || !this._thoughtTextEl) return;
this._thoughtBubbleEl.dataset.active = 'true';
@@ -1711,10 +1734,25 @@ class Agent3DElement extends HTMLElement {
this._thoughtBubbleEl.setAttribute('aria-label', '');
this._thoughtBubbleEl.dataset.active = 'false';
this._thoughtBubbleEl.dataset.streaming = 'false';
+ this._thoughtBubbleEl.dataset.error = 'false';
if (this._thoughtTextEl) this._thoughtTextEl.textContent = '';
}, 200);
}
+ _showBubbleError(message = 'Something went wrong') {
+ if (!this._thoughtBubbleEl || this.getAttribute('avatar-chat') === 'off') return;
+ clearTimeout(this._bubbleClearTimer);
+ this._thoughtBubbleEl.dataset.active = 'true';
+ this._thoughtBubbleEl.dataset.streaming = 'true';
+ this._thoughtBubbleEl.dataset.error = 'true';
+ if (this._thoughtTextEl) this._thoughtTextEl.textContent = message;
+ this._bubbleClearTimer = setTimeout(() => {
+ this._thoughtBubbleEl.dataset.error = 'false';
+ this._clearThoughtBubble();
+ }, 3000);
+ }
+
+ // Disables/re-enables the input and updates placeholder during LLM turns.
_setBusy(busy) {
if (!this._inputEl) return;
this._inputEl.disabled = busy;
@@ -2053,6 +2091,8 @@ class Agent3DElement extends HTMLElement {
this._isWalking = false;
this._bubbleBuffer = '';
this._bubbleRafPending = false;
+ clearTimeout(this._bubbleClearTimer);
+ this._bubbleClearTimer = null;
this._streamingMsgEl = null;
this._streamingChatBuffer = '';
this._streamingChatRafPending = false;
@@ -2104,7 +2144,12 @@ class Agent3DElement extends HTMLElement {
await this._runtime.send(text, { voice: opts.voice ?? this.hasAttribute('voice') });
} catch (err) {
this._stopWalkAnimation();
- this._clearThoughtBubble();
+ const msg = err?.message?.includes('429')
+ ? 'Too many requests — try again'
+ : err?.message?.includes('busy')
+ ? 'Still thinking…'
+ : 'Connection error';
+ this._showBubbleError(msg);
this._setBusy(false);
protocol.emit({
type: ACTION_TYPES.EMOTE,
@@ -2213,16 +2258,17 @@ class Agent3DElement extends HTMLElement {
/**
* Enable the inline avatar-in-chat layout.
- * Avatar walks during LLM streaming, thought bubble shows response text.
- * @returns {void}
+ * Avatar walks during LLM streaming and shows a thought bubble.
+ * This is the default state — only needed to re-enable after `disableAvatarChat()`.
*/
enableAvatarChat() {
this.removeAttribute('avatar-chat');
}
/**
- * Disable the inline avatar-in-chat layout and restore bottom-bar chat.
- * @returns {void}
+ * Disable the inline avatar-in-chat layout.
+ * Restores the original bottom-bar chat overlay.
+ * Stops any in-progress walk animation and clears the thought bubble.
*/
disableAvatarChat() {
this.setAttribute('avatar-chat', 'off');
diff --git a/src/runtime/index.js b/src/runtime/index.js
index ed1abaf7d..74f85e97d 100644
--- a/src/runtime/index.js
+++ b/src/runtime/index.js
@@ -62,6 +62,10 @@ export class Runtime extends EventTarget {
return [...builtins, ...stageTools, ...skillTools];
}
+ /**
+ * Abort the current in-flight LLM request, if any.
+ * Resolves the pending `send()` call immediately.
+ */
cancel() {
this._abortController?.abort();
}
diff --git a/src/runtime/providers.js b/src/runtime/providers.js
index d313af9a5..e9fece7a9 100644
--- a/src/runtime/providers.js
+++ b/src/runtime/providers.js
@@ -28,6 +28,12 @@ export class AnthropicProvider {
}
}
+ /**
+ * Send a completion request to Anthropic.
+ * Streams the response via SSE and calls `onChunk` for each text delta.
+ * @param {{ system, messages, tools, onChunk?, signal? }} opts
+ * @returns {Promise<{ text, toolCalls, thinking, stopReason }>}
+ */
async complete({ system, messages, tools, onChunk, signal }) {
const body = {
model: this.model,