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(AS-persistenz): "Turn fertig" heisst jetzt "Turn liegt im Store"
David4bb215907074
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex b9f5813c..50ac9056 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -18,7 +18,8 @@ import { requestGenerationCancel } from '../api/vram-handoff'import { resolveWorkspace } from '../api/agents/workspace-resolve'import { useAgentModeStore } from '../stores/agentModeStore'import { streamOllamaChatWithTools } from '../lib/ollama-stream-tools'-import { useChatStore, flushChatPersist } from '../stores/chatStore'+import { useChatStore } from '../stores/chatStore'+import { endTurnDurably } from '../stores/durability'import { useGenerationStore } from '../stores/generationStore'import { useModelStore } from '../stores/modelStore'import { useSettingsStore } from '../stores/settingsStore'@@ -2201,8 +2202,6 @@ export function useAgentChat() {}}} finally {- setIsAgentRunning(false)- useGenerationStore.getState().setGenerating(convId, false)useGenerationStore.getState().clearAborter(convId)runningRef.current = falseabortRef.current = null@@ -2217,11 +2216,18 @@ export function useAgentChat() {capturedArtifacts.map((a) => ({ id: uuid(), name: a.name, content: a.content, mime: a.mime })),)}- // The run is done, including the artifacts attached just above, so put it- // on disk now. Persistence is coalesced while the run streams (2.6.3 —- // see coalescedStorage); an agent turn is long and its blocks are big, so- // this is where the result becomes durable.- void flushChatPersist()+ // The run is done, including the artifacts attached just above, so it+ // goes on disk — and only THEN does the app report the run finished.+ // Persistence is coalesced while the run streams (2.6.3 — see+ // coalescedStorage); an agent turn is long and its blocks are big, so+ // this is where the result becomes durable. Same contract as Chat and+ // Code; stores/durability.ts carries the measurement, including why the+ // call stays in the statement the old `void flushChatPersist()` occupied+ // rather than moving to the bottom of the block.+ await endTurnDurably(() => {+ setIsAgentRunning(false)+ useGenerationStore.getState().setGenerating(convId, false)+ })// Drop the per-run workspace scope so standalone tool calls from// other tabs don't accidentally land in this chat's folder. Only when// this run still owns the shared mirror, so a Coding run that outlivesdiff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex 5bced345..298d1716 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -1,6 +1,7 @@import { useRef, useState, useCallback } from "react"import { v4 as uuid } from "uuid"-import { useChatStore, flushChatPersist } from "../stores/chatStore"+import { useChatStore } from "../stores/chatStore"+import { endTurnDurably } from "../stores/durability"import { useModelStore } from "../stores/modelStore"import { useSettingsStore } from "../stores/settingsStore"import { useRAGStore } from "../stores/ragStore"@@ -316,11 +317,16 @@ export function useChat() {await runGroupTurn(convId, model, models, abort)}} finally {- setIsGenerating(false)- useGenerationStore.getState().setGenerating(convId, false)useGenerationStore.getState().clearAborter(convId)abortRef.current = null- void flushChatPersist()+ // The round is over, so it goes on disk BEFORE the app says so. Same+ // contract as the single-model turn below and as the Agent and Coding+ // runs — see stores/durability.ts for the measurement that made the+ // order matter.+ await endTurnDurably(() => {+ setIsGenerating(false)+ useGenerationStore.getState().setGenerating(convId, false)+ })}}, [])@@ -980,18 +986,32 @@ export function useChat() {}}} finally {- setIsGenerating(false)- useGenerationStore.getState().setGenerating(convId, false)useGenerationStore.getState().clearAborter(convId)setIsLoadingModel(false)useModelStore.getState().setIsModelLoading(false)abortRef.current = null- // The turn is done, so put it on disk now. Persistence is coalesced while- // tokens stream (2.6.3 — see coalescedStorage), and an IndexedDB write- // cannot finish during unload, so THIS is the point that makes a finished- // answer durable, not the pagehide handler.- void flushChatPersist()+ // The turn is done, so it goes on disk — and only then does the app say+ // it is done. Persistence is coalesced while tokens stream (2.6.3 — see+ // coalescedStorage), and an IndexedDB write cannot finish during unload,+ // so THIS is the point that makes a finished answer durable, not the+ // pagehide handler. It used to fire the write and announce the turn+ // finished in the same breath, which under load meant announcing it+ // ~300 ms early; stores/durability.ts carries the measurement.+ //+ // Position matters as much as the await, and cost a regression to learn:+ // moving this call below the TTS and memory blocks pushed the START of+ // the write ~5 ms past the paint, and the reload race in+ // e2e/chat-streaming-persist.spec.ts went from never to 3 runs in 10.+ // The write begins in the same statement it always began in; the only+ // thing that changed is that the announcement now waits for it.+ //+ // The answer itself is already painted, so what waits here is the Stop+ // button turning back into Send, not the text.+ await endTurnDurably(() => {+ setIsGenerating(false)+ useGenerationStore.getState().setGenerating(convId, false)+ })// Auto-read the finished response when the user opted in (#77, ElBiggus).// Default OFF and additionally gated on ttsEnabled; getState() (not thediff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 2914895a..a1174625 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -4,6 +4,7 @@ import { useCodexStore } from '../stores/codexStore'import { useModelStore } from '../stores/modelStore'import { useSettingsStore } from '../stores/settingsStore'import { useChatStore, flushChatPersist } from '../stores/chatStore'+import { endTurnDurably } from '../stores/durability'import { getProviderForModel, getProviderIdFromModel } from '../api/providers'import { markToolsUnsupported } from '../api/tool-capability'import { toolRegistry } from '../api/mcp'@@ -2495,8 +2496,6 @@ export function useCodex() {})}- setIsRunning(false)- useGenerationStore.getState().setGenerating(convId, false)useGenerationStore.getState().clearAborter(convId)runningRef.current = falseabortRef.current = null@@ -2506,15 +2505,26 @@ export function useCodex() {endAgentRun(run)// The turn is done, including the hidden tool history inserted above, so- // put it on disk now. Persistence is coalesced while the run streams- // (2.6.3 — see coalescedStorage), and losing the tool chain would cost- // the next turn its context, not just the transcript.- void flushChatPersist()- // Same reasoning for the approval queue: what is still pending is work- // the user paid for and has not seen land yet. It has to be on disk- // before the app can be closed or updated (2026-08-11).- void flushStagedPersist()- codexStore.setThreadStatus(convId, 'idle')+ // it goes on disk BEFORE the app reports the run finished. Persistence is+ // coalesced while the run streams (2.6.3 — see coalescedStorage), and+ // losing the tool chain would cost the next turn its context, not just+ // the transcript.+ //+ // The staged-changes queue rides along for the same reason: what is still+ // pending there is work the user paid for and has not seen land yet, and+ // it has to be on disk before the app can be closed or updated+ // (2026-08-11). Both are awaited together, under one deadline —+ // stores/durability.ts has the measurement, including why this stays in+ // the statement the old `void flushChatPersist()` occupied instead of+ // moving to the bottom of the block.+ await endTurnDurably(+ () => {+ setIsRunning(false)+ useGenerationStore.getState().setGenerating(convId, false)+ codexStore.setThreadStatus(convId, 'idle')+ },+ [flushChatPersist, flushStagedPersist],+ )// The per-batch bump above only fires when a batch RETURNS. A user who// aborts mid-run (David 2026-07-31: files on disk, panel still showingdiff --git a/src/lib/coalescedStorage.ts b/src/lib/coalescedStorage.tsindex a4b3346f..7944d70f 100644--- a/src/lib/coalescedStorage.ts+++ b/src/lib/coalescedStorage.ts@@ -30,11 +30,28 @@* The flush is best effort on the way out, and cannot be anything else: an* IndexedDB write is asynchronous and the window does not wait for it during* unload. That is why `waitMs` is short and why the call site flushes when a- * turn ENDS rather than relying on the unload path — a finished answer is- * already on disk by the time anyone can close the app. Only a stream killed- * mid-sentence can lose its last `waitMs` of tokens, which the pre-existing- * per-set() write could lose too (it was equally asynchronous, just with a- * narrower window).+ * turn ENDS rather than relying on the unload path.+ *+ * What that flush is worth, precisely — the old wording here said a finished+ * answer is "already on disk by the time anyone can close the app", and that+ * was not measured. It is now (stores/durability.ts carries the numbers, taken+ * in a real Chromium against real IndexedDB):+ *+ * - `flush()` resolves when the put has LANDED, so awaiting it is a real+ * guarantee, and the three chat hooks now await it before they report a+ * turn finished. Once the app says the turn is over, the turn is readable+ * out of the store. On an idle Mac that costs under 2 ms; with the CPU+ * throttled 20x on a 6.5 MB profile it cost 323-545 ms, and that is the+ * Stop button waiting, not the text — the answer is painted long before.+ * - It is NOT true that the answer is on disk as soon as it is on screen.+ * The paint comes first and always will. A reload fired inside that window+ * still loses the tail of the turn: six of six throttled runs, and four+ * runs in twelve unthrottled on a busy machine — the same four in twelve+ * with and without the awaited turn end, because the write starts at the+ * same instant either way.+ * - A stream killed mid-sentence still loses its last `waitMs` of tokens,+ * which the pre-existing per-set() write could lose too (it was equally+ * asynchronous, just with a narrower window).*/import type { PersistStorage, StateStorage, StorageValue } from 'zustand/middleware'import { log } from './logger'diff --git a/src/stores/__tests__/a-turn-is-finished-when-it-is-stored.test.ts b/src/stores/__tests__/a-turn-is-finished-when-it-is-stored.test.tsnew file mode 100644index 00000000..37ff4b57--- /dev/null+++ b/src/stores/__tests__/a-turn-is-finished-when-it-is-stored.test.ts@@ -0,0 +1,235 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { readFileSync } from 'node:fs'++/**+ * A finished turn is readable out of the store by the time the app says the+ * turn is finished.+ *+ * ── What was wrong ─────────────────────────────────────────────────────────+ * Three hooks ended a turn by announcing it and THEN starting the write:+ *+ * setIsGenerating(false) // Stop turns back into Send+ * …+ * void flushChatPersist() // the write starts here+ *+ * Measured in a real Chromium against real IndexedDB (30 chats + 3 screenshots+ * = 6.48 MB persisted, CPU throttled 20x to stand in for a loaded machine), the+ * app reported the turn finished 323 ms, 327 ms and 522 ms before the turn+ * reached the store. A reload in that window came back without the answer in+ * six of six runs. Unthrottled on this Mac the same gap is 0.6-2 ms, which is+ * why it hid for so long.+ *+ * ── What this test pins ────────────────────────────────────────────────────+ * The CONSEQUENCE, not the shape: at the instant the completion signal is+ * published, the persisted blob already contains the finished turn. Written+ * that way on purpose — `await` on line N is a detail, "the record exists when+ * the app claims it exists" is the promise.+ *+ * ── What is real here and what is not ──────────────────────────────────────+ * Real: the actual `useChatStore`, the actual `coalescedJSONStorage` window,+ * the actual `flushChatPersist`, the actual `endTurnDurably`. Nothing about the+ * path under test is stubbed.+ *+ * Not real: IndexedDB itself. The vitest environment is `node`, which has no+ * `indexedDB` and no jsdom, and the repo carries no fake — so the backend below+ * stands in for it as an ASYNCHRONOUS key/value store with a settable write+ * delay, which is the property the bug depends on. The engine-level behaviour+ * of IndexedDB (transaction commit, durability across a reload) is verified in+ * a real browser instead; e2e/chat-streaming-persist.spec.ts is that test.+ */++const disk = new Map<string, string>()+let writeDelayMs = 0+let writeCalls = 0+/** Set to make the next writes hang forever — a database Chromium has given+ * up on, which is the case the deadline exists for. */+let wedged = false++vi.mock('../../lib/idbStorage', () => ({+ idbStorage: {+ getItem: () => null,+ setItem: async (k: string, v: string) => {+ writeCalls+++ if (wedged) return new Promise<void>(() => {})+ if (writeDelayMs) await new Promise((r) => setTimeout(r, writeDelayMs))+ disk.set(k, v)+ },+ removeItem: async (k: string) => { disk.delete(k) },+ },+}))++const KEY = 'chat-conversations'+const ANSWER = 'THE-FINISHED-ANSWER-THAT-MUST-SURVIVE'++function storedContains(needle: string): boolean {+ const raw = disk.get(KEY)+ return typeof raw === 'string' && raw.includes(needle)+}++describe('a turn is finished when it is stored', () => {+ beforeEach(() => {+ disk.clear()+ writeCalls = 0+ writeDelayMs = 0+ wedged = false+ })+ afterEach(() => { vi.useRealTimers() })++ it('the persisted record carries the answer at the moment the app reports the turn finished', async () => {+ // A write that takes real time, like an IndexedDB put of a real history.+ writeDelayMs = 40++ const { useChatStore } = await import('../chatStore')+ const { endTurnDurably } = await import('../durability')++ const convId = useChatStore.getState().createConversation('m', '')+ // Let the store settle so the assertion below is about THIS turn.+ await new Promise((r) => setTimeout(r, 400))+ disk.delete(KEY)++ useChatStore.getState().addMessage(convId, {+ id: 'a1', role: 'assistant', content: ANSWER, timestamp: 1,+ })+ // The coalescing window has not elapsed: nothing is on disk yet, which is+ // the whole reason the end of a turn has to do something about it.+ expect(storedContains(ANSWER)).toBe(false)++ let storedWhenAnnounced: boolean | null = null+ await endTurnDurably(() => {+ storedWhenAnnounced = storedContains(ANSWER)+ })++ expect(storedWhenAnnounced).toBe(true)+ })++ it('a turn that changes nothing still announces itself, and costs no extra write', async () => {+ const { useChatStore } = await import('../chatStore')+ const { endTurnDurably } = await import('../durability')++ useChatStore.getState().createConversation('m', '')+ await new Promise((r) => setTimeout(r, 400))+ const before = writeCalls++ let announced = false+ await endTurnDurably(() => { announced = true })++ expect(announced).toBe(true)+ expect(writeCalls).toBe(before)+ })++ it('a store that will never write does not pin the composer: the turn ends on the deadline', async () => {+ const { useChatStore } = await import('../chatStore')+ const { endTurnDurably, TURN_FLUSH_TIMEOUT_MS } = await import('../durability')++ const convId = useChatStore.getState().createConversation('m', '')+ await new Promise((r) => setTimeout(r, 400))++ wedged = true+ useChatStore.getState().addMessage(convId, {+ id: 'a2', role: 'assistant', content: 'never lands', timestamp: 2,+ })++ vi.useFakeTimers()+ let announced = false+ const done = endTurnDurably(() => { announced = true })+ await vi.advanceTimersByTimeAsync(TURN_FLUSH_TIMEOUT_MS - 1)+ expect(announced).toBe(false) // it really does wait for the write+ await vi.advanceTimersByTimeAsync(2)+ await expect(done).resolves.toBe('timeout')+ expect(announced).toBe(true)+ })++ it('a flush that rejects still ends the turn', async () => {+ const { endTurnDurably } = await import('../durability')+ let announced = false+ const verdict = await endTurnDurably(+ () => { announced = true },+ [() => Promise.reject(new Error('idb gone'))],+ )+ expect(announced).toBe(true)+ expect(verdict).toBe('flushed') // it settled — badly, but it settled+ })++ it('a flush that throws synchronously still ends the turn', async () => {+ const { endTurnDurably } = await import('../durability')+ let announced = false+ const verdict = await endTurnDurably(+ () => { announced = true },+ [() => { throw new Error('storage went away') }],+ )+ expect(announced).toBe(true)+ expect(verdict).toBe('timeout')+ })++ it('every flush in the list is awaited, not just the first', async () => {+ const { endTurnDurably } = await import('../durability')+ const landed: string[] = []+ const slow = (name: string, ms: number) => () =>+ new Promise<void>((r) => setTimeout(() => { landed.push(name); r() }, ms))++ let atAnnounce: string[] = []+ await endTurnDurably(+ () => { atAnnounce = [...landed] },+ [slow('chat', 10), slow('staged', 30)],+ )+ expect(atAnnounce.sort()).toEqual(['chat', 'staged'])+ })+})++/**+ * The pattern guard, and the reason it is here at all.+ *+ * The four `void flushChatPersist()` call sites were not one slip repeated: the+ * three hooks each grew their own copy of the same closing block, and they had+ * already drifted — useAgentChat attached the run's artifacts to the message+ * AFTER announcing the run finished, and useCodex flushed a second store the+ * other two do not have. Two paths that are supposed to do the same thing and+ * only one gets maintained is this project's recurring shape, so the guard is+ * against the divergence coming back, not against a particular line of code.+ *+ * This one IS a source-text check. There is no render harness in this repo+ * (vitest runs in `node`, there is no @testing-library), so a hook's finally+ * block cannot be executed from a test at all; the behaviour it enforces is+ * covered above on `endTurnDurably` itself and in the browser by+ * e2e/chat-streaming-persist.spec.ts.+ */+describe('all three chat hooks end a turn the same way', () => {+ const hooks = ['useChat', 'useCodex', 'useAgentChat'] as const++ /**+ * Source with comments removed. Load-bearing, and it cost a red run to+ * learn: the comments at these very call sites QUOTE the shape that is+ * forbidden ("the statement the old `void flushChatPersist()` occupied"),+ * so a check that reads the whole file finds the explanation instead of the+ * code. The same trap is documented in components/__tests__/+ * fokusring-und-press.test.ts, which strips comments for the same reason.+ */+ const strip = (s: string) => s.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '')++ for (const hook of hooks) {+ const code = strip(readFileSync(new URL(`../../hooks/${hook}.ts`, import.meta.url), 'utf8'))++ it(`${hook} routes its turn end through the shared contract`, () => {+ expect(code).toContain('endTurnDurably(')+ })++ it(`${hook} never fires the persist flush and walks away`, () => {+ expect(code).not.toMatch(/void\s+flushChatPersist\s*\(/)+ expect(code).not.toMatch(/void\s+flushStagedPersist\s*\(/)+ })++ it(`${hook} publishes "not generating any more" only from inside that contract`, () => {+ // Every `setGenerating(<something>, false)` in the hook has to sit in the+ // callback endTurnDurably runs after the write, never loose in a finally.+ const announcements = [...code.matchAll(/setGenerating\([^)]*,\s*false\s*\)/g)]+ expect(announcements.length).toBeGreaterThan(0)+ for (const m of announcements) {+ const before = code.slice(0, m.index)+ const lastContract = before.lastIndexOf('endTurnDurably(')+ expect(lastContract).toBeGreaterThan(-1)+ // …and nothing closed that callback in between.+ expect(before.slice(lastContract)).not.toContain('\n }\n')+ }+ })+ }+})diff --git a/src/stores/durability.ts b/src/stores/durability.tsnew file mode 100644index 00000000..c4ccd812--- /dev/null+++ b/src/stores/durability.ts@@ -0,0 +1,142 @@+/**+ * When a write counts as landed, and what "this turn is finished" is allowed+ * to mean.+ *+ * ── The finding (2026-09-01) ────────────────────────────────────────────────+ * Three hooks ended a turn with the same four lines and the same mistake:+ *+ * setIsGenerating(false) // the app says: done+ * useGenerationStore…setGenerating(id, false) // the app says: done+ * …+ * void flushChatPersist() // the write STARTS here+ *+ * The `void` is not the bug. Not blocking the render path is a legitimate+ * goal, and the answer is on screen long before any of this runs. The bug is+ * the ORDER: the app published "finished" while the write of that very turn+ * had not begun. Measured in a real Chromium against real IndexedDB, on the+ * profile coalescedStorage.ts itself describes (30 chats, 3 screenshots,+ * 6.48 MB persisted) with the CPU throttled 20x to stand in for a loaded+ * machine, the gap between the app reporting the turn finished and the turn+ * reaching the store was 323 ms, 327 ms and 522 ms across three runs. On an+ * idle Mac the same gap is under 2 ms — which is why this never showed up in+ * casual use and why the comment in coalescedStorage.ts got away with+ * promising that a finished answer is "already on disk".+ *+ * A reload inside that window loses the turn: six of six runs under the same+ * throttle came back from `page.reload()` with the user's line present and the+ * assistant's answer gone. Unthrottled but on a busy machine it is four runs+ * in twelve — the "one in three or four" the finding was reported as.+ *+ * ── What this module changes ────────────────────────────────────────────────+ * The turn's write goes FIRST and the announcement goes last. Nothing about+ * the render path changes: by the time a turn ends, the answer has already+ * been painted, so what waits here is the spinner, not the text. In exchange,+ * "the turn is finished" becomes a signal that can be trusted — by the user+ * closing the app, by an e2e spec, and by anything that reloads. Under the same+ * 20x throttle the gap changed sign: -225 ms, -318 ms, -256 ms, i.e. the store+ * holds the turn a quarter of a second BEFORE the app admits the turn is over.+ *+ * What this does NOT buy, stated plainly so nobody has to rediscover it: the+ * answer is on SCREEN before it is on disk, and it always will be. A reload+ * fired in the window between the paint and the completion signal still loses+ * the tail — four runs in twelve, measured identically with and without this+ * module, because the write starts at the same instant either way. The unload+ * path (pagehide/visibilitychange in chatStore) is best effort and cannot be+ * anything else: an IndexedDB write is asynchronous and the window does not+ * wait for it. The completion signal is the one moment the app is entitled to+ * claim durability, so that is the moment it claims it.+ *+ * ── One trap, paid for once ─────────────────────────────────────────────────+ * WHERE the call sites invoke this is load-bearing, not just THAT they await+ * it. `flushes.map(f => f())` runs synchronously, which is where the whole+ * serialise-and-put happens, so the call belongs at the earliest point where+ * the turn's writes are all in the store — the statement the old+ * `void flushChatPersist()` occupied. Moving it to the bottom of the hooks'+ * `finally` blocks (past the TTS and memory blocks) pushed the START of the+ * write about 5 ms past the paint and took the reload race from never to three+ * runs in ten. Awaiting late is free; starting late is not.+ */+import { log } from '../lib/logger'+import { flushChatPersist } from './chatStore'++/**+ * Resolve when `work` resolves, or after `ms`, whichever comes first, and+ * never reject. The caller wants to know it may proceed, not what happened.+ *+ * Exported for the test: a flush that never settles is not something a store+ * can be talked into from the outside.+ */+export function settledOrTimedOut(work: Promise<unknown>, ms: number): Promise<'settled' | 'timeout'> {+ return new Promise((resolve) => {+ const timer = setTimeout(() => resolve('timeout'), ms)+ work.then(+ () => { clearTimeout(timer); resolve('settled') },+ () => { clearTimeout(timer); resolve('settled') },+ )+ })+}++/**+ * How long a finished turn may wait for its own write before the app reports+ * it finished anyway.+ *+ * Same shape of reasoning as the update path's deadline, different number: an+ * update is a one-off the user has already agreed to and can afford ten+ * seconds, whereas this runs at the end of EVERY turn and the thing waiting on+ * it is the Stop button turning back into Send. Two seconds is far beyond a+ * healthy multi-megabyte write (the worst measured under a 20x CPU throttle+ * was 545 ms) and short enough that a wedged IndexedDB cannot pin the composer.+ */+export const TURN_FLUSH_TIMEOUT_MS = 2_000++/** A coalesced store's `flush()`, bound to its store. */+export type TurnFlush = () => Promise<void>++/**+ * End a turn: put what the turn produced on disk, THEN tell the app the turn+ * is over.+ *+ * `publishDone` is the announcement and nothing else — the `isGenerating` /+ * `isRunning` / thread-status writes that flip the composer back and stop the+ * typing dots. Everything the turn still has to WRITE (the assistant message,+ * the hidden tool history, attached artifacts, a plan awaiting approval) must+ * already be in the store before this is called, or it will not be in the+ * flush it is supposed to be in.+ *+ * `publishDone` runs exactly once, on every path, including a flush that+ * rejects and a flush that never settles. A store that cannot write is a+ * reason to log and carry on, never a reason to leave the user with a Stop+ * button that does nothing.+ *+ * Returns which of the two happened, so a caller can say so; the three hooks+ * currently ignore it and let the log carry it.+ */+export async function endTurnDurably(+ publishDone: () => void,+ flushes: readonly TurnFlush[] = [flushChatPersist],+ timeoutMs: number = TURN_FLUSH_TIMEOUT_MS,+): Promise<'flushed' | 'timeout'> {+ let verdict: 'flushed' | 'timeout' = 'flushed'+ try {+ // allSettled, not all: one store failing to write must not stop the app+ // from waiting for the others, and none of them may reject out of here.+ const outcome = await settledOrTimedOut(+ Promise.allSettled(flushes.map((flush) => flush())),+ timeoutMs,+ )+ if (outcome === 'timeout') {+ verdict = 'timeout'+ log.warn('[turn] the finished turn did not reach the store before the deadline — reporting it finished anyway', {+ timeoutMs,+ })+ }+ } catch (err) {+ // A flush that throws SYNCHRONOUSLY never became a promise, so allSettled+ // never saw it. Same answer: say so, then let the turn end.+ verdict = 'timeout'+ log.warn('[turn] a store flush threw on the way out of a finished turn', { err: String(err) })+ } finally {+ publishDone()+ }+ return verdict+}diff --git a/src/stores/updateStore.ts b/src/stores/updateStore.tsindex 1cf81749..33ce6998 100644--- a/src/stores/updateStore.ts+++ b/src/stores/updateStore.ts@@ -8,6 +8,7 @@ import { isTauri, backendCall, openExternal } from '../api/backend'import { stopBundledEngine, stopBundledEmbed } from '../api/engine'import { flushChatPersist } from './chatStore'import { flushStagedPersist } from './stagedChangesStore'+import { settledOrTimedOut } from './durability'// Static on purpose. The next thing that happens after this is called is an// installer overwriting the binary, which is the worst imaginable moment to be// fetching a chunk off disk for the first time.@@ -34,22 +35,12 @@ const UPDATE_SETTLE_MS = 250* not worth waiting for forever. */const UPDATE_FLUSH_TIMEOUT_MS = 10_000-/**- * Resolve when `work` resolves, or after `ms`, whichever comes first, and- * never reject. The caller wants to know it may proceed, not what happened.- *- * Exported for the test: a flush that never settles is not something a store- * can be talked into from the outside.- */-export function settledOrTimedOut(work: Promise<unknown>, ms: number): Promise<'settled' | 'timeout'> {- return new Promise((resolve) => {- const timer = setTimeout(() => resolve('timeout'), ms)- work.then(- () => { clearTimeout(timer); resolve('settled') },- () => { clearTimeout(timer); resolve('settled') },- )- })-}+// `settledOrTimedOut` used to be defined here. It moved to ./durability when+// the end of a chat turn needed the same deadline, because a second copy of+// "wait, but not forever" is exactly how two paths that should agree stop+// agreeing. Still re-exported under the old name: this is where its test and+// every existing reader look for it.+export { settledOrTimedOut } from './durability'// ── Types ─────────────────────────────────────────────────────