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.

fix(brain): keep Send clickable, explain a dead model route, and gate by real session

nirholas69dee28741a7
diff --git a/api/brain/chat.js b/api/brain/chat.js
index fc42fa372..e8feb1add 100644
--- a/api/brain/chat.js
+++ b/api/brain/chat.js
@@ -1133,7 +1133,8 @@ export async function streamBrain(res, { plan, providerKey, messages, system, ma
if (!res.writableEnded) {
try {
res.write(`event: error\ndata: ${JSON.stringify({
- message: err?.message || 'upstream error',
+ message: userFacingStreamError(err),
+ reason: conciseReason(err),
elapsedMs,
})}\n\n`);
res.end();
@@ -1250,3 +1251,30 @@ function conciseReason(err) {
const msg = (err?.message || String(err)).replace(/\s+/g, ' ').trim();
return msg.length > 160 ? `${msg.slice(0, 157)}…` : msg;
}
+
+/**
+ * The message a visitor reads inside the model's column once every rung of the
+ * fallback chain has failed. The raw error belongs to the last route tried, so
+ * it surfaces words like "Forbidden" or "fetch failed" that describe a provider
+ * the visitor never chose and cannot act on. Say what happened and what to do
+ * instead; the precise reason still ships alongside as `reason` and is logged.
+ * Exported for tests.
+ */
+export function userFacingStreamError(err) {
+ const status = Number(err?.statusCode ?? err?.status) || 0;
+ const msg = (err?.message || '').toLowerCase();
+
+ if (status === 429 || /rate.?limit|too many requests|quota|resource[ _-]?exhausted/.test(msg)) {
+ return 'Every route for this model is rate limited right now. Try again in a moment, or pick another model.';
+ }
+ if (status === 401 || status === 403 || /forbidden|unauthorized|permission denied|api key/.test(msg)) {
+ return 'This model has no working route on this deployment right now. Pick another model while the route is restored.';
+ }
+ if (status === 404 || /not found|no such model|model.*(deprecated|retired)/.test(msg)) {
+ return 'This model is no longer served upstream. Pick another model.';
+ }
+ if (/timeout|timed out|aborted|deadline/.test(msg)) {
+ return 'This model took too long to answer. Try again, or pick a faster model.';
+ }
+ return 'This model could not answer. Try again, or pick another model.';
+}
diff --git a/public/app-next.css b/public/app-next.css
index 60843c37a..54cf9c15a 100644
--- a/public/app-next.css
+++ b/public/app-next.css
@@ -1691,7 +1691,17 @@ body.app-next-body.nxt-chat-merged .nxt-chat-input-wrap:focus-within {
.nxt-action--primary span { display: inline; }
.nxt-chat-dock { bottom: 64px; }
.nxt-action-bar--secondary { bottom: 12px; }
- .nxt-chat-chips { max-width: 100%; overflow-x: auto; flex-wrap: nowrap; padding-bottom: 2px; }
+ /* `justify-content: center` on a scroll container pushes the overflow past
+ BOTH edges, and the leading half can never be scrolled back into view. The
+ flex-start fallback keeps every chip reachable on engines without `safe`. */
+ .nxt-chat-chips {
+ max-width: 100%;
+ overflow-x: auto;
+ flex-wrap: nowrap;
+ padding-bottom: 2px;
+ justify-content: flex-start;
+ justify-content: safe center;
+ }
.nxt-chat-chip { white-space: nowrap; flex: none; }
.nxt-anim-sheet { bottom: 130px; max-height: 50vh; }
.nxt-first-hint { font-size: 11.5px; padding: 6px 6px 6px 12px; max-width: calc(100vw - 24px); }
@@ -1713,6 +1723,16 @@ body.app-next-body.nxt-chat-merged .nxt-chat-input-wrap:focus-within {
}
}
+/* Below ~380px the wordmark plus the full action cluster no longer fit on one
+ line. The header does not scroll, so the overflow pushed the sign-in link
+ clean off the right edge where it could not be read or tapped. Drop to the
+ mark alone; the link keeps its "three.ws home" label for assistive tech. */
+@media (max-width: 380px) {
+ .nxt-brand-text { display: none; }
+ .nxt-header { padding: 0 12px 0 10px; }
+ .nxt-header-right { gap: 6px; }
+}
+
/* Hide the production dat.gui by default — controls live inside the viewer
panel that's intentionally not surfaced in this UX preview. Power users
can re-enable via the explore menu (link routes to /app). */
diff --git a/public/brain.css b/public/brain.css
index dfcbc3728..5e7049960 100644
--- a/public/brain.css
+++ b/public/brain.css
@@ -963,7 +963,25 @@ body {
outline: none;
}
.br-sys-textarea:focus { border-color: #2a3060; }
-.br-input-row { display: flex; gap: 8px; align-items: flex-end; }
+/* The platform's bottom-right corner widgets (the shared corner stack, the walk
+ companion) take pointer events across their whole box and sit exactly on top
+ of Send, which made the primary action of this page unclickable whenever one
+ was on screen. syncCornerReserve() in src/brain.js measures whatever is
+ actually there and publishes the gutter; nothing is reserved when the corner
+ is empty. */
+.br-input-row {
+ display: flex;
+ gap: 8px;
+ align-items: flex-end;
+ padding-right: var(--br-corner-gutter, 0px);
+ transition: padding-right 0.2s ease;
+}
+/* When the widget is wide enough that a gutter would leave no room to type,
+ Send moves to its own line on the left instead, clear of the corner either
+ way. */
+.br-input-row.crowded { padding-right: 0; flex-wrap: wrap; }
+.br-input-row.crowded .br-prompt { flex: 1 1 100%; }
+.br-input-row.crowded .br-send { margin-right: auto; }
.br-prompt {
flex: 1;
background: #0c0c0c;
diff --git a/src/brain.js b/src/brain.js
index 0ba830e48..86eb969ee 100644
--- a/src/brain.js
+++ b/src/brain.js
@@ -503,6 +503,10 @@ async function runExtraction(payload) {
if (!res.ok) throw new Error(data.error_description || data.error || `HTTP ${res.status}`);
state.authed = true;
+ // The gate is raised on a 401 and nothing ever took it back down, so a
+ // visitor who signed in and returned kept reading "sign in to build your
+ // persona" above the persona they had just built.
+ hideAuthGate();
state.persona = data.persona;
persistPersona();
renderPersonaCard(state.persona);
@@ -1160,6 +1164,62 @@ function setPlayMode(m) {
renderCanvas();
}
+// The site mounts fixed widgets in the bottom-right corner (the shared corner
+// stack, the walk companion). Their boxes take pointer events, and this page
+// puts Send in exactly that spot, so a first-time visitor with the atlas hint
+// or the companion on screen could not click the page's primary action at all.
+// Measure whatever is actually parked there and reserve that much room beside
+// the composer; an empty corner reserves nothing.
+const CORNER_WIDGET_SELECTOR = '#tws-corner-stack, .walk-companion';
+
+function syncCornerReserve() {
+ const row = document.querySelector('.br-input-row');
+ if (!row) return;
+ const rowRect = row.getBoundingClientRect();
+ let gutter = 0;
+
+ for (const el of document.querySelectorAll(CORNER_WIDGET_SELECTOR)) {
+ const r = el.getBoundingClientRect();
+ if (r.width <= 0 || r.height <= 0) continue;
+ // Only a widget that actually overlaps the composer's band matters.
+ if (r.bottom <= rowRect.top || r.top >= rowRect.bottom) continue;
+ gutter = Math.max(gutter, window.innerWidth - r.left + 10);
+ }
+
+ // Past a third of the row the gutter costs more than it buys, so the layout
+ // wraps instead and Send lands on its own line clear of the corner.
+ const crowded = gutter > rowRect.width * 0.34;
+ row.classList.toggle('crowded', crowded);
+ document.documentElement.style.setProperty('--br-corner-gutter', crowded ? '0px' : `${Math.round(gutter)}px`);
+}
+
+// Corner widgets mount late (the atlas hint on first visit, the companion after
+// an idle callback), grow as their content changes, and move with the viewport,
+// so the reserve is re-measured on all three rather than computed once at boot.
+// The observers are deliberately narrow: both widgets are direct children of
+// <body>, so childList alone catches them, and this page rewrites its canvas on
+// every streamed token, which a subtree observer would turn into layout thrash.
+function watchCornerWidgets() {
+ let queued = false;
+ const schedule = () => {
+ if (queued) return;
+ queued = true;
+ requestAnimationFrame(() => { queued = false; syncCornerReserve(); });
+ };
+
+ const sizes = new ResizeObserver(schedule);
+ const trackWidgets = () => {
+ sizes.disconnect();
+ for (const el of document.querySelectorAll(CORNER_WIDGET_SELECTOR)) sizes.observe(el);
+ schedule();
+ };
+
+ trackWidgets();
+ window.addEventListener('resize', schedule);
+ window.addEventListener('tws-corner-stack:ready', trackWidgets);
+ new MutationObserver(trackWidgets).observe(document.body, { childList: true });
+}
+
// Below 900px the sessions rail is off-canvas, so the topbar carries the only
// route to it. Without this the New-session button and the whole session list
// were unreachable on a phone.
@@ -1331,6 +1391,7 @@ loadPersona();
renderArchetypes();
renderSidebar();
bindEvents();
+watchCornerWidgets();
fetchProviderRoster();
if (state.persona) {
diff --git a/tests/api/brain-roster-contract.test.js b/tests/api/brain-roster-contract.test.js
new file mode 100644
index 000000000..c92eb8ec9
--- /dev/null
+++ b/tests/api/brain-roster-contract.test.js
@@ -0,0 +1,103 @@
+// Two things the /brain page reads off GET /api/brain/chat, pinned here because
+// the page has no other source of truth for either.
+//
+// 1. `requiresAuth`. `available` only says the deployment holds a route for a
+// model; the anon gate (ANON_BRAIN_PROVIDERS) decides whether a signed-out
+// caller may use it. Without the flag the page cannot tell the two apart, so
+// it opened with a default line-up of paid models that could only answer 401
+// for the visitor most likely to be signed out: a first-time one.
+//
+// 2. The message a failed stream shows. When every rung of the fallback chain
+// fails, the raw error belongs to the last route tried, and the visitor read
+// a bare "Forbidden" inside the model's column: a word about a provider they
+// never chose and cannot act on.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => null),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+}));
+
+const ENV_KEYS = ['OPENAI_API_KEY', 'OPENROUTER_API_KEY', 'OPENROUTER_FALLBACK_KEYS', 'NVIDIA_API_KEY'];
+const saved = {};
+
+beforeEach(() => {
+ for (const k of ENV_KEYS) {
+ saved[k] = process.env[k];
+ delete process.env[k];
+ }
+ process.env.OPENAI_API_KEY = 'sk-test';
+ process.env.NVIDIA_API_KEY = 'nv-test';
+});
+
+afterEach(() => {
+ for (const k of ENV_KEYS) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+});
+
+describe('GET /api/brain/chat roster · requiresAuth', () => {
+ it('flags every provider, and agrees with the anon gate the handler enforces', async () => {
+ const { getAvailableProviders, ANON_BRAIN_PROVIDERS } = await import('../../api/brain/chat.js');
+ const roster = getAvailableProviders();
+ expect(roster.length).toBeGreaterThan(0);
+
+ for (const p of roster) {
+ expect(typeof p.requiresAuth).toBe('boolean');
+ // The flag IS the gate, not a second opinion about it.
+ expect(p.requiresAuth).toBe(!ANON_BRAIN_PROVIDERS.has(p.key));
+ }
+ });
+
+ it('leaves the platform default open to a signed-out visitor', async () => {
+ const { getAvailableProviders } = await import('../../api/brain/chat.js');
+ const dflt = getAvailableProviders().find((p) => p.key === 'gpt-oss-120b');
+ expect(dflt.requiresAuth).toBe(false);
+ });
+
+ it('keeps the paid first-party lanes behind sign-in', async () => {
+ const { getAvailableProviders } = await import('../../api/brain/chat.js');
+ const byKey = new Map(getAvailableProviders().map((p) => [p.key, p]));
+ for (const key of ['claude-sonnet-5', 'gpt-5.6-sol', 'o3', 'qwen-plus']) {
+ expect(byKey.get(key).requiresAuth).toBe(true);
+ }
+ });
+
+ it('offers a signed-out visitor at least one usable model besides the default', async () => {
+ const { getAvailableProviders } = await import('../../api/brain/chat.js');
+ const open = getAvailableProviders().filter((p) => p.available && !p.requiresAuth);
+ expect(open.length).toBeGreaterThan(1);
+ });
+});
+
+describe('userFacingStreamError', () => {
+ it('turns an upstream 403 into something the visitor can act on', async () => {
+ const { userFacingStreamError } = await import('../../api/brain/chat.js');
+ const msg = userFacingStreamError(Object.assign(new Error('Forbidden'), { statusCode: 403 }));
+ expect(msg).not.toMatch(/forbidden/i);
+ expect(msg).toMatch(/pick another model/i);
+ });
+
+ it('names rate limiting as rate limiting', async () => {
+ const { userFacingStreamError } = await import('../../api/brain/chat.js');
+ expect(userFacingStreamError({ statusCode: 429, message: 'Too Many Requests' }))
+ .toMatch(/rate limited/i);
+ expect(userFacingStreamError(new Error('RESOURCE_EXHAUSTED: quota exceeded')))
+ .toMatch(/rate limited/i);
+ });
+
+ it('distinguishes a timeout from a dead route', async () => {
+ const { userFacingStreamError } = await import('../../api/brain/chat.js');
+ expect(userFacingStreamError(new Error('The operation timed out'))).toMatch(/too long/i);
+ });
+
+ it('still says something useful for an error it has never seen', async () => {
+ const { userFacingStreamError } = await import('../../api/brain/chat.js');
+ const msg = userFacingStreamError(new Error('socket hang up'));
+ expect(msg).toMatch(/could not answer/i);
+ expect(msg).not.toMatch(/socket/i);
+ });
+});