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(forge): retry HF Spaces anonymously when the platform token hits ZeroGPU quota

nirholas3c581d5a2a29
diff --git a/api/_providers/huggingface.js b/api/_providers/huggingface.js
index c76f448d7..16ffd8684 100644
--- a/api/_providers/huggingface.js
+++ b/api/_providers/huggingface.js
@@ -268,6 +268,12 @@ async function consumeSseUntilComplete(response) {
throw Object.assign(new Error(`huggingface inference failed: ${errorMessage}`), {
code: 'provider_error',
status: 502,
+ // The no-detail error (and any explicit quota message) is the signature
+ // of ZeroGPU quota exhaustion. It is scoped to the *identity* making the
+ // call: an exhausted account fails while the same request succeeds
+ // anonymously on per-IP quota. runOnSpace uses this to retry once
+ // without the bearer token before advancing the failover chain.
+ quotaLike: /quota/i.test(errorMessage) || errorMessage.startsWith('Space error event with no detail'),
});
}
if (result === null) {
@@ -371,7 +377,7 @@ async function rehostGlbToR2(glbUrls, token) {
for (const glbUrl of candidates) {
for (let attempt = 1; attempt <= REHOST_MAX_ATTEMPTS; attempt++) {
try {
- const resp = await fetch(glbUrl, { headers: { authorization: `Bearer ${token}` } });
+ const resp = await fetch(glbUrl, { headers: spaceAuthHeaders(token) });
if (!resp.ok) {
lastErr = Object.assign(new Error(`GLB fetch ${resp.status}`), { status: resp.status });
// 404/410 on this address = wrong route or the temp file is gone;
@@ -416,10 +422,32 @@ async function rehostGlbToR2(glbUrls, token) {
return publicUrl(key);
}
-// Try one Space end-to-end: enqueue → consume SSE → extract GLB url.
-// Throws with a tagged error containing the Space slug so the failover loop
-// can decide whether to advance to the next entry.
+// Authorization header set for a Space call. Anonymous calls (token=null) must
+// omit the header entirely — "Bearer null" is an invalid credential, not anon.
+function spaceAuthHeaders(token) {
+ return token ? { authorization: `Bearer ${token}` } : {};
+}
+
+// Try one Space end-to-end, first with the platform HF token, and once more
+// anonymously when the authed run dies with the ZeroGPU quota signature.
+// Public Spaces meter anonymous callers per-IP, a separate allowance from the
+// account's — so an exhausted platform account (observed live 2026-07-16: the
+// same TripoSR request errored with the token and produced a GLB without it)
+// must not take the whole rung down. Throws with a tagged error containing the
+// Space slug so the failover loop can decide whether to advance.
async function runOnSpace({ token, target, photos, params }) {
+ try {
+ return await attemptOnSpace({ token, target, photos, params });
+ } catch (err) {
+ if (!token || !err?.quotaLike) throw err;
+ console.warn(
+ `[hf] ${target.space} hit the quota signature with the platform token; retrying anonymously on per-IP quota`,
+ );
+ return attemptOnSpace({ token: null, target, photos, params });
+ }
+}
+
+async function attemptOnSpace({ token, target, photos, params }) {
const { space, api, builder } = target;
const spaceUrl = spaceBaseUrl(space);
const payloadBuilder = BUILDERS[builder] || BUILDERS.single;
@@ -432,7 +460,7 @@ async function runOnSpace({ token, target, photos, params }) {
try {
queueRes = await fetch(`${spaceUrl}/call/${api}`, {
method: 'POST',
- headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
+ headers: { ...spaceAuthHeaders(token), 'content-type': 'application/json' },
body: JSON.stringify({ data: payload }),
});
} catch (err) {
@@ -458,7 +486,7 @@ async function runOnSpace({ token, target, photos, params }) {
let streamRes;
try {
streamRes = await fetch(`${spaceUrl}/call/${api}/${eventId}`, {
- headers: { authorization: `Bearer ${token}`, accept: 'text/event-stream' },
+ headers: { ...spaceAuthHeaders(token), accept: 'text/event-stream' },
});
} catch (err) {
throw tag(Object.assign(new Error(`SSE GET failed: ${err?.message}`), {
diff --git a/tests/api/providers-huggingface-failover.test.js b/tests/api/providers-huggingface-failover.test.js
index a2c958d9a..acb044f09 100644
--- a/tests/api/providers-huggingface-failover.test.js
+++ b/tests/api/providers-huggingface-failover.test.js
@@ -147,6 +147,56 @@ describe('huggingface provider — failover chain', () => {
expect(fetchMock.mock.calls.length).toBe(3); // one enqueue per Space
});
+ it('retries a Space anonymously when the authed run dies with the ZeroGPU quota signature', async () => {
+ process.env.HF_RECONSTRUCT_SPACES = 'foo/A,bar/B';
+ // Gradio's quota death: event: error with data: null. Authed attempt hits
+ // it (exhausted account allowance); the anonymous retry on per-IP quota
+ // succeeds. Observed live on stabilityai/TripoSR 2026-07-16.
+ const errorStream = () => {
+ const text = `event: error\ndata: null\n\n`;
+ const encoder = new TextEncoder();
+ const stream = new ReadableStream({
+ start(controller) {
+ controller.enqueue(encoder.encode(text));
+ controller.close();
+ },
+ });
+ return new Response(stream, { status: 200, headers: { 'content-type': 'text/event-stream' } });
+ };
+ let enqueueCount = 0;
+ const fetchMock = vi.fn(async (url, opts) => {
+ if (url === `${spaceUrl('foo/A')}/call/generation_all`) {
+ enqueueCount += 1;
+ if (enqueueCount === 1) {
+ expect(opts?.headers?.authorization).toBe('Bearer hf_test_token');
+ return jsonResp({ event_id: 'evt-authed' });
+ }
+ // Anonymous retry must omit the authorization header entirely.
+ expect(opts?.headers?.authorization).toBeUndefined();
+ return jsonResp({ event_id: 'evt-anon' });
+ }
+ if (url === `${spaceUrl('foo/A')}/call/generation_all/evt-authed`) return errorStream();
+ if (url === `${spaceUrl('foo/A')}/call/generation_all/evt-anon`) {
+ expect(opts?.headers?.authorization).toBeUndefined();
+ return sseStream([{ url: 'https://files/anon.glb' }]);
+ }
+ throw new Error(`unexpected url ${url}`);
+ });
+ globalThis.fetch = fetchMock;
+
+ const { createRegenProvider } = await import('../../api/_providers/huggingface.js');
+ const out = await createRegenProvider().submit({
+ mode: 'reconstruct',
+ params: { images: ['data:image/jpeg;base64,AAA'] },
+ });
+
+ const decoded = JSON.parse(Buffer.from(out.extJobId, 'base64url').toString('utf8'));
+ expect(decoded.resultGlbUrl).toBe('https://files/anon.glb');
+ expect(decoded.space).toBe('foo/A');
+ // Same Space recovered — no failover to bar/B.
+ expect(decoded.fellBackFrom).toEqual([]);
+ });
+
it('legacy HF_RECONSTRUCT_SPACE env still works as a single-Space chain', async () => {
process.env.HF_RECONSTRUCT_SPACE = 'legacy/only';
const fetchMock = vi.fn(async (url) => {