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
forge(poll): survive backgrounded tabs and dropped sockets during a generation
nirholasac9264dab2f1
diff --git a/src/forge.js b/src/forge.jsindex 1b31ed221..3aed8238f 100644--- a/src/forge.js+++ b/src/forge.js@@ -1673,9 +1673,16 @@ async function pollUntilDone(jobId) {if (err?.kind !== 'transport') throw err;if (!offlineSince) offlineSince = runNow();if (runNow() - offlineSince > POLL_TRANSPORT_GRACE_MS) {- throw new Error(+ // The job is alive on the server and the inflight record is the+ // only handle this browser has on it, so this branch must NOT be+ // treated like a failed generation. `kind` says so: the catch in+ // run() keeps the record instead of clearing it, which is what+ // makes the "reopen /forge" instruction below actually true.+ const e = new Error('Lost the connection to the generator. Your model is still being built and will keep going. Reopen /forge to pick it back up.',);+ e.kind = 'transport_lost';+ throw e;}setLaneNote(PATCHY_NETWORK_NOTE);backoffMs = nextBackoff(backoffMs, POLL_MAX_BACKOFF_MS);@@ -2593,7 +2600,13 @@ async function run(cfg) {// re-runs (which writes a fresh inflight record), so the old record is// dead either way. The server-side finalizer still completes the row// into the gallery if the lane actually finished after our timeout.- clearInflight();+ //+ // One exception: a connection we gave up waiting on. The generation is+ // still running server-side and the inflight record is the only handle+ // this browser has on it, so clearing it here is what used to make the+ // error's own "reopen /forge to pick it back up" a lie. Keep it and the+ // resume path in boot() picks the same job back up.+ if (err?.kind !== 'transport_lost') clearInflight();// This job is over on every branch below (a designed error state, a gate,// or an automatic lane hop that starts a fresh timeline of its own), so the// stage list stops here rather than sitting on a spinning row.@@ -3195,6 +3208,59 @@ els.download.addEventListener('click', async (e) => {els.cinema?.addEventListener('click', () => setCinema(!cinemaOn));+// ── Escape collapses the panel you just opened ───────────────────────────────+// The result column stacks a lot of disclosures (Materials, Optimize, Split+// into parts, Game-Ready, Embed, Stylize, and the art-direction details), each+// owned by its own module with its own open/close logic. None of them listened+// for Escape, so the only way back out of one was to find its trigger again.+//+// Rather than duplicate seven modules' state here, this watches the triggers+// themselves: after a click inside the result panel, whatever now reports+// aria-expanded="true" (or a <details open>) goes on a stack, and Escape pops+// the top and re-clicks it, which runs that module's own close path. A panel+// added later needs no wiring at all, and focus returns to the trigger so a+// keyboard user is not dropped at the top of the document.+const openPanels = [];++function panelTriggerState(el) {+ if (!el) return null;+ const details = el.closest('details');+ if (details && el.closest('summary')) return { el: details, open: !details.open };+ const trigger = el.closest('[aria-expanded]');+ if (!trigger) return null;+ return { el: trigger, open: trigger.getAttribute('aria-expanded') === 'true' };+}++els.states.result.addEventListener('click', (e) => {+ // Bubble phase on purpose: the owning module's handler has already run, so+ // the attribute read here is the panel's new state, not its old one.+ const state = panelTriggerState(e.target);+ if (!state) return;+ const at = openPanels.indexOf(state.el);+ if (at !== -1) openPanels.splice(at, 1);+ if (state.open) openPanels.push(state.el);+});++function collapseTopPanel() {+ while (openPanels.length) {+ const el = openPanels.pop();+ // A panel closed by its own UI (or torn down on a new generation) is stale.+ const stillOpen =+ el.isConnected &&+ (el.tagName === 'DETAILS' ? el.open : el.getAttribute('aria-expanded') === 'true');+ if (!stillOpen) continue;+ if (el.tagName === 'DETAILS') {+ el.open = false;+ el.querySelector('summary')?.focus();+ } else {+ el.click();+ el.focus();+ }+ return true;+ }+ return false;+}+document.addEventListener('keydown', (e) => {if (e.key === 'Escape') {if (cinemaOn) {@@ -3206,6 +3272,8 @@ document.addEventListener('keydown', (e) => {els.cancel.click();return;}+ // Nothing in flight: back out of the last result panel that was opened.+ if (collapseTopPanel()) return;}if (e.metaKey || e.ctrlKey || e.altKey) return;const active = document.activeElement;diff --git a/src/shared/resilient-poll.js b/src/shared/resilient-poll.jsindex fbf57d131..647dbfdd8 100644--- a/src/shared/resilient-poll.js+++ b/src/shared/resilient-poll.js@@ -43,9 +43,16 @@*//**- * Sleep that also wakes the moment the tab returns to the foreground, so a- * finished generation is visible as soon as the user looks at the tab again- * rather than after the browser's clamped background timer fires.+ * Sleep that also wakes the moment the tab returns to the foreground, or the+ * moment the device regains connectivity.+ *+ * Two separate stalls, one primitive. Waking on `visibilitychange` means a+ * finished generation is on screen as soon as the user looks at the tab again,+ * rather than after the browser's clamped background timer fires. Waking on+ * `online` matters on exactly the network this whole module exists for: a phone+ * that loses its radio in a lift or a tunnel has already been pushed to a 20 s+ * backoff by the time it comes back, so without this the user watches a+ * "connection dropped" notice for most of a minute after their signal returned.** @param {number} ms* @returns {Promise<void>}@@ -58,6 +65,7 @@ export function sleepUntilVisibleOrElapsed(ms) {settled = true;clearTimeout(timer);document.removeEventListener('visibilitychange', onVisibility);+ window.removeEventListener('online', finish);resolve();};const onVisibility = () => {@@ -65,6 +73,7 @@ export function sleepUntilVisibleOrElapsed(ms) {};const timer = setTimeout(finish, ms);document.addEventListener('visibilitychange', onVisibility);+ window.addEventListener('online', finish);});}diff --git a/tests/resilient-poll.test.js b/tests/resilient-poll.test.jsnew file mode 100644index 000000000..10f3f5e56--- /dev/null+++ b/tests/resilient-poll.test.js@@ -0,0 +1,157 @@+// src/shared/resilient-poll.js: the poll primitives every long-running+// generation on the site is built on (src/forge.js, src/home-forge.js).+//+// These are the failure modes of a phone, not of a server, so they are tested+// against a fake document/window rather than a browser: a tab that goes hidden+// must not burn the run budget, a radio that comes back must not leave the user+// waiting out a 20 s backoff, and a dropped socket must be distinguishable from+// a dead job.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++// The module reads `document` and `window` at call time, so a minimal stub is+// enough and keeps the test honest about exactly which events it relies on.+function installDom(visibility = 'visible') {+ const listeners = { document: new Map(), window: new Map() };+ const make = (bag) => ({+ addEventListener: (type, fn) => {+ if (!bag.has(type)) bag.set(type, new Set());+ bag.get(type).add(fn);+ },+ removeEventListener: (type, fn) => bag.get(type)?.delete(fn),+ emit: (type) => [...(bag.get(type) || [])].forEach((fn) => fn()),+ count: (type) => bag.get(type)?.size ?? 0,+ });+ const doc = make(listeners.document);+ const win = make(listeners.window);+ globalThis.document = Object.assign(doc, { visibilityState: visibility });+ globalThis.window = win;+ return { doc, win };+}++let dom;+beforeEach(() => {+ dom = installDom();+ vi.useFakeTimers();+});+afterEach(() => {+ vi.useRealTimers();+ delete globalThis.document;+ delete globalThis.window;+});++describe('sleepUntilVisibleOrElapsed', () => {+ it('resolves early when the device comes back online', async () => {+ const { sleepUntilVisibleOrElapsed } = await import('../src/shared/resilient-poll.js');+ let done = false;+ const p = sleepUntilVisibleOrElapsed(20_000).then(() => {+ done = true;+ });+ await vi.advanceTimersByTimeAsync(500);+ expect(done).toBe(false);+ dom.win.emit('online');+ await p;+ expect(done).toBe(true);+ });++ it('resolves early when the tab returns to the foreground', async () => {+ const { sleepUntilVisibleOrElapsed } = await import('../src/shared/resilient-poll.js');+ const p = sleepUntilVisibleOrElapsed(20_000);+ globalThis.document.visibilityState = 'visible';+ dom.doc.emit('visibilitychange');+ await expect(p).resolves.toBeUndefined();+ });++ it('detaches both listeners once it settles, however it settled', async () => {+ // The poll loop calls this once per iteration for minutes on end, so a+ // listener left attached is an unbounded leak on the exact devices this+ // module exists for.+ const { sleepUntilVisibleOrElapsed } = await import('../src/shared/resilient-poll.js');+ const p = sleepUntilVisibleOrElapsed(1000);+ expect(dom.win.count('online')).toBe(1);+ await vi.advanceTimersByTimeAsync(1000);+ await p;+ expect(dom.win.count('online')).toBe(0);+ expect(dom.doc.count('visibilitychange')).toBe(0);+ });++ it('resolves once even if both wake sources fire', async () => {+ const { sleepUntilVisibleOrElapsed } = await import('../src/shared/resilient-poll.js');+ const fn = vi.fn();+ const p = sleepUntilVisibleOrElapsed(5000).then(fn);+ dom.win.emit('online');+ dom.doc.emit('visibilitychange');+ await vi.advanceTimersByTimeAsync(5000);+ await p;+ expect(fn).toHaveBeenCalledTimes(1);+ });+});++describe('createHiddenClock', () => {+ it('does not count foreground time', async () => {+ const { createHiddenClock } = await import('../src/shared/resilient-poll.js');+ const clock = createHiddenClock();+ expect(clock.hiddenMs()).toBe(0);+ clock.stop();+ });++ it('counts the time a backgrounded tab spends hidden', async () => {+ const { createHiddenClock } = await import('../src/shared/resilient-poll.js');+ const clock = createHiddenClock();+ const start = performance.now();+ globalThis.document.visibilityState = 'hidden';+ dom.doc.emit('visibilitychange');+ // performance.now() is real here; the assertion only needs the clock to+ // have started accruing, not a precise duration.+ expect(clock.hiddenMs()).toBeGreaterThanOrEqual(0);+ globalThis.document.visibilityState = 'visible';+ dom.doc.emit('visibilitychange');+ const accrued = clock.hiddenMs();+ expect(accrued).toBeGreaterThanOrEqual(0);+ expect(accrued).toBeLessThan(performance.now() - start + 50);+ clock.stop();+ expect(dom.doc.count('visibilitychange')).toBe(0);+ });+});++describe('fetchJobStatus', () => {+ it('marks a dropped socket as transport so the caller can retry it', async () => {+ const { fetchJobStatus } = await import('../src/shared/resilient-poll.js');+ globalThis.fetch = vi.fn().mockRejectedValue(new TypeError('Failed to fetch'));+ await expect(fetchJobStatus('/api/forge?job=x')).rejects.toMatchObject({ kind: 'transport' });+ });++ it('marks a 5xx and a 429 as transport, but not a 400', async () => {+ const { fetchJobStatus } = await import('../src/shared/resilient-poll.js');+ for (const status of [500, 502, 429]) {+ globalThis.fetch = vi.fn().mockResolvedValue({ status, json: async () => ({}) });+ await expect(fetchJobStatus('/u')).rejects.toMatchObject({ kind: 'transport' });+ }+ globalThis.fetch = vi.fn().mockResolvedValue({ status: 400, json: async () => ({ error: 'bad' }) });+ await expect(fetchJobStatus('/u')).resolves.toEqual({ error: 'bad' });+ });++ it('reads an unparseable body as "no status yet" rather than a failure', async () => {+ const { fetchJobStatus } = await import('../src/shared/resilient-poll.js');+ globalThis.fetch = vi.fn().mockResolvedValue({+ status: 200,+ json: async () => {+ throw new SyntaxError('Unexpected token <');+ },+ });+ await expect(fetchJobStatus('/u')).resolves.toEqual({});+ });+});++describe('nextBackoff', () => {+ it('grows and then holds at the ceiling, jittered', async () => {+ const { nextBackoff } = await import('../src/shared/resilient-poll.js');+ const grown = nextBackoff(2500, 20_000);+ expect(grown).toBeGreaterThan(2500);+ // Jitter is +/-15% around the doubled value, so the ceiling is approached,+ // never exceeded by more than that band.+ const capped = nextBackoff(20_000, 20_000);+ expect(capped).toBeLessThanOrEqual(20_000 * 1.15);+ expect(capped).toBeGreaterThanOrEqual(20_000 * 0.85);+ });+});