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
tech(CLOUD/PERSIST): 15 Gegenpruefungs-Befunde geschlossen, jeder mit Mutationsprobe
David2d8b9279b734
diff --git a/src/api/__tests__/prod-licenses.test.ts b/src/api/__tests__/prod-licenses.test.tsindex be191133..6d5109d6 100644--- a/src/api/__tests__/prod-licenses.test.ts+++ b/src/api/__tests__/prod-licenses.test.ts@@ -22,8 +22,19 @@ const lock = JSON.parse(readFileSync(resolve(__dirname, '../../../package-lock.json'), 'utf8'),) as { packages: Record<string, LockEntry> }-/** Everything that can reach a user's machine: the root and devDependencies- * are out, optional platform builds stay in — one of them ships per OS. */+/** Everything that can reach a user's machine.+ *+ * `path &&` drops the root entry (npm keys it ""), which is this app itself.+ *+ * `!entry.dev` is npm's own reachability answer, and it is narrower than+ * "devDependencies are out": npm marks `dev: true` only on packages reachable+ * EXCLUSIVELY through the dev tree. A package that both a dependency and a+ * devDependency pull in carries no flag and stays in this list — correctly,+ * because it does install for a consumer of the production tree. So the+ * filter is "everything npm cannot prove is dev-only", which is the inclusive+ * side to err on for a licence check.+ *+ * Optional platform builds stay in — one of them ships per OS. */const production = Object.entries(lock.packages).filter(([path, entry]) => path && !entry.dev)/**diff --git a/src/api/cloud/__tests__/cloud-client.test.ts b/src/api/cloud/__tests__/cloud-client.test.tsindex dfe7be27..aabe66d5 100644--- a/src/api/cloud/__tests__/cloud-client.test.ts+++ b/src/api/cloud/__tests__/cloud-client.test.ts@@ -92,16 +92,97 @@ describe('cloudFetch', () => {vi.useRealTimers()})+ it('gives up when the TOKEN never arrives, not only when the request does not', async () => {+ // getAccessToken() is not a local lookup: supabase-js refreshes an expired+ // access token there, over the network, with no deadline of its own. The+ // guard used to be armed AFTER that await, so a refresh whose peer+ // disappeared mid-flight wedged Create exactly the way a hanging fetch did+ // — one step earlier, and past every clock this file installs.+ vi.useFakeTimers()+ getAccessToken.mockImplementation(() => new Promise(() => {}))+ const settled = cloudFetch('/api/jobs', { method: 'POST', body: '{"x":1}' }).catch(+ (e: unknown) => e,+ )+ await vi.advanceTimersByTimeAsync(120_000)+ const err = await settled+ expect(err).toBeInstanceOf(CloudJobError)+ expect((err as CloudJobError).status).toBe(408)+ expect(fetchMock).not.toHaveBeenCalled()+ vi.useRealTimers()+ })++ it("the caller's cancel also ends a token refresh that is hanging", async () => {+ getAccessToken.mockImplementation(() => new Promise(() => {}))+ const ac = new AbortController()+ const settled = cloudFetch('/api/me', { signal: ac.signal }).catch((e: unknown) => e)+ ac.abort()+ const err = await settled+ // A cancelled run is not a timeout, here just as much as at the fetch.+ expect(err).not.toBeInstanceOf(CloudJobError)+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('a 401 raised inside the window keeps its own status', async () => {+ // The deadline wraps the token now, so "not signed in" travels the same+ // catch as a timeout and must not come out relabelled 408.+ getAccessToken.mockResolvedValue(null)+ await expect(cloudFetch('/api/me')).rejects.toMatchObject({ status: 401 })+ })++ it('measures a FormData body instead of counting it as zero bytes', async () => {+ // deadlineFor only knew ArrayBuffer, views, Blob and string. FormData,+ // URLSearchParams and a stream all measured 0 and silently took the flat+ // ceiling, while the comment above it promised a size-derived deadline.+ vi.useFakeTimers()+ let aborted = false+ fetchMock.mockImplementation(hangingFetch(() => { aborted = true }))+ const fd = new FormData()+ fd.append('clip', new Blob(['x'.repeat(1024 * 1024)]))+ const settled = cloudFetch('/api/jobs/upload?role=video', { method: 'POST', body: fd }).catch(+ (e: unknown) => e,+ )+ // 1 MiB at the 64 B/ms floor buys ~16 s on top of the 60 s ceiling.+ await vi.advanceTimersByTimeAsync(65_000)+ expect(aborted).toBe(false)+ await vi.advanceTimersByTimeAsync(20_000)+ expect(await settled).toBeInstanceOf(CloudJobError)+ vi.useRealTimers()+ })++ it('measures a URLSearchParams body too', async () => {+ vi.useFakeTimers()+ let aborted = false+ fetchMock.mockImplementation(hangingFetch(() => { aborted = true }))+ const params = new URLSearchParams()+ params.set('payload', 'x'.repeat(1024 * 1024))+ const settled = cloudFetch('/api/jobs', { method: 'POST', body: params }).catch(+ (e: unknown) => e,+ )+ await vi.advanceTimersByTimeAsync(65_000)+ expect(aborted).toBe(false)+ await vi.advanceTimersByTimeAsync(20_000)+ expect(await settled).toBeInstanceOf(CloudJobError)+ vi.useRealTimers()+ })+it("hands the caller's abort signal through to the request", async () => {// pollJob and generate() both hold an AbortController for the run; before// this, cancelling could not reach a request already in flight.const ac = new AbortController()let seen: AbortSignal | undefined+ let inFlight!: () => void+ const started = new Promise<void>((resolve) => { inFlight = resolve })fetchMock.mockImplementation((url: string, init: RequestInit) => {seen = init.signal ?? undefined+ inFlight()return hangingFetch()(url, init)})const settled = cloudFetch('/api/me', { signal: ac.signal }).catch((e: unknown) => e)+ // Wait for the request to be genuinely in flight before cancelling. The+ // deadline now also covers the token step, so aborting before fetch is+ // reached (correctly) means no request is ever issued — which is the+ // adjacent test, not this one.+ await startedac.abort()const err = await settledexpect(seen?.aborted).toBe(true)diff --git a/src/api/cloud/__tests__/keychain-storage.test.ts b/src/api/cloud/__tests__/keychain-storage.test.tsindex ed07f0d9..fd6afa7d 100644--- a/src/api/cloud/__tests__/keychain-storage.test.ts+++ b/src/api/cloud/__tests__/keychain-storage.test.ts@@ -202,6 +202,39 @@ describe('the localStorage fallback is not a plaintext token dump', () => {await expect(store.getItem(SESSION)).resolves.toBe(REFRESH_TOKEN)})+ it('has no silent way back to writing the token in the clear', async () => {+ // The encoder used to be `try { btoa(...) } catch { return value }` — one+ // throw and the raw refresh token went to localStorage, unmarked, with+ // nothing logged and nothing to find it by afterwards. That is precisely+ // the state this whole encoding exists to remove, so there is no fallback+ // to it: without btoa the value is encoded here instead.+ const store = await freshAdapter()+ secretSet.mockRejectedValue(new Error('keychain unsupported on this platform'))+ secretGet.mockRejectedValue(new Error('keychain unsupported on this platform'))+ const realBtoa = globalThis.btoa+ const realAtob = globalThis.atob+ vi.stubGlobal('btoa', () => { throw new Error('btoa is not available here') })+ vi.stubGlobal('atob', () => { throw new Error('atob is not available here') })+ try {+ await store.setItem(SESSION, REFRESH_TOKEN)++ const onDisk = localStorage.getItem(SESSION)!+ expect(onDisk).not.toContain('v1.MRefr3sh')+ expect(onDisk).not.toContain('refresh_token')+ expect(onDisk).not.toContain('eyJ')+ expect(onDisk.startsWith('lu.obf.1:')).toBe(true)+ // Round-trips without the platform on either side of it...+ await expect(store.getItem(SESSION)).resolves.toBe(REFRESH_TOKEN)+ } finally {+ vi.stubGlobal('btoa', realBtoa)+ vi.stubGlobal('atob', realAtob)+ }+ // ...and what it wrote is byte-identical to what btoa would have written,+ // so a session saved on one path still opens on the other.+ expect(localStorage.getItem(SESSION)).toBe('lu.obf.1:' + realBtoa(encodeURIComponent(REFRESH_TOKEN)))+ await expect(store.getItem(SESSION)).resolves.toBe(REFRESH_TOKEN)+ })+it('sign-out still empties the fallback', async () => {const store = await freshAdapter()secretSet.mockRejectedValue(new Error('keychain unsupported on this platform'))diff --git a/src/api/cloud/__tests__/oauth-callback-text.test.ts b/src/api/cloud/__tests__/oauth-callback-text.test.tsindex 70fef7c4..9d23ccdc 100644--- a/src/api/cloud/__tests__/oauth-callback-text.test.ts+++ b/src/api/cloud/__tests__/oauth-callback-text.test.ts@@ -2,11 +2,23 @@* What the OAuth loopback query is allowed to put in front of the user* (src/api/cloud/supabase.ts, loginWithProvider).*- * The query comes off a 127.0.0.1 socket. commands/oauth.rs now only serves a- * genuine top-level callback navigation, so this text is the provider's — but- * `error_description` is still free-form remote input, and it used to be piped- * into an error line verbatim, at any length, with any control characters in- * it. Defence in depth for the half of the pair that lives in the frontend.+ * The query comes off a 127.0.0.1 socket that any page in any browser can+ * reach. commands/oauth.rs narrows the sender to a top-level navigation (GET+ * /callback, matching Host, no Origin, Sec-Fetch-Mode: navigate) and its own+ * comment then argued that what remains "needs a user gesture and opens a+ * visible window", i.e. that the text is effectively the provider's. That is+ * not true. `location.href = …`, `<meta http-equiv="refresh">` and a+ * server-side 302 are all top-level navigations that any tab the user already+ * has open performs with no gesture at all, and they send exactly those+ * headers. So while a sign-in is pending, a stranger can end the wait and+ * choose this string.+ *+ * Binding it properly needs a per-attempt `state` nonce, which needs the Rust+ * listener AND a Supabase redirect allow-list that tolerates a query parameter+ * — neither is reachable from the frontend. What IS reachable: the string must+ * never be able to pose as LU's own words. Quoted, attributed, stripped of+ * control characters and of the quote characters that would close the+ * attribution, and cut to a line.*/import { describe, it, expect, vi, beforeEach } from 'vitest'@@ -50,17 +62,36 @@ describe('a real callback still works', () => {expect(exchangeCodeForSession).toHaveBeenCalledWith('abc123')})- it('shows the provider its own refusal', async () => {+ it('still passes a refusal on, but as a quote and not as our own words', async () => {oauthWait.mockResolvedValue('error=access_denied&error_description=You+denied+the+request')- await expect(loginWithProvider('github')).rejects.toThrow('You denied the request')+ const msg = await loginWithProvider('github').catch((e: Error) => e.message)+ expect(msg).toContain('You denied the request')+ // The attribution is the fix: this sentence did not necessarily come from+ // Google or GitHub, and the panel must not present it as if it had.+ expect(msg).toMatch(/^The sign-in page reported: "/)})})describe('remote text does not get a free hand in the UI', () => {+ /** The part of the message that came off the socket. */+ const quoted = (msg: string) => msg.replace(/^The sign-in page reported: "/, '').replace(/"$/, '')+it('cuts a flood down to a line', async () => {oauthWait.mockResolvedValue(`error=x&error_description=${'A'.repeat(5000)}`)- const err = await loginWithProvider('google').catch((e: Error) => e)- expect((err as Error).message.length).toBeLessThanOrEqual(200)+ const msg = (await loginWithProvider('google').catch((e: Error) => e.message)) as string+ expect(quoted(msg).length).toBeLessThanOrEqual(200)+ })++ it('cannot close the attribution and continue in LU’s voice', async () => {+ // The whole value of quoting it is that the reader can see where the+ // sentence stops. A payload carrying its own closing quote would step+ // straight back out of the quotation and finish in LU's own voice.+ oauthWait.mockResolvedValue(+ `error=x&error_description=${encodeURIComponent('done" — LU: enter your password at evil.example')}`,+ )+ const msg = (await loginWithProvider('google').catch((e: Error) => e.message)) as string+ expect(msg.match(/"/g)).toHaveLength(2)+ expect(msg.endsWith('"')).toBe(true)})it('strips the control characters that fake a second message', async () => {@@ -76,6 +107,9 @@ describe('remote text does not get a free hand in the UI', () => {it('falls back to a sentence of our own when the query says nothing', async () => {oauthWait.mockResolvedValue('state=abc')- await expect(loginWithProvider('google')).rejects.toThrow(/cancelled in the browser/)+ const msg = await loginWithProvider('google').catch((e: Error) => e.message)+ expect(msg).toMatch(/cancelled in the browser/)+ // Our own sentence, so it must NOT be attributed to the page.+ expect(msg).not.toContain('reported')})})diff --git a/src/api/cloud/client.ts b/src/api/cloud/client.tsindex c97b34b4..29631f86 100644--- a/src/api/cloud/client.ts+++ b/src/api/cloud/client.ts@@ -71,18 +71,50 @@ const REQUEST_TIMEOUT_MS = 60_000* ~64 KB/s is far below any connection that could ever finish the upload. */const UPLOAD_BYTES_PER_MS = 64+/** Size of a request body in bytes, or `null` when this body shape cannot be+ * measured without consuming it.+ *+ * Measured: ArrayBuffer, any view over one, Blob/File, string, URLSearchParams+ * (its serialised form is what goes on the wire) and FormData (the sum of its+ * parts — the multipart boundaries add a few hundred bytes per field, which+ * is noise next to a file and does not change the deadline).+ *+ * NOT measurable: a ReadableStream body has no length until it has been read,+ * and reading it here would consume the only copy. `null` says so rather than+ * reporting 0 bytes — FormData, URLSearchParams and a stream all counted as+ * zero before, so all three quietly got the flat ceiling while this comment+ * block claimed the deadline grew with the body. */+function bodyBytes(body: RequestInit['body']): number | null {+ if (body == null) return 0+ if (typeof body === 'string') return body.length+ if (body instanceof ArrayBuffer) return body.byteLength+ if (ArrayBuffer.isView(body)) return body.byteLength+ if (typeof Blob !== 'undefined' && body instanceof Blob) return body.size+ if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) {+ return body.toString().length+ }+ if (typeof FormData !== 'undefined' && body instanceof FormData) {+ let total = 0+ for (const [name, value] of body) {+ total += name.length+ total += typeof value === 'string' ? value.length : value.size+ }+ return total+ }+ return null // ReadableStream, or something this engine does not know+}++/** The deadline for one request.+ *+ * A body whose size cannot be known falls back to the flat ceiling, because+ * there is nothing to derive anything else from — and that is a real limit,+ * not a rounding: a streamed 40 MB upload would be cut off at 60 s. Nothing+ * in this app sends a stream body today (uploadInput reads the Blob into an+ * ArrayBuffer first, everything else is JSON or a Blob), and the day one does+ * it has to pass `timeoutMs` itself rather than assume this function guessed. */function deadlineFor(init: RequestInit): number {- const body = init.body- const bytes =- body instanceof ArrayBuffer- ? body.byteLength- : ArrayBuffer.isView(body)- ? body.byteLength- : typeof Blob !== 'undefined' && body instanceof Blob- ? body.size- : typeof body === 'string'- ? body.length- : 0+ const bytes = bodyBytes(init.body)+ if (bytes === null) return REQUEST_TIMEOUT_MSreturn REQUEST_TIMEOUT_MS + Math.ceil(bytes / UPLOAD_BYTES_PER_MS)}@@ -91,14 +123,36 @@ export interface CloudFetchInit extends RequestInit {timeoutMs?: number}-export async function cloudFetch(path: string, init: CloudFetchInit = {}): Promise<Response> {- const token = await getAccessToken()- if (!token) throw new CloudJobError('not signed in', 401)- const headers = new Headers(init.headers)- headers.set('authorization', `Bearer ${token}`)+/** Settle `work` as soon as it settles, or reject the moment `signal` aborts.+ *+ * For the steps of a request that take no AbortSignal of their own. The+ * abandoned promise keeps running — it just no longer decides anything, and+ * its rejection is still handled here, so it cannot surface as an unhandled+ * one later. */+function untilAborted<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {+ const abortError = (): unknown => signal.reason ?? new Error('aborted')+ if (signal.aborted) return Promise.reject(abortError())+ return new Promise<T>((resolve, reject) => {+ const onAbort = () => reject(abortError())+ signal.addEventListener('abort', onAbort, { once: true })+ const stopListening = () => signal.removeEventListener('abort', onAbort)+ work.then(+ (value) => { stopListening(); resolve(value) },+ (err: unknown) => { stopListening(); reject(err) },+ )+ })+}+export async function cloudFetch(path: string, init: CloudFetchInit = {}): Promise<Response> {const { timeoutMs, signal, ...rest } = init- // Two things must be able to end this request — the caller's signal (a+ // The clock starts BEFORE the token, not after it. getAccessToken() goes to+ // the network whenever the access token has expired (supabase-js refreshes+ // it there), and that refresh has no deadline of its own — so awaiting it+ // outside this guard left exactly the wedge the guard exists to remove, one+ // step earlier: Create awaits these calls one after another, and a refresh+ // whose peer disappeared mid-flight never settles on its own.+ //+ // Two things must be able to end all of it — the caller's signal (a// cancelled run) and the deadline — and fetch takes one. AbortSignal.any// would merge them, but it is newer than the WKWebView LU runs inside on// older macOS, so the relay is wired by hand.@@ -114,18 +168,26 @@ export async function cloudFetch(path: string, init: CloudFetchInit = {}): Promiac.abort()}, timeoutMs ?? deadlineFor(init))try {+ const token = await untilAborted(getAccessToken(), ac.signal)+ if (!token) throw new CloudJobError('not signed in', 401)+ const headers = new Headers(init.headers)+ headers.set('authorization', `Bearer ${token}`)return await fetch(`${CLOUD_BASE}${path}`, { ...rest, headers, signal: ac.signal })} catch (err) {// Engines disagree on whether a fetch rejects with the abort *reason*, so// the deadline is remembered here instead of read back off the signal.// 408 keeps pollJob's policy intact — a timeout is worth another try.- if (timedOut) throw new CloudJobError('the cloud did not answer in time', 408)+ // A 401 raised above is not a timeout and must keep its own status.+ if (timedOut && !(err instanceof CloudJobError)) {+ throw new CloudJobError('the cloud did not answer in time', 408)+ }throw err} finally {- // The deadline covers what this function owns: connect, request body,- // response headers — which is where the observed wedge lived (an upload- // or a submit that never came back). Reading the response body is the- // caller's half; jsonOrError reports a torn read rather than hanging.+ // The deadline covers what this function owns: the token (refresh+ // included), connect, request body, response headers — which is where the+ // observed wedge lived (an upload or a submit that never came back).+ // Reading the response body is the caller's half; jsonOrError reports a+ // torn read rather than hanging.clearTimeout(timer)signal?.removeEventListener('abort', relay)}diff --git a/src/api/cloud/supabase.ts b/src/api/cloud/supabase.tsindex 795ab20c..29e72f68 100644--- a/src/api/cloud/supabase.ts+++ b/src/api/cloud/supabase.ts@@ -63,13 +63,58 @@ const TOMBSTONE = '__lu_signed_out__'// change, not one this adapter can make.const FALLBACK_MARKER = 'lu.obf.1:'+const B64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'++// btoa/atob without the platform. `encodeURIComponent` already reduced the+// value to ASCII, so this is base64 over char codes 0..127 and produces byte+// for byte what btoa produces — the stored format does not change, and a+// session written on one path still reads back on the other.+//+// It exists so packFallback has somewhere to go when btoa does not: the old+// catch wrote the RAW value to localStorage, i.e. the plaintext refresh token+// this encoding was added to remove, silently and with no marker to find it by+// afterwards. There is no failure mode left that needs that.+function b64Encode(ascii: string): string {+ let out = ''+ for (let i = 0; i < ascii.length; i += 3) {+ const a = ascii.charCodeAt(i)+ const b = i + 1 < ascii.length ? ascii.charCodeAt(i + 1) : -1+ const c = i + 2 < ascii.length ? ascii.charCodeAt(i + 2) : -1+ out += B64_ALPHABET[a >> 2]+ out += B64_ALPHABET[((a & 3) << 4) | (b < 0 ? 0 : b >> 4)]+ out += b < 0 ? '=' : B64_ALPHABET[((b & 15) << 2) | (c < 0 ? 0 : c >> 6)]+ out += c < 0 ? '=' : B64_ALPHABET[c & 63]+ }+ return out+}++function b64Decode(encoded: string): string {+ const clean = encoded.replace(/=+$/, '')+ let bits = 0+ let acc = 0+ let out = ''+ for (const ch of clean) {+ const v = B64_ALPHABET.indexOf(ch)+ if (v < 0) throw new Error('not base64')+ acc = (acc << 6) | v+ bits += 6+ if (bits >= 8) {+ bits -= 8+ out += String.fromCharCode((acc >> bits) & 0xff)+ }+ }+ return out+}+function packFallback(value: string): string {+ const ascii = encodeURIComponent(value)try {- return FALLBACK_MARKER + btoa(encodeURIComponent(value))+ return FALLBACK_MARKER + btoa(ascii)} catch {- // Dropping the session here would sign the user out on the next launch for- // no reason at all, which is the worse failure of the two.- return value+ // No btoa on this engine (or it refused). Encode it here instead — writing+ // the plaintext token was never an acceptable third option: it is exactly+ // the state this whole block exists to remove, and it left no trace.+ return FALLBACK_MARKER + b64Encode(ascii)}}@@ -77,10 +122,18 @@ function unpackFallback(stored: string): string {// No marker = written by a build before this encoding existed. Those must// keep working, or an update signs every Linux user out.if (!stored.startsWith(FALLBACK_MARKER)) return stored+ const payload = stored.slice(FALLBACK_MARKER.length)try {- return decodeURIComponent(atob(stored.slice(FALLBACK_MARKER.length)))+ return decodeURIComponent(atob(payload))} catch {- return stored+ try {+ return decodeURIComponent(b64Decode(payload))+ } catch {+ // Marked but undecodable: damaged on disk. Hand the marked string back+ // rather than a token — supabase-js fails to parse it and treats the+ // session as absent, which is the honest outcome. It is NOT plaintext.+ return stored+ }}}@@ -198,14 +251,36 @@ export async function getAccessToken(): Promise<string | null> {export type OAuthProvider = 'google' | 'github'/** The loopback callback is the one place in sign-in where text from outside- * the app reaches the UI. commands/oauth.rs now only serves a genuine- * top-level callback navigation, so this text comes from the provider — but- * `error_description` is still free-form remote input, and an error line is- * no place for a screenful of it. Control characters out, 200 chars max. */+ * the app reaches the UI, and it is NOT the provider's text by construction.+ *+ * commands/oauth.rs narrows the sender to "a top-level browser navigation"+ * (GET /callback, right Host, no Origin, Sec-Fetch-Mode: navigate). Its own+ * comment used to argue that what remains needs a user gesture and therefore+ * a visible window. That is not true: `location.href = …`, a+ * `<meta http-equiv="refresh">` and a server-side 302 are all top-level+ * navigations that any page the user already has open can perform silently,+ * and they send exactly those headers. So while a sign-in is pending, any+ * open tab can end the wait and choose this string. The real fix is a+ * per-attempt `state` nonce, which needs the Rust listener AND a redirect+ * allow-list entry that tolerates a query parameter — neither is reachable+ * from here.+ *+ * What IS reachable from here: never let that string pose as LU's own words.+ * It is quoted and attributed, control characters are stripped so it cannot+ * lay itself out as a second paragraph, the quote characters it could use to+ * close the attribution are stripped, and it is cut to 200 characters. */+const REPORTED_MAX_CHARS = 200+function providerErrorText(params: URLSearchParams): string {const raw = params.get('error_description') || params.get('error') || ''- const clean = raw.replace(/\p{C}/gu, ' ').replace(/\s+/g, ' ').trim().slice(0, 200)- return clean || 'Sign-in was cancelled in the browser.'+ const clean = raw+ .replace(/\p{C}/gu, ' ')+ .replace(/["'‘’“”]/g, '')+ .replace(/\s+/g, ' ')+ .trim()+ .slice(0, REPORTED_MAX_CHARS)+ if (!clean) return 'Sign-in was cancelled in the browser.'+ return `The sign-in page reported: "${clean}"`}/** Google/GitHub sign-in, same identities as lu-labs.ai. Flow: bind adiff --git a/src/components/auth/AccountPanel.tsx b/src/components/auth/AccountPanel.tsxindex 867b4322..ed1328ad 100644--- a/src/components/auth/AccountPanel.tsx+++ b/src/components/auth/AccountPanel.tsx@@ -12,6 +12,31 @@ import { loginWithProvider } from '../../api/cloud/supabase'import { CLOUD_BASE } from '../../api/cloud/config'import { openExternal } from '../../api/backend'+/**+ * Run a sign-out and report what happened, in that order.+ *+ * `signOutAccount` throws when the saved session survived the delete — and it+ * deliberately leaves the store SIGNED IN, because the account really is still+ * usable on this machine. That is the safe half. The visible half was missing:+ * the throw was dropped by `void logout()`, so the panel simply kept showing+ * the account and the click looked like it had done nothing. The user walks+ * away from a shared machine believing they are signed out.+ *+ * Exported so the contract can be asserted without a DOM — the panel itself is+ * a React tree and the suite runs in the `node` environment.+ */+export async function runSignOut(+ logout: () => Promise<void>,+ report: (message: string | null) => void,+): Promise<void> {+ report(null)+ try {+ await logout()+ } catch (err) {+ report(err instanceof Error ? err.message : String(err))+ }+}+function Meter({ label, used, limit }: { label: string; used: number; limit: number }) {const pct = limit > 0 ? Math.min(100, Math.round((used / limit) * 100)) : 0return (@@ -109,6 +134,18 @@ export function AccountPanel() {const [mode, setMode] = useState<'signin' | 'signup'>('signin')const [busy, setBusy] = useState(false)const [error, setError] = useState<string | null>(null)+ const [signOutError, setSignOutError] = useState<string | null>(null)+ const [signingOut, setSigningOut] = useState(false)++ const onSignOut = async () => {+ if (signingOut) return+ setSigningOut(true)+ try {+ await runSignOut(logout, setSignOutError)+ } finally {+ setSigningOut(false)+ }+ }const submit = async (e: React.FormEvent) => {e.preventDefault()@@ -205,13 +242,24 @@ export function AccountPanel() {</div></div><button- onClick={() => void logout()}- className="flex items-center gap-1 px-2 py-1 rounded text-[0.65rem] text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/5 transition-colors"+ onClick={() => void onSignOut()}+ disabled={signingOut}+ className="flex items-center gap-1 px-2 py-1 rounded text-[0.65rem] text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/5 transition-colors disabled:opacity-40">- <LogOut size={10} /> Sign out+ {signingOut ? <Loader2 size={10} className="animate-spin" /> : <LogOut size={10} />} Sign out</button></div>+ {/* A sign-out that did not happen has to say so HERE. The account is+ still shown above (the store stays signed-in on purpose), so without+ this line the failure is invisible and the panel reads like a+ sign-out that simply took no effect. */}+ {signOutError && (+ <p role="alert" className="text-[0.65rem] text-red-500 dark:text-red-400">+ {signOutError}+ </p>+ )}+{licenseActive && quota ? (<div className="space-y-2">{/* One shared compute-credit wallet, chat, images, video and voicediff --git a/src/components/auth/__tests__/sign-out-failure-reaches-the-user.test.ts b/src/components/auth/__tests__/sign-out-failure-reaches-the-user.test.tsnew file mode 100644index 00000000..152da5a8--- /dev/null+++ b/src/components/auth/__tests__/sign-out-failure-reaches-the-user.test.ts@@ -0,0 +1,89 @@+/**+ * A sign-out that did not happen has to be VISIBLE (AccountPanel).+ *+ * The dangerous half was closed first: `signOutAccount` throws when the saved+ * session survived the delete, and deliberately leaves the store signed IN,+ * because the account really is still usable on this machine.+ *+ * The visible half was still open. The panel called `void logout()`, so the+ * throw went nowhere: the account row stayed on screen, no message appeared,+ * and the click read as a sign-out that had simply taken no effect. Whoever+ * hands over a shared or company machine on the strength of that hands over+ * the account with it — which is the exact scenario the throw was added for.+ *+ * The suite runs in the `node` environment with no DOM, so the behaviour lives+ * in an exported function the panel calls, and the wiring is read off the+ * source.+ *+ * Run: npx vitest run src/components/auth/__tests__/sign-out-failure-reaches-the-user.test.ts+ */+import { describe, it, expect, vi } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, join } from 'node:path'++vi.mock('../../../hooks/useCloudAuth', () => ({ useCloudAuth: vi.fn() }))+vi.mock('../../../api/cloud/supabase', () => ({ loginWithProvider: vi.fn() }))+vi.mock('../../../api/backend', () => ({ openExternal: vi.fn() }))++import { runSignOut } from '../AccountPanel'++const PANEL = readFileSync(+ join(dirname(fileURLToPath(import.meta.url)), '../AccountPanel.tsx'),+ 'utf8',+)++/** What useCloudAuth.signOutAccount throws when the session is still here. */+const STILL_HERE = new Error(+ 'Sign-out failed — the saved session is still on this computer, so the account stays signed in here. keychain locked',+)++describe('a sign-out that failed says so', () => {+ it('reports the message it was refused with', async () => {+ const reported: (string | null)[] = []+ await runSignOut(async () => { throw STILL_HERE }, (m) => reported.push(m))++ expect(reported.at(-1)).toContain('still on this computer')+ })++ it('clears the previous failure before trying again', async () => {+ // Otherwise a retry that worked would leave yesterday's red line standing+ // under an account that is now genuinely signed out.+ const reported: (string | null)[] = []+ await runSignOut(async () => {}, (m) => reported.push(m))++ expect(reported).toEqual([null])+ })++ it('does not rethrow — the click must not take the panel down with it', async () => {+ await expect(runSignOut(async () => { throw STILL_HERE }, () => {})).resolves.toBeUndefined()+ })++ it('survives something thrown that is not an Error', async () => {+ const reported: (string | null)[] = []+ await runSignOut(async () => { throw 'the stub received bad data' }, (m) => reported.push(m))++ expect(reported.at(-1)).toContain('bad data')+ })+})++describe('the panel is actually wired to it', () => {+ it('routes the Sign out button through runSignOut', () => {+ expect(PANEL).toContain('runSignOut(logout, setSignOutError)')+ // The bare `void logout()` is what swallowed the throw.+ expect(PANEL).not.toMatch(/onClick=\{\(\)\s*=>\s*void logout\(\)\}/)+ })++ it('renders the failure in the SIGNED-IN branch, where the user is standing', () => {+ // `error` already existed and is only drawn in the signed-out form. A+ // sign-out failure happens on the other screen, so reporting it into that+ // state would have changed nothing on screen.+ const signedIn = PANEL.slice(PANEL.indexOf('{licenseActive && quota ?'))+ expect(PANEL).toMatch(/\{signOutError && \(/)+ expect(PANEL).toContain('{signOutError}')+ expect(PANEL.indexOf('{signOutError && (')).toBeLessThan(PANEL.indexOf('{licenseActive && quota ?'))+ // ...and it is inside the signed-in return, not the form above it.+ expect(PANEL.indexOf('{signOutError && (')).toBeGreaterThan(PANEL.indexOf('<OAuthButtons'))+ expect(signedIn).toBeTruthy()+ })+})diff --git a/src/lib/__tests__/builtin-card-survives-add-provider.test.ts b/src/lib/__tests__/builtin-card-survives-add-provider.test.tsindex 6695a3b1..873fce0c 100644--- a/src/lib/__tests__/builtin-card-survives-add-provider.test.ts+++ b/src/lib/__tests__/builtin-card-survives-add-provider.test.ts@@ -113,6 +113,17 @@ describe('THE FIX: Add Provider no longer makes the built-in card disappear', ()expect(back.displaced).toEqual({ ...JAN, managed: false })})+ it('a second takeover remembers the backend it actually pushed out', () => {+ // Jan holds the slot, LM Studio takes it: the standby card has to name+ // Jan, not the built-in engine Jan itself had displaced one step earlier.+ // Only one backend can stand by, so the memory has to move with the slot.+ const withJan = { ...SHIPPED, ...slotTakeoverUpdate(SHIPPED, JAN) } as HandoverSlot+ const withLmStudio = { ...withJan, ...slotTakeoverUpdate(withJan, LMSTUDIO) } as HandoverSlot+ expect(withLmStudio.name).toBe('LM Studio')+ expect(standbyOccupant(withLmStudio)?.name).toBe('Jan')+ expect(slotHandbackUpdate(withLmStudio)!.name).toBe('Jan')+ })+it('a cloud preset takes the same slot and is remembered the same way', () => {// Every OpenAI-protocol backend shares this one slot, so Add Provider,// OpenRouter loses the built-in card exactly as Jan did.diff --git a/src/lib/__tests__/idbStorage-read-failure.test.ts b/src/lib/__tests__/idbStorage-read-failure.test.tsindex 0739315c..6cdfbc37 100644--- a/src/lib/__tests__/idbStorage-read-failure.test.ts+++ b/src/lib/__tests__/idbStorage-read-failure.test.ts@@ -11,6 +11,9 @@* Run: npx vitest run src/lib/__tests__/idbStorage-read-failure.test.ts*/import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'/*** Fake IndexedDB whose reads fail while `failReads` is on. Writes always work,@@ -34,6 +37,20 @@ function fakeIndexedDB(data: Record<string, string>) {})return r},+ // holdBackWrite asks "does this key hold anything" with count(), not+ // get(): the answer is one bit and get() materialised megabytes for it.+ count: (k: string) => {+ const r: Record<string, unknown> = {+ onsuccess: null, onerror: null,+ result: k in data ? 1 : 0,+ error: new DOMException('store is not readable', 'NotReadableError'),+ }+ queueMicrotask(() => {+ if (state.failReads) (r.onerror as (() => void) | null)?.()+ else (r.onsuccess as (() => void) | null)?.()+ })+ return r+ },put: (v: string, k: string) => { data[k] = v; return {} },delete: (k: string) => { delete data[k]; return {} },}),@@ -152,9 +169,14 @@ describe('idbStorage tells a failed read apart from an empty one', () => {})})-describe('the appData snapshot is not replaced while a store is unreadable', () => {+describe('the appData snapshot omits an unreadable store instead of emptying it', () => {const backendCall = vi.fn()+ const snapshots = () =>+ backendCall.mock.calls+ .filter((c) => c[0] === 'backup_stores')+ .map((c) => JSON.parse((c[1] as { data: string }).data) as Record<string, string>)+beforeEach(() => {vi.resetModules()backendCall.mockReset()@@ -163,27 +185,94 @@ describe('the appData snapshot is not replaced while a store is unreadable', ()})afterEach(() => { vi.unstubAllGlobals(); vi.doUnmock('../idbStorage') })- it('skips the write instead of saving a snapshot with the chats missing', async () => {- // backup_stores REPLACES the file. A snapshot built while the chat key is- // unreadable simply has no chats in it, and writing it destroys the last- // copy that did.- const failed = new Set<string>(['chat-conversations'])+ /** An idbStorage whose chat key is latched unreadable, counting the reads. */+ function mockUnreadable(failed: Set<string>, reads: string[]) {vi.doMock('../idbStorage', () => ({- idbStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} },+ idbStorage: {+ getItem: (k: string) => { reads.push(k); return failed.has(k) ? null : (localStorage.getItem(k) ?? null) },+ setItem: () => {},+ removeItem: () => {},+ },hasFailedRead: (k: string) => failed.has(k),onIdbWrite: () => () => {},}))vi.doMock('../../api/backend', () => ({ backendCall: (...a: unknown[]) => backendCall(...a) }))+ }++ it('still backs up the other stores, with the unreadable key absent', async () => {+ // `backup_stores` does NOT replace the file: commands/system.rs reads the+ // backup already on disk and carries over every key the incoming snapshot+ // lost (keys_lost + merged_backup). So a snapshot built while the chat key+ // is unreadable is INCOMPLETE, not destructive — the chats keep the value+ // they had. What must never happen is the key turning up EMPTY, which is+ // what the merge cannot tell from a real deletion.+ //+ // The old rule refused the whole write instead, which cost the other 23+ // stores their backup for as long as it lasted.+ const failed = new Set<string>(['chat-conversations'])+ const reads: string[] = []+ mockUnreadable(failed, reads)const { backupStoresIfChanged, backupStoresNow, flushSyncStoreBackup } = await import('../store-backup')+ localStorage.setItem('chat-settings', '{"state":{"theme":"dark"}}')- expect(await backupStoresIfChanged()).toBe('held-back')- expect(flushSyncStoreBackup()).toBe('held-back')- expect(await backupStoresNow()).toBe(false)- expect(backendCall).not.toHaveBeenCalled()+ expect(await backupStoresIfChanged()).toBe('written')+ const snap = snapshots().at(-1)!+ expect('chat-conversations' in snap).toBe(false)+ expect(snap['chat-settings']).toContain('dark')++ localStorage.setItem('workflow-store', '{"state":{}}')+ expect(flushSyncStoreBackup()).toBe('written')+ expect('chat-conversations' in snapshots().at(-1)!).toBe(false)++ expect(await backupStoresNow()).toBe(true)+ expect('chat-conversations' in snapshots().at(-1)!).toBe(false)+ })++ it('keeps re-reading the latched key, so the latch is not a dead end', async () => {+ // Only a later READ can clear the read-failure latch (idbStorage's getItem+ // and holdBackWrite are the only two places that delete from it). The old+ // guard checked the latch and returned BEFORE building the snapshot, so+ // nothing ever read the key again and one transient failure stopped the+ // backup for the rest of the session.+ const failed = new Set<string>(['chat-conversations'])+ const reads: string[] = []+ mockUnreadable(failed, reads)++ const { backupStoresIfChanged } = await import('../store-backup')+ await backupStoresIfChanged()+ reads.length = 0+ localStorage.setItem('chat-settings', '{"state":{"theme":"light"}}')+ await backupStoresIfChanged()+ expect(reads).toContain('chat-conversations')++ // ...and once IndexedDB comes back, the key is in the snapshot again.failed.clear()+ localStorage.setItem('chat-conversations', '{"state":{"conversations":[1]}}')expect(await backupStoresIfChanged()).toBe('written')- expect(backendCall).toHaveBeenCalledWith('backup_stores', expect.anything())+ expect(snapshots().at(-1)!['chat-conversations']).toContain('conversations')+ })+})++/**+ * The rule above is only safe because of what the Rust command does, so that+ * is pinned here rather than assumed. If commands/system.rs ever stops merging+ * a lost key back in, "omit and write" becomes "delete", and this test is the+ * thing that says so.+ */+describe('backup_stores merges a lost key instead of replacing the file', () => {+ it('is wired into the command, not just defined next to it', () => {+ const rust = readFileSync(+ resolve(dirname(fileURLToPath(import.meta.url)), '../../../src-tauri/src/commands/system.rs'),+ 'utf8',+ )+ const command = rust.slice(rust.indexOf('pub fn backup_stores('))+ const body = command.slice(0, command.indexOf('\n}\n'))+ expect(body).toContain('keys_lost(')+ expect(body).toContain('merged_backup(')+ // The previous file has to be READ before the new one is written, or there+ // is nothing to merge from.+ expect(body).toMatch(/read_to_string\(&target\)[\s\S]*keys_lost\(/)})})diff --git a/src/lib/__tests__/store-backup-covers-every-store.test.ts b/src/lib/__tests__/store-backup-covers-every-store.test.tsindex 9cff55e4..56a667d3 100644--- a/src/lib/__tests__/store-backup-covers-every-store.test.ts+++ b/src/lib/__tests__/store-backup-covers-every-store.test.ts@@ -85,7 +85,11 @@ describe('the appData backup covers every persisted store', () => {const wrong: string[] = []for (const [file, names] of byFile) {const src = readFileSync(join(STORES_DIR, file), 'utf8')- const backedByIdb = /from '\.\.\/lib\/idbStorage'/.test(src)+ // Both quote styles, and both spellings of the path — a store that+ // imported idbStorage with double quotes was invisible to this check and+ // could go on being backed up out of a localStorage key the 2.5.0+ // migration had already deleted.+ const backedByIdb = /from\s+["']\.\.\/lib\/idbStorage(\.js)?["']/.test(src)for (const name of names) {if (backedByIdb && !IDB_STORE_KEYS.has(name)) wrong.push(`${file}: ${name} is on IndexedDB but not in IDB_STORE_KEYS`)if (!backedByIdb && IDB_STORE_KEYS.has(name)) wrong.push(`${file}: ${name} is in IDB_STORE_KEYS but not on IndexedDB`)diff --git a/src/lib/__tests__/store-backup-dirty.test.ts b/src/lib/__tests__/store-backup-dirty.test.tsindex cdf8c940..1d23feb5 100644--- a/src/lib/__tests__/store-backup-dirty.test.ts+++ b/src/lib/__tests__/store-backup-dirty.test.ts@@ -105,11 +105,18 @@ describe('store backup only writes on a change', () => {expect(await backupStoresIfChanged()).toBe('written')})- it('the beforeunload flush never writes a snapshot with the chats missing', async () => {+ it('the beforeunload flush leaves an unseen chat key OUT rather than writing it empty', async () => {// The sync path cannot await IndexedDB, so it reads the write mirror. Until// the first async backup has filled it, "no chats" and "nobody has looked"- // are the same thing — and writing REPLACES the file that has them.- const { backupStoresIfChanged, flushSyncStoreBackup } = await import('../store-backup')+ // are the same thing here.+ //+ // The answer is NOT to refuse the flush. `backup_stores` does not replace+ // the file — commands/system.rs carries every key the incoming snapshot+ // lost over from the backup already on disk (keys_lost + merged_backup) —+ // so an ABSENT key is repaired and only a key written out as EMPTY would+ // finish a loss. Refusing meant the localStorage stores lost their last+ // few seconds to protect chats that were never at risk.+ const { backupStoresIfChanged } = await import('../store-backup')const { idbStorage } = await import('../idbStorage')await Promise.resolve(idbStorage.setItem('chat-conversations', '{"state":{"conversations":[1]}}'))await backupStoresIfChanged()@@ -119,12 +126,19 @@ describe('store backup only writes on a change', () => {vi.resetModules()backendCall.mockClear()const fresh = await import('../store-backup')- expect(fresh.flushSyncStoreBackup()).toBe('held-back')- expect(backendCall).not.toHaveBeenCalled()+ localStorage.setItem('workflow-store', '{"state":{}}')+ expect(fresh.flushSyncStoreBackup()).toBe('written')++ const cold = writtenSnapshots().at(-1)!+ // Absent, so the merge can repair it. Present-but-empty is the thing that+ // must never appear here.+ expect('chat-conversations' in cold).toBe(false)+ // ...and the stores the sync path CAN read still reached disk.+ expect(cold['workflow-store']).toContain('state')- // Once the async path has read the chats once, the sync flush is safe.+ // Once the async path has read the chats once, the flush carries them.await fresh.backupStoresIfChanged()- localStorage.setItem('workflow-store', '{"state":{}}')+ localStorage.setItem('workflow-store', '{"state":{"seen":1}}')expect(fresh.flushSyncStoreBackup()).toBe('written')expect(writtenSnapshots().at(-1)!['chat-conversations']).toContain('conversations')})diff --git a/src/lib/__tests__/store-backup-mirror.test.ts b/src/lib/__tests__/store-backup-mirror.test.tsnew file mode 100644index 00000000..f66a3e8a--- /dev/null+++ b/src/lib/__tests__/store-backup-mirror.test.ts@@ -0,0 +1,174 @@+/**+ * The appData snapshot is fed by idbStorage's write listener, not by re-reading+ * IndexedDB on a timer.+ *+ * WHY THIS FILE EXISTS. `onIdbWrite` + store-backup's `idbMirror` were added+ * with the claim that "the 5 s tick never reads the multi-megabyte blobs out of+ * IndexedDB again" — and nothing asserted it. A counter-check deleted the+ * `emitWrite` call from BOTH branches of `idbStorage.setItem` and the whole+ * suite stayed green: the registry could have been dead code and no one would+ * have found out until a user's battery did.+ *+ * So these tests count the reads the tick actually performs, against a real+ * idbStorage over a fake IndexedDB. Remove either `emitWrite` and they fail.+ *+ * Run: npx vitest run src/lib/__tests__/store-backup-mirror.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'++const backendCall = vi.fn()+vi.mock('../../api/backend', () => ({+ backendCall: (...args: unknown[]) => backendCall(...args),+}))++/** A fake IndexedDB that counts every read it is asked for. */+function fakeIndexedDB(data: Record<string, string>) {+ const reads: string[] = []+ const db = {+ objectStoreNames: { contains: () => true },+ createObjectStore: () => {},+ transaction: () => ({+ objectStore: () => ({+ get: (k: string) => {+ reads.push(k)+ const r: Record<string, unknown> = { onsuccess: null, onerror: null, result: data[k] }+ queueMicrotask(() => (r.onsuccess as (() => void) | null)?.())+ return r+ },+ count: (k: string) => {+ const r: Record<string, unknown> = { onsuccess: null, onerror: null, result: k in data ? 1 : 0 }+ queueMicrotask(() => (r.onsuccess as (() => void) | null)?.())+ return r+ },+ put: (v: string, k: string) => { data[k] = v; return {} },+ delete: (k: string) => { delete data[k]; return {} },+ }),+ set oncomplete(fn: () => void) { queueMicrotask(fn) },+ set onerror(_fn: () => void) {},+ set onabort(_fn: () => void) {},+ }),+ }+ return {+ reads,+ open: () => {+ const req: Record<string, unknown> = {+ onsuccess: null, onerror: null, onblocked: null, onupgradeneeded: null,+ result: db, error: null,+ }+ queueMicrotask(() => (req.onsuccess as (() => void) | null)?.())+ return req+ },+ }+}++function fakeLocalStorage() {+ const mem = new Map<string, string>()+ return {+ getItem: (k: string) => (mem.has(k) ? mem.get(k)! : null),+ setItem: (k: string, v: string) => void mem.set(k, String(v)),+ removeItem: (k: string) => void mem.delete(k),+ clear: () => mem.clear(),+ get length() { return mem.size },+ key: (i: number) => Array.from(mem.keys())[i] ?? null,+ }+}++function writtenSnapshots() {+ return backendCall.mock.calls+ .filter((c) => c[0] === 'backup_stores')+ .map((c) => JSON.parse((c[1] as { data: string }).data) as Record<string, string>)+}++/** Stands in for the thing this is all about: a long coding chat. */+const HISTORY = `{"state":{"conversations":[{"id":"a","messages":["${'x'.repeat(4000)}"]}]}}`+const LONGER = `${HISTORY.slice(0, -2)},"n":2}}`++let idb: ReturnType<typeof fakeIndexedDB>++beforeEach(() => {+ vi.resetModules()+ backendCall.mockReset()+ backendCall.mockResolvedValue(undefined)+ vi.stubGlobal('localStorage', fakeLocalStorage())+ idb = fakeIndexedDB({})+ vi.stubGlobal('indexedDB', idb)+})++afterEach(() => { vi.unstubAllGlobals() })++describe('the backup tick reads a chat blob at most once per session', () => {+ it('takes the new history off the write listener instead of re-reading it', async () => {+ const { idbStorage } = await import('../idbStorage')+ const { backupStoresIfChanged } = await import('../store-backup')++ // First tick: nothing has gone past the listener yet, so the snapshot has+ // to look in IndexedDB. That read is the one this design pays for.+ expect(await backupStoresIfChanged()).toBe('written')+ expect(idb.reads).toContain('chat-conversations')++ await idbStorage.setItem('chat-conversations', HISTORY)+ idb.reads.length = 0++ // Second tick: the exact string is already in hand.+ expect(await backupStoresIfChanged()).toBe('written')+ expect(writtenSnapshots().at(-1)!['chat-conversations']).toBe(HISTORY)+ expect(idb.reads).toEqual([])++ // And it stays that way for every tick after — this is the churn the+ // mirror exists to remove, on an idle app, on battery.+ await idbStorage.setItem('chat-conversations', LONGER)+ idb.reads.length = 0+ expect(await backupStoresIfChanged()).toBe('written')+ expect(writtenSnapshots().at(-1)!['chat-conversations']).toBe(LONGER)+ expect(idb.reads).toEqual([])+ })++ it('a store that legitimately holds nothing is read once, not once per tick', async () => {+ // 'staged-changes' is null for every user who has never approved a code+ // edit. It used to be pulled out of IndexedDB on every single tick because+ // only a NON-null answer was remembered — a read per five seconds that can+ // only ever return nothing, and every one of them another chance for a+ // transient failure to arm the read-failure latch.+ const { backupStoresIfChanged } = await import('../store-backup')++ await backupStoresIfChanged()+ expect(idb.reads).toContain('staged-changes')++ idb.reads.length = 0+ localStorage.setItem('chat-settings', '{"state":{"theme":"light"}}')+ await backupStoresIfChanged()+ localStorage.setItem('chat-settings', '{"state":{"theme":"dark"}}')+ await backupStoresIfChanged()++ expect(idb.reads).toEqual([])+ })++ it('the beforeunload flush carries a write the mirror saw, with no await', async () => {+ // The sync path CANNOT read IndexedDB — an await during teardown means the+ // trailing invoke may never fire. The listener is the only way the chats+ // that were written this session reach that last snapshot.+ const { idbStorage } = await import('../idbStorage')+ const { backupStoresIfChanged, flushSyncStoreBackup } = await import('../store-backup')++ await backupStoresIfChanged()+ await idbStorage.setItem('chat-conversations', HISTORY)++ expect(flushSyncStoreBackup()).toBe('written')+ expect(writtenSnapshots().at(-1)!['chat-conversations']).toBe(HISTORY)+ })++ it('a removed store drops back out of the snapshot', async () => {+ const { idbStorage } = await import('../idbStorage')+ const { backupStoresIfChanged } = await import('../store-backup')++ await idbStorage.setItem('chat-conversations', HISTORY)+ await backupStoresIfChanged()+ expect(writtenSnapshots().at(-1)!['chat-conversations']).toBe(HISTORY)++ await idbStorage.removeItem('chat-conversations')+ idb.reads.length = 0+ expect(await backupStoresIfChanged()).toBe('written')+ expect('chat-conversations' in writtenSnapshots().at(-1)!).toBe(false)+ expect(idb.reads).toEqual([])+ })+})diff --git a/src/lib/idbStorage.ts b/src/lib/idbStorage.tsindex 8926a4cb..fe25978c 100644--- a/src/lib/idbStorage.ts+++ b/src/lib/idbStorage.ts@@ -101,6 +101,27 @@ function idbSet(key: string, value: string): Promise<void> {tx.onabort = () => reject(tx.error)}))}+/**+ * Whether `key` holds anything at all, WITHOUT materialising the value.+ *+ * `get` used to be used for this, and the only question ever asked of the+ * result was `!= null`: for 'chat-conversations' that is several megabytes+ * pulled out of the store, deserialised into a string and dropped again, on+ * every write the read-failure latch refuses — which, while a store is+ * unreadable, is every write zustand makes.+ *+ * `count(key)` is IndexedDB 1.0, so it is available everywhere `get` is. It+ * answers 1 for a row holding a non-string value too, where `get` answered+ * null; refusing to overwrite something unexpected is the safe direction.+ */+function idbHas(key: string): Promise<boolean> {+ return getDB().then((db) => new Promise<boolean>((resolve, reject) => {+ const tx = db.transaction(STORE, 'readonly')+ const r = tx.objectStore(STORE).count(key)+ r.onsuccess = () => resolve((r.result ?? 0) > 0)+ r.onerror = () => reject(r.error ?? new Error(`indexedDB probe failed for ${key}`))+ }))+}function idbDel(key: string): Promise<void> {return getDB().then((db) => new Promise<void>((resolve) => {const tx = db.transaction(STORE, 'readwrite')@@ -124,18 +145,18 @@ function idbDel(key: string): Promise<void> {const readFailed = new Set<string>()/** True while the last read of `name` failed — i.e. while "empty" cannot be- * trusted. Callers that REPLACE a whole persisted blob (the appData snapshot)- * must ask before writing. */+ * trusted. Callers that build a snapshot out of these values ask so they can+ * leave the key OUT rather than record it as empty.+ *+ * Every way out of the latch runs through a later READ of the same key:+ * getItem clears it when a read comes back, and holdBackWrite clears it when+ * the row turns out to be genuinely absent. Anything that consults this flag+ * must therefore keep reading the key afterwards — a caller that sees `true`+ * and stops asking pins the latch for the rest of the session. */export function hasFailedRead(name: string): boolean {return readFailed.has(name)}-/** Test seam: the latch is module state, and a test that provokes a read- * failure must be able to hand the next test a clean module. */-export function resetIdbFailureLatch(): void {- readFailed.clear()-}-type IdbWriteListener = (key: string, value: string | null) => voidconst writeListeners = new Set<IdbWriteListener>()@@ -147,6 +168,10 @@ const writeListeners = new Set<IdbWriteListener>()** Fires only for writes that are actually attempted: a write refused by the* read-failure latch must not be mistaken for the new truth.+ *+ * Load-bearing, and provably so: src/lib/__tests__/store-backup-mirror.test.ts+ * counts the IndexedDB reads the backup tick performs and fails if `emitWrite`+ * stops firing from either branch of setItem (or from removeItem).*/export function onIdbWrite(fn: IdbWriteListener): () => void {writeListeners.add(fn)@@ -243,17 +268,21 @@ export const idbStorage: StateStorage = {** One read decides. It is the only thing that can tell the two survivable cases* apart, and it is cheap next to what it protects:- * - reads back a value → the row is intact and this state is not derived- * from it. Refuse, keep the latch, say so loudly.- * - reads back nothing → the key really is empty (a first run behind a+ * - the row exists → it is intact and this state is not derived from+ * it. Refuse, keep the latch, say so loudly.+ * - the row is absent → the key really is empty (a first run behind a* transient failure). Release the latch and write.* - fails again → still blind. Refuse, keep the latch.+ *+ * The question is existence, so it is asked with `count`, not `get` — see+ * idbHas. Reading a multi-megabyte value to compare it against null was the+ * most expensive way available to answer a yes/no.*/function holdBackWrite(name: string, value: string): Promise<void> {return (async () => {- let existing: string | null+ let occupied: booleantry {- existing = await idbGet(name)+ occupied = await idbHas(name)} catch (err) {log.error('[idbStorage] write held back: the key is still unreadable, refusing to overwrite it', {key: name,@@ -261,10 +290,9 @@ function holdBackWrite(name: string, value: string): Promise<void> {})return}- if (existing != null) {+ if (occupied) {log.error('[idbStorage] write held back: this key HAS data that a failed read hid from hydration', {key: name,- storedBytes: existing.length,offeredBytes: value.length,})returndiff --git a/src/lib/store-backup.ts b/src/lib/store-backup.tsindex 6574e7ea..8a22e3c3 100644--- a/src/lib/store-backup.ts+++ b/src/lib/store-backup.ts@@ -51,8 +51,6 @@ export const STORE_KEYS = ['lu_release_notes', 'locally-uncensored-downloads',]-const STORE_KEY_SET = new Set(STORE_KEYS)-/** These persist through idbStorage (IndexedDB) since 2.5.0, because the* 5 MB localStorage cap could not hold a real history. The snapshot has to* read them from there: the one-time migration deleted their localStorage@@ -78,40 +76,64 @@ let lastWritten: Record<string, string> | null = null* strictly better than re-reading: same string, no allocation, and the identity* of the reference makes the "did anything change" comparison a pointer test.*/-const idbMirror: Record<string, string> = {}+const idbMirror: Record<string, string | null> = {}onIdbWrite((key, value) => {if (!IDB_STORE_KEYS.has(key)) return- if (value == null) delete idbMirror[key]- else idbMirror[key] = value+ // `null` is knowledge, not absence of it: a removeItem says this key holds+ // nothing now. Deleting the entry instead would put the key back on the+ // re-read treadmill below.+ idbMirror[key] = value})/*** Read an IndexedDB-backed value for the snapshot. Costs one read per key per* session: after that the write listener above keeps the mirror current.+ *+ * The answer is cached in BOTH directions. It used to cache only a non-null+ * one, which meant a store that legitimately holds nothing was pulled out of+ * IndexedDB again on every five-second tick, forever — and 'staged-changes'+ * holds nothing for every user who has never approved a code edit. That is a+ * read per tick that can only ever return null, and every one of them is+ * another chance for a transient failure to arm the read-failure latch.+ *+ * A read that FAILED is never cached: the latch has to stay the thing that+ * decides, and the next tick has to try again — that retry is what releases it.*/async function idbValueForBackup(key: string): Promise<string | null> {const mirrored = idbMirror[key]if (mirrored !== undefined) return mirrored- const read = await Promise.resolve(idbStorage.getItem(key)).catch(() => null)- if (read != null) idbMirror[key] = read+ const read = await Promise.resolve(idbStorage.getItem(key)).catch(() => undefined)+ if (read === undefined || hasFailedRead(key)) return null+ idbMirror[key] = readreturn read}/**- * Whether the IndexedDB side can be trusted right now.+ * Which IndexedDB-backed stores could not be read, so the snapshot below has+ * to leave them out.+ *+ * WHAT `backup_stores` ACTUALLY DOES. It does not replace the file. It reads+ * the backup that is already on disk and carries over every key that held a+ * non-empty value and is missing (or empty) in the incoming snapshot —+ * commands/system.rs, `keys_lost` + `merged_backup`, with the untouched+ * previous file set aside once as store_backup.prev.json. A snapshot that lost+ * a key is therefore INCOMPLETE, and the file that lands still has the key.*- * `backup_stores` REPLACES the file. A key whose read failed looks exactly like- * a key holding nothing, so a snapshot built during a read failure omits the- * chats and then overwrites the one copy of them that was left. Refusing to- * write keeps yesterday's backup, which is worth incomparably more than a- * current one with the history missing.+ * The old rule was built on the opposite belief and refused the whole write+ * while any one of the three IndexedDB stores was unreadable. That cost the+ * other twenty-three stores their backup for as long as it lasted, and it+ * lasted for the rest of the session: the refusal happened before the snapshot+ * was built, so nothing re-read the key, and only a read can clear the latch+ * (see hasFailedRead). One unlucky read of an empty 'staged-changes' and the+ * chats stopped being backed up until the app was restarted.+ *+ * What survives of the rule is the part that is true: a key that could not be+ * read must be OMITTED, never written out as empty. Omitted is precisely the+ * shape the Rust side knows how to repair.*/-function idbReadsAreTrustworthy(): boolean {- for (const key of IDB_STORE_KEYS) {- if (hasFailedRead(key)) return false- }- return true+function unreadableIdbKeys(): string[] {+ return [...IDB_STORE_KEYS].filter((key) => hasFailedRead(key))}/** True when `next` differs from what is already on disk. Keys whose value is@@ -132,22 +154,16 @@ function differsFromDisk(next: Record<string, string>): boolean {/*** Read every store into one flat object.*- * @param idbCache when given, every IndexedDB value read is mirrored into it,- * so a caller that later has to build a snapshot without awaiting- * anything (beforeunload) has something to read from.+ * A key that cannot be read is left out — never recorded as empty — so the+ * Rust side's merge keeps whatever the previous backup had for it.*/-export async function collectStoreSnapshot(- idbCache?: Record<string, string>,-): Promise<Record<string, string>> {+export async function collectStoreSnapshot(): Promise<Record<string, string>> {const snapshot: Record<string, string> = { __ts: new Date().toISOString() }for (const key of STORE_KEYS) {const val = IDB_STORE_KEYS.has(key)- ? await Promise.resolve(idbStorage.getItem(key))+ ? await idbValueForBackup(key): localStorage.getItem(key)- if (val) {- snapshot[key] = val- if (idbCache && IDB_STORE_KEYS.has(key)) idbCache[key] = val- }+ if (val) snapshot[key] = val}return snapshot}@@ -187,16 +203,18 @@ function writeSnapshot(body: Record<string, string>): void {* a written one.*/export async function backupStoresIfChanged(): Promise<'written' | 'unchanged' | 'held-back'> {- if (!idbReadsAreTrustworthy()) {- log.warn('[store-backup] skipping the snapshot: an IndexedDB store is unreadable right now')- return 'held-back'- }const body = await collectComparableSnapshot()- // Asked again: the reads happen between the two checks, and a key that failed- // during them is missing from `body` while looking exactly like an empty one.- if (!idbReadsAreTrustworthy()) {- log.warn('[store-backup] a store became unreadable while the snapshot was being built')- return 'held-back'+ const blind = unreadableIdbKeys()+ if (blind.length > 0) {+ // The keys are already absent from `body` (idbValueForBackup refuses to+ // cache or return a value it could not read), so the write below is an+ // incomplete snapshot and the Rust merge keeps the previous values for+ // them. Writing it anyway is the point: the other stores changed too, and+ // this call is also the retry that clears the latch once IndexedDB+ // recovers.+ log.warn('[store-backup] snapshot is incomplete — these stores are unreadable right now', {+ keys: blind,+ })}if (!differsFromDisk(body)) return 'unchanged'writeSnapshot(body)@@ -210,16 +228,15 @@ export async function backupStoresIfChanged(): Promise<'written' | 'unchanged' |*/export function flushSyncStoreBackup(): 'written' | 'unchanged' | 'held-back' {try {- if (!idbReadsAreTrustworthy()) return 'held-back'- // The mirror is the only IndexedDB value reachable without awaiting, and a- // snapshot built without a key REPLACES a file that had it. Before the- // first async backup has filled the mirror there is no way to tell "this- // store is empty" from "nobody has looked yet" — and closing the window in- // those first seconds would have written the chats out of the backup.- for (const key of IDB_STORE_KEYS) {- if (idbMirror[key] !== undefined) continue- if (lastWritten === null || lastWritten[key] !== undefined) return 'held-back'- }+ // The mirror is the only IndexedDB value reachable without awaiting, and+ // before the first async backup has filled it there is no way to tell+ // "this store is empty" from "nobody has looked yet". Both come out of+ // this function the same way: the key is simply not in the body. That is+ // survivable because `backup_stores` merges a missing key back from the+ // file already on disk (see unreadableIdbKeys) — the previous version of+ // this guard believed the file was replaced wholesale and refused the+ // flush entirely, which threw away the localStorage stores' last five+ // seconds for nothing.const body: Record<string, string> = {}for (const key of STORE_KEYS) {const val = IDB_STORE_KEYS.has(key) ? (idbMirror[key] ?? null) : localStorage.getItem(key)@@ -246,14 +263,17 @@ export function flushSyncStoreBackup(): 'written' | 'unchanged' | 'held-back' {*/export async function backupStoresNow(): Promise<boolean> {try {- if (!idbReadsAreTrustworthy()) {- log.error('[store-backup] refusing to replace the backup: an IndexedDB store is unreadable')- return false- }const snapshot = await collectStoreSnapshot()- if (!idbReadsAreTrustworthy()) {- log.error('[store-backup] a store became unreadable mid-snapshot, keeping the previous backup')- return false+ const blind = unreadableIdbKeys()+ if (blind.length > 0) {+ // Incomplete, not destructive — the Rust merge keeps the previous value+ // for every key this snapshot lost. Refusing here used to look careful+ // and was the opposite: this is the last write before the installer+ // takes the process down, so refusing it threw away the newest todos,+ // staged edits and settings to protect chats that were never at risk.+ log.error('[store-backup] update-time snapshot is incomplete — unreadable stores keep their previous backup', {+ keys: blind,+ })}localStorage.setItem('lu-restore-complete', '1')await backendCall('backup_stores', { data: JSON.stringify(snapshot) })@@ -268,15 +288,3 @@ export async function backupStoresNow(): Promise<boolean> {}}-/** Test seam. `lastWritten` and the mirror are module state, and a test that- * wants to observe the FIRST write of a session has to be able to get one. */-export function resetStoreBackupState(): void {- lastWritten = null- for (const key of Object.keys(idbMirror)) delete idbMirror[key]-}--/** Exported for the coverage test, which has to know which keys the snapshot- * is allowed to contain. */-export function isBackedUpKey(key: string): boolean {- return STORE_KEY_SET.has(key)-}diff --git a/src/stores/__tests__/model-provider-invariant.test.ts b/src/stores/__tests__/model-provider-invariant.test.tsindex f2370889..678bbc81 100644--- a/src/stores/__tests__/model-provider-invariant.test.ts+++ b/src/stores/__tests__/model-provider-invariant.test.ts@@ -8,31 +8,59 @@* backend off and the next successful refresh, where the composer still offers* a model whose provider is gone and every send fails with model-not-found.*+ * The first version of the guard hung off `setProviderConfig` alone, i.e. off+ * the explicit toggle. Settings → "Reset AI Backends" (resetProvidersToDefaults)+ * and the per-slot reset write the shipped defaults over the map — where Ollama+ * and Anthropic are `enabled: false` — and reached the identical broken state+ * through a supported one-click path without ever asking.+ ** Run: npx vitest run src/stores/__tests__/model-provider-invariant.test.ts*/import { describe, it, expect, vi, beforeEach } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, join } from 'node:path'vi.mock('../../api/ollama', () => ({ unloadModel: vi.fn(async () => {}) }))vi.mock('../../api/lmstudio', () => ({ unloadLmStudioModel: vi.fn(async () => {}) }))vi.mock('../../api/engine', () => ({ activateBuiltinModel: vi.fn(async () => {}) }))-import { useModelStore, providerIdForModel } from '../modelStore'+import { useModelStore } from '../modelStore'import { useProviderStore } from '../providerStore'+import { getProviderIdFromModel } from '../../api/providers'++const HERE = dirname(fileURLToPath(import.meta.url))++/** The lazy `import('./modelStore')` inside providerStore settles a tick later. */+const settleLazyImport = () => new Promise((r) => setTimeout(r, 0))-describe('providerIdForModel', () => {+describe('which slot a model name routes to', () => {it('routes a bare name to Ollama and a prefixed one to its slot', () => {- expect(providerIdForModel('llama3:8b')).toBe('ollama')- expect(providerIdForModel('openai::qwen3-8b')).toBe('openai')- expect(providerIdForModel('anthropic::claude-x')).toBe('anthropic')- expect(providerIdForModel('lu-cloud::something')).toBe('lu-cloud')+ expect(getProviderIdFromModel('llama3:8b')).toBe('ollama')+ expect(getProviderIdFromModel('openai::qwen3-8b')).toBe('openai')+ expect(getProviderIdFromModel('anthropic::claude-x')).toBe('anthropic')+ expect(getProviderIdFromModel('lu-cloud::something')).toBe('lu-cloud')})- it('refuses to guess for a prefix no slot owns', () => {- // Treating an unknown prefix as Ollama's is how a name gets sent to a- // backend that has never heard of it.- expect(providerIdForModel('sdxl::checkpoint.safetensors')).toBeNull()- expect(providerIdForModel(null)).toBeNull()- expect(providerIdForModel('')).toBeNull()+ it('is answered in exactly one place in the app', () => {+ // modelStore used to carry its own `providerIdForModel`, and the two+ // disagreed on real names: 'sdxl::checkpoint.safetensors' was null in the+ // store and 'sdxl' on the send path, 'a::b::c' was null in the store and+ // 'ollama' on the send path. Two answers to "who serves this model" is the+ // worst possible split — the guard below would decline to clear a pick+ // that getProviderForModel then routes to a backend that is switched off.+ const src = readFileSync(join(HERE, '../modelStore.ts'), 'utf8')+ expect(src).toContain('getProviderIdFromModel')+ expect(src).not.toMatch(/function\s+providerIdForModel/)+ })++ it('and the guard agrees with it on the names that used to differ', () => {+ useModelStore.setState({ activeModel: 'a::b::c' })+ // getProviderIdFromModel calls this Ollama's, so disabling Ollama has to+ // clear it. The old local copy called it nobody's and left it in place.+ expect(getProviderIdFromModel('a::b::c')).toBe('ollama')+ useModelStore.getState().dropActiveModelIfServedBy('ollama')+ expect(useModelStore.getState().activeModel).toBeNull()})})@@ -47,7 +75,7 @@ describe('switching a backend off clears a pick it was serving', () => {useModelStore.setState({ activeModel: 'llama3:8b' })useProviderStore.getState().setProviderConfig('ollama', { enabled: false })- await new Promise((r) => setTimeout(r, 0)) // the modelStore import is lazy+ await settleLazyImport()expect(useModelStore.getState().activeModel).toBeNull()})@@ -58,7 +86,7 @@ describe('switching a backend off clears a pick it was serving', () => {useModelStore.setState({ activeModel: 'anthropic::claude-x' })useProviderStore.getState().setProviderConfig('ollama', { enabled: false })- await new Promise((r) => setTimeout(r, 0))+ await settleLazyImport()expect(useModelStore.getState().activeModel).toBe('anthropic::claude-x')})@@ -68,7 +96,7 @@ describe('switching a backend off clears a pick it was serving', () => {useModelStore.setState({ activeModel: 'llama3:8b' })useProviderStore.getState().setProviderConfig('ollama', { baseUrl: 'http://localhost:11500' })- await new Promise((r) => setTimeout(r, 0))+ await settleLazyImport()expect(useModelStore.getState().activeModel).toBe('llama3:8b')})@@ -82,3 +110,47 @@ describe('switching a backend off clears a pick it was serving', () => {expect(useModelStore.getState().activeModel).toBeNull()})})++describe('the reset buttons close the same invariant', () => {+ beforeEach(() => {+ useModelStore.setState({ activeModel: null, models: [] })+ useProviderStore.getState().resetProvidersToDefaults()+ })++ it('"Reset AI Backends" drops a pick whose slot it switches off', async () => {+ // The regular user path: Ollama enabled, an Ollama model picked, then+ // Settings → Reset AI Backends. DEFAULT_PROVIDERS has ollama enabled:false,+ // so the model is unservable from that click on — and nothing asked.+ useProviderStore.getState().setProviderConfig('ollama', { enabled: true })+ useModelStore.setState({ activeModel: 'llama3:8b' })++ useProviderStore.getState().resetProvidersToDefaults()+ await settleLazyImport()++ expect(useProviderStore.getState().providers.ollama.enabled).toBe(false)+ expect(useModelStore.getState().activeModel).toBeNull()+ })++ it('the reset leaves a pick on a slot it keeps switched on', async () => {+ // The built-in engine occupies the openai slot and the defaults have it+ // ON, so a pick it serves survives the reset. A guard that cleared the+ // pick on every reset would be its own bug.+ useModelStore.setState({ activeModel: 'openai::qwen3-8b' })++ useProviderStore.getState().resetProvidersToDefaults()+ await settleLazyImport()++ expect(useProviderStore.getState().providers.openai.enabled).toBe(true)+ expect(useModelStore.getState().activeModel).toBe('openai::qwen3-8b')+ })++ it('the single-slot reset drops a pick it switches off', async () => {+ useProviderStore.getState().setProviderConfig('anthropic', { enabled: true })+ useModelStore.setState({ activeModel: 'anthropic::claude-x' })++ useProviderStore.getState().resetProvider('anthropic')+ await settleLazyImport()++ expect(useModelStore.getState().activeModel).toBeNull()+ })+})diff --git a/src/stores/__tests__/modelStore-builtin-vram.test.ts b/src/stores/__tests__/modelStore-builtin-vram.test.tsindex 2d099b65..83fea55d 100644--- a/src/stores/__tests__/modelStore-builtin-vram.test.ts+++ b/src/stores/__tests__/modelStore-builtin-vram.test.ts@@ -4,9 +4,9 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'// away from a built-in model to any OTHER local backend must stop the sidecar,// or two models sit in VRAM at once. These tests lock that mutual-exclusion.-const backendCall = vi.fn(async () => ({}))-const unloadModel = vi.fn(async () => undefined)-const unloadLmStudioModel = vi.fn(async () => undefined)+const backendCall = vi.fn(async (..._args: unknown[]) => ({}))+const unloadModel = vi.fn(async (..._args: unknown[]) => undefined)+const unloadLmStudioModel = vi.fn(async (..._args: unknown[]) => undefined)vi.mock('../../api/backend', () => ({backendCall: (...a: unknown[]) => backendCall(...a),diff --git a/src/stores/modelStore.ts b/src/stores/modelStore.tsindex 19cb2223..c9333613 100644--- a/src/stores/modelStore.ts+++ b/src/stores/modelStore.ts@@ -9,27 +9,15 @@ import { isLmStudioProvider } from '../lib/hf-to-provider'import { isTauri, backendCall } from '../api/backend'import { useChatStore } from './chatStore'import { log } from '../lib/logger'--/**- * Which provider slot a model name routes to.- *- * LU prefixes every non-Ollama model with the id of the provider that serves- * it ("openai::qwen3-8b"); a bare name goes to Ollama. Pure, because the point- * of it is to be assertable without a store.- *- * `null` means "no slot in this build owns that name" — an unknown prefix is- * not silently treated as Ollama's, which is how a checkpoint name ends up- * being sent to a backend that has never heard of it.- */-export function providerIdForModel(name: string | null | undefined): ProviderId | null {- if (!name) return null- const sep = name.indexOf('::')- if (sep < 0) return 'ollama'- const prefix = name.slice(0, sep)- return PROVIDER_IDS.includes(prefix as ProviderId) ? (prefix as ProviderId) : null-}--const PROVIDER_IDS: readonly ProviderId[] = ['ollama', 'openai', 'anthropic', 'lu-cloud']+// Which provider slot a model name routes to. There is exactly one answer to+// that question in this app and it lives in api/providers/registry — the same+// function getProviderForModel uses to pick the client that actually sends the+// turn. A second implementation here disagreed with it on real names+// ('sdxl::x.safetensors' → null vs 'sdxl', 'a::b::c' → null vs 'ollama'), which+// is the worst possible place for two answers: the guard below would decline to+// clear a pick that the send path would then route to a dead backend.+import { getProviderIdFromModel } from '../api/providers'+import type { ProviderId } from '../api/providers/types'export interface PullState {progress: PullProgress@@ -290,7 +278,7 @@ export const useModelStore = create<ModelState>()(dropActiveModelIfServedBy: (providerId) => {const active = get().activeModel- if (!active || providerIdForModel(active) !== providerId) return+ if (!active || getProviderIdFromModel(active) !== providerId) returnlog.warn('[modelStore] the picked model\'s backend was switched off, clearing the pick', {model: active, provider: providerId,})diff --git a/src/stores/providerStore.ts b/src/stores/providerStore.tsindex b4b53d45..bd23331d 100644--- a/src/stores/providerStore.ts+++ b/src/stores/providerStore.ts@@ -101,6 +101,40 @@ const DEFAULT_PROVIDERS: Record<ProviderId, ProviderConfig> = {},}+/**+ * The model/provider invariant, asked on EVERY path that can switch a slot off.+ *+ * A slot going dark makes the picked model unservable, and nothing used to+ * notice: the pick is only re-validated against the next NON-EMPTY model list,+ * so until a refresh lands the composer offers a model whose backend is off and+ * every send fails with model-not-found.+ *+ * It hung off `setProviderConfig` alone, which is only the explicit toggle.+ * `resetProvidersToDefaults` ("Reset AI Backends", a button in Settings) writes+ * DEFAULT_PROVIDERS over the whole map — Ollama and Anthropic default to+ * `enabled: false` — so a user whose pick was an Ollama model reached exactly+ * the same broken state through a supported, one-click, non-exotic path.+ * `resetProvider` does the same for one slot.+ *+ * Imported lazily on purpose: modelStore reaches back here through+ * chatStore/remoteStore, and a static edge would close that circle at+ * module-init time.+ */+function dropPicksForDarkenedSlots(+ before: Partial<Record<ProviderId, ProviderConfig>>,+ after: Partial<Record<ProviderId, ProviderConfig>>,+): void {+ const darkened = (Object.keys(after) as ProviderId[]).filter(+ (id) => before[id]?.enabled === true && after[id]?.enabled === false,+ )+ if (darkened.length === 0) return+ void import('./modelStore')+ .then((m) => {+ for (const id of darkened) m.useModelStore.getState().dropActiveModelIfServedBy(id)+ })+ .catch(() => { /* best-effort: the next inventory refresh re-checks */ })+}+// ── Store Interface ────────────────────────────────────────────interface ProviderState {@@ -147,17 +181,7 @@ export const useProviderStore = create<ProviderState>()(},}))clearProviderCache() // invalidate cached clients- // A slot going dark makes the picked model unservable, and nothing used- // to notice: the pick is only re-validated against the next NON-EMPTY- // model list, so until a refresh lands the composer offers a model whose- // backend is off. Imported lazily on purpose — modelStore reaches back- // here through chatStore/remoteStore, and a static edge would close that- // circle at module-init time.- if (before?.enabled && get().providers[id]?.enabled === false) {- void import('./modelStore')- .then((m) => m.useModelStore.getState().dropActiveModelIfServedBy(id))- .catch(() => { /* best-effort: the next inventory refresh re-checks */ })- }+ dropPicksForDarkenedSlots({ [id]: before }, { [id]: get().providers[id] })// Every route that moves the shared local slot comes through here (Add// Provider, Enable on the standby card, Remove, Disable, onboarding), so// the memory question is asked here, once. R12/R13 measured the answer@@ -215,10 +239,13 @@ export const useProviderStore = create<ProviderState>()(void secretDelete(id).catch(() => { /* vault delete best-effort */ })}clearProviderCache()+ // A single-slot reset can switch that slot off too (ollama and+ // anthropic both default to enabled: false).+ dropPicksForDarkenedSlots({ [id]: before }, { [id]: get().providers[id] })},resetProvidersToDefaults: () => {- const before = get().providers.openai+ const before = get().providersset((state) => {const next = {} as Record<ProviderId, ProviderConfig>for (const id of Object.keys(DEFAULT_PROVIDERS) as ProviderId[]) {@@ -233,7 +260,10 @@ export const useProviderStore = create<ProviderState>()(clearProviderCache()// Reset hands the slot back to the app's own engine, which voids a// pending unload rather than causing one.- onLocalSlotChanged(before, get().providers.openai)+ onLocalSlotChanged(before.openai, get().providers.openai)+ // ...but it switches every OTHER slot the user had enabled back off,+ // and a pick served by one of them is unservable from this moment on.+ dropPicksForDarkenedSlots(before, get().providers)},hydrateProviderKeys: async () => {