The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(cloud): a token that aged out mid-run is refreshed, not the end of the run
David4adf0ca9f6ef
diff --git a/src/api/providers/lu-cloud-provider.ts b/src/api/providers/lu-cloud-provider.tsindex 403dcaff..53adb3ef 100644--- a/src/api/providers/lu-cloud-provider.ts+++ b/src/api/providers/lu-cloud-provider.ts@@ -38,7 +38,11 @@ export class LuCloudProvider implements ProviderClient {)}if (!token) {- throw new ProviderError('Sign in to your LU Cloud account to chat in the cloud.', 'lu-cloud', 'auth', 401)+ // `signed_out`, not `auth`: there is no session left to refresh, so this+ // is the one 401 on this provider that a retry cannot fix. The retry+ // guard (lib/http-status) keeps every OTHER lu-cloud 401 retryable+ // precisely because the call below re-mints the token.+ throw new ProviderError('Sign in to your LU Cloud account to chat in the cloud.', 'lu-cloud', 'signed_out', 401)}// Hard-pin the endpoint at call time. The Supabase access token is a live// bearer; if we trusted `this.config.baseUrl` a tampered provider store coulddiff --git a/src/hooks/__tests__/cloud-session-outlives-a-long-run.test.ts b/src/hooks/__tests__/cloud-session-outlives-a-long-run.test.tsnew file mode 100644index 00000000..6c2273fd--- /dev/null+++ b/src/hooks/__tests__/cloud-session-outlives-a-long-run.test.ts@@ -0,0 +1,66 @@+/**+ * An hour into an agent run, the cloud token ages out. The run must not.+ *+ * Review 2026-08-14. LU Cloud's bearer is a Supabase access token with a life+ * of about an hour, and LuCloudProvider.delegate() calls getAccessToken()+ * afresh on every single call, so the retry IS the refresh. The 4xx guard+ * classified 401 as terminal, which threw that away: the run ended at the+ * first refusal, and the user, who is signed in and watching, read+ * "unauthenticated" or, on an opaque body, "Invalid API key for LU Cloud.+ * Check Settings > Providers." for a provider that has no API key field.+ *+ * The same cloud already states the policy on its jobs path+ * (api/cloud/jobs.ts): 401 stays retryable so a failed lazy refresh never+ * tells a signed-in user to sign in.+ *+ * Run: npx vitest run src/hooks/__tests__/cloud-session-outlives-a-long-run.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'++const here = dirname(fileURLToPath(import.meta.url))+const read = (rel: string) => readFileSync(resolve(here, rel), 'utf8')+const provider = read('../../api/providers/lu-cloud-provider.ts')+const agent = read('../useAgentChat.ts')+const chat = read('../useChat.ts')+const jobs = read('../../api/cloud/jobs.ts')++describe('the retry is the refresh', () => {+ it('every call mints its own token, so attempt two is a different request', () => {+ const delegate = provider.slice(+ provider.indexOf('private async delegate'),+ provider.indexOf('async *chatStream'),+ )+ expect(delegate).toContain('await getAccessToken()')+ // chatStream must go through delegate(), not a cached client.+ expect(provider).toContain('const inner = await this.delegate()')+ })++ it('no session at all is tagged apart, that one no retry can fix', () => {+ expect(provider).toContain("'lu-cloud', 'signed_out', 401")+ })+})++describe('the dead end says the true thing', () => {+ it('the agent has a branch for it instead of falling into "Agent error"', () => {+ const branch = agent.indexOf("code === 'signed_out'")+ const generic = agent.indexOf("'\\n\\nAgent error: ' + errorMsg")+ expect(branch).toBeGreaterThan(-1)+ expect(branch).toBeLessThan(generic)+ expect(agent).toContain('Your LU Cloud session ended and could not be renewed')+ // Same treatment as an empty wallet: a /loop must not run on into it.+ expect(agent).toContain("loopHalt = 'signed out of LU Cloud'")+ })++ it('plain chat prints the sentence instead of wrapping it in "Error:"', () => {+ expect(chat).toContain("(err as any).code === 'auth' || (err as any).code === 'signed_out'")+ })+})++describe('the house policy is one policy', () => {+ it('the jobs path on the same cloud exempts 401 for the same reason', () => {+ expect(jobs).toContain('status !== 401 && status !== 408 && status !== 429')+ })+})diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 9ef14ade..0aa3885b 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -1778,6 +1778,24 @@ export function useAgentChat() {convId!, assistantMessage.id,(contentRef.current ? contentRef.current + '\n\n' : '') + CREDITS_EXHAUSTED_MESSAGE + planLine)+ } else if ((err as { code?: string })?.code === 'signed_out'+ || (httpStatusOf(err) === 401 && (err as { provider?: string })?.provider === 'lu-cloud')) {+ // The retries above already re-minted the token twice, so reaching+ // here means the session is really gone, not merely aged out. Before+ // this branch existed the run ended on "Agent error: unauthenticated"+ // or, on an opaque body, "Invalid API key for LU Cloud. Check+ // Settings > Providers." for a provider that has no API key field.+ loopHalt = 'signed out of LU Cloud'+ const todos = useTodoStore.getState().getTodos(convId!)+ const done = todos.filter((t) => t.status === 'completed').length+ const planLine = todos.length+ ? `\n\nThe plan stopped at ${done} of ${todos.length}. Everything finished so far stays in this chat. After signing in, send a new message naming only what is still left, rather than the original prompt.`+ : ''+ useChatStore.getState().updateMessageContent(+ convId!, assistantMessage.id,+ (contentRef.current ? contentRef.current + '\n\n' : '') ++ 'Your LU Cloud session ended and could not be renewed, so the run stopped here. Sign in again in Settings, then carry on.' + planLine+ )} else if (/failed to fetch|connection refused|connection reset|error sending request|proxy_localhost|network ?error|timed out|timeout|tcp connect|llama runner process|backend unreachable|HTTP 5\d\d/i.test(errorMsg)) {// Connection-class failure — after the transient retries above this// means the backend really dropped mid-run (crashed, was killed, ordiff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex f4406743..7ac3146f 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -751,7 +751,7 @@ export function useChat() {// can call the same translation without re-implementing it.syncOllamaHealthFromError(err)- const errorMsg = (err as any).code === 'auth'+ const errorMsg = (err as any).code === 'auth' || (err as any).code === 'signed_out'? (err as Error).message: (err as any).code === 'rate_limit'? (err as Error).messagediff --git a/src/lib/__tests__/http-status.test.ts b/src/lib/__tests__/http-status.test.tsindex 034e1e72..83a7e03f 100644--- a/src/lib/__tests__/http-status.test.ts+++ b/src/lib/__tests__/http-status.test.ts@@ -59,3 +59,42 @@ describe('isTerminalModelError', () => {expect(isTerminalModelError(new Error('Failed to fetch'))).toBe(false)})})++// ── a lapsed cloud session is not a dead end (review 2026-08-14) ────────────+//+// LU Cloud's bearer is a Supabase access token that lives about an hour, and+// LuCloudProvider.delegate() re-mints it on EVERY call. So a 401 an hour into+// an agent run usually means the token aged out between two steps, and the+// next attempt already carries a fresh one. Ending the run there threw away+// the only thing that would have fixed it, and told a signed-in user either+// "unauthenticated" or "Invalid API key, check Settings > Providers" for a+// provider with no API key field. api/cloud/jobs.ts exempts 401 and 408 on the+// same cloud for the same reason.+describe('401 depends on whose credential it is', () => {+ it('a lapsed LU Cloud token is retried, which is what re-mints it', () => {+ expect(isTerminalModelError(new ProviderError('unauthenticated', 'lu-cloud', 'auth', 401))).toBe(false)+ })++ it('but a wrong API key on a configured provider still stops at once', () => {+ expect(isTerminalModelError(new ProviderError('bad key', 'openai', 'auth', 401))).toBe(true)+ expect(isTerminalModelError(new ProviderError('bad key', 'anthropic', 'auth', 401))).toBe(true)+ expect(isTerminalModelError(Object.assign(new Error('nope'), { statusCode: 401 }))).toBe(true)+ })++ it('really signed out IS terminal, so the dead end costs one backoff, not three', () => {+ // What delegate() throws when getAccessToken() comes back empty: there is+ // no session left to refresh, so retrying only delays the true message.+ expect(isTerminalModelError(+ new ProviderError('Sign in to your LU Cloud account to chat in the cloud.', 'lu-cloud', 'signed_out', 401),+ )).toBe(true)+ })++ it('a 403 from the cloud stays terminal, it is not about a stale token', () => {+ expect(isTerminalModelError(new ProviderError('closed beta', 'lu-cloud', 'auth', 403))).toBe(true)+ })++ it('a request timeout is worth another try on any provider', () => {+ expect(isTerminalModelError(new ProviderError('request timeout', 'openai', undefined, 408))).toBe(false)+ expect(isTerminalModelError(Object.assign(new Error('timeout'), { statusCode: 408 }))).toBe(false)+ })+})diff --git a/src/lib/http-status.ts b/src/lib/http-status.tsindex 848b814a..fd12105b 100644--- a/src/lib/http-status.ts+++ b/src/lib/http-status.ts@@ -22,15 +22,37 @@ export function httpStatusOf(err: unknown): number {* the same request will be refused the same way, so the run must stop and say* so instead of burning seconds on backoff.*- * 429 is the exception that makes this worth a function. LU Cloud answers 429- * for three different things: the per-user burst guard, an upstream provider+ * "Deterministic" is about the request, not about the status number, and three+ * 4xx codes are not:+ *+ * 429 is the one that makes this worth a function. LU Cloud answers it for+ * three different things: the per-user burst guard, an upstream provider* throttle (both genuinely transient, both send retry-after), and an empty* wallet, which no amount of waiting fixes. Only the last one is terminal, and* it is the only one that carries `code: 'credits_exhausted'`.+ *+ * 408 is a request timeout, which is the definition of worth another try.+ *+ * 401 depends on WHOSE credential it is. For a provider the user configured+ * with an API key, a refusal is final until they fix the key. LU Cloud does+ * not work that way: its bearer is a Supabase access token that lives about an+ * hour and is re-minted per call by LuCloudProvider.delegate(), so a 401 in+ * the middle of a long agent run usually means nothing worse than "that token+ * just aged out". The retry calls delegate() again, getSession() hands back a+ * fresh token, and the user never learns it happened. Treating it as terminal+ * ended the run at the first refusal with "unauthenticated", or worse with+ * "Invalid API key, check Settings > Providers" for a provider that has no API+ * key field. api/cloud/jobs.ts states the same policy for the same cloud, with+ * the same reason: a failed lazy refresh must not tell a signed-in user to+ * sign in. When the session really is gone, getAccessToken() returns nothing+ * and the provider throws `signed_out`, which IS terminal, so the dead end+ * costs one backoff and then says the true thing.*/export function isTerminalModelError(err: unknown): boolean {- const code = (err as { code?: unknown } | null)?.code- if (code === 'credits_exhausted') return true+ const e = err as { code?: unknown; provider?: unknown } | null+ if (e?.code === 'credits_exhausted' || e?.code === 'signed_out') return trueconst status = httpStatusOf(err)- return status >= 400 && status < 500 && status !== 429+ if (status === 429 || status === 408) return false+ if (status === 401 && e?.provider === 'lu-cloud') return false+ return status >= 400 && status < 500}