The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(agent): a failed Agent setup never locks the chat; a queued line is never lost; background wakes stop after three (CA)
purple11662cc48bc0
diff --git a/src/api/mcp/__tests__/mobile-tool-filter.test.ts b/src/api/mcp/__tests__/mobile-tool-filter.test.tsindex 8ed7dbd1..c1b18649 100644--- a/src/api/mcp/__tests__/mobile-tool-filter.test.ts+++ b/src/api/mcp/__tests__/mobile-tool-filter.test.ts@@ -208,10 +208,12 @@ describe('the prompt builders', () => {// P-L (3.1.0) changed the web line of the agent and the chat prompt on// purpose (web_research first); C59 changed the agent prompt on purpose// (A1: plain questions get a direct answer instead of "MUST use tools").- // The agent hash below is the one with both changes (integ/310).+ // The agent hash below is the one with both changes (integ/310), plus CA+ // (13.11.2026, cloud loops): one line that results stay above and a+ // shortened one is read in part.it('desktop: the three prompts are byte for byte the ones from before this change', () => {standOn('windows')- expect(sha(buildAgentSystemPrompt('BASE', roster))).toBe('9155fc04df15addacb1bd49778b7658fdf753b65d9570b9fe9468ea40a880a13')+ expect(sha(buildAgentSystemPrompt('BASE', roster))).toBe('9a1ede6fa93a8789ae2b3082c99560431e75d8253fded5679c8c1325da7c4698')expect(sha(buildAgentSystemPromptLean('BASE', 'file_read, file_write'))).toBe('28489a4807fe126dbef27f057b0414996a7618ca58d3c822cd51f7e6796184fd')expect(sha(buildChatToolsSystemPrompt('BASE'))).toBe('91e7f3ef8669ea15f7cca78a8789e842248ada2920505d4c23025d37ac416a0e')expect(buildAgentSystemPrompt('', roster)).toContain('with full access to this computer')diff --git a/src/components/chat/ChatNotices.tsx b/src/components/chat/ChatNotices.tsxindex 6bc9ca9f..2e810c79 100644--- a/src/components/chat/ChatNotices.tsx+++ b/src/components/chat/ChatNotices.tsx@@ -11,7 +11,7 @@* fuer Anmerkungen und Fehler vorschreibt: eine Zeile, kein Kasten, ruhiges* Grau oder Rot, und ein x, das sie wegnimmt.*/-import { AtSign, Binary, Bot, Download, FileText, FolderOpen, ImageOff, Images, Paperclip, RotateCcw, Scissors } from 'lucide-react'+import { AlertCircle, AtSign, Binary, Bot, Download, FileText, FolderOpen, ImageOff, Images, Paperclip, RotateCcw, Scissors } from 'lucide-react'import { Hinweis } from '../ui/Hinweis'import { useChatNoticeStore, CONVERSATION_BOUND, type ChatNoticeId } from '../../stores/chatNoticeStore'import { COMPOSER_MAX_W } from './composer-width'@@ -34,6 +34,7 @@ const ICON: Record<ChatNoticeId, typeof Paperclip> = {'create-save': Download,'file-mention': AtSign,rewind: RotateCcw,+ 'agent-start-failed': AlertCircle,}diff --git a/src/hooks/__tests__/a-queued-message-is-never-lost.test.tsx b/src/hooks/__tests__/a-queued-message-is-never-lost.test.tsxnew file mode 100644index 00000000..0d158d83--- /dev/null+++ b/src/hooks/__tests__/a-queued-message-is-never-lost.test.tsx@@ -0,0 +1,52 @@+/**+ * @vitest-environment jsdom+ *+ * CA (13.11.2026), support case "the app answers once, then never again": a+ * line queued while a run went was sent only if THIS view saw the run end.+ * Switch chats or tabs in between and it stayed in the queue for good.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { cleanup, renderHook } from '@testing-library/react'+import { useSteerQueue } from '../useSteerQueue'+import { useSteerStore } from '../../stores/steerStore'++beforeEach(() => useSteerStore.setState({ queue: {} } as never))+afterEach(() => cleanup())++describe('useSteerQueue', () => {+ it('holds the line while the run goes, sends it when it ends', () => {+ const send = vi.fn()+ const h = renderHook(({ running }) => useSteerQueue('c1', running, true, send), { initialProps: { running: true } })+ h.result.current.steer!('also add a test')+ h.rerender({ running: true })+ expect(send).not.toHaveBeenCalled()+ h.rerender({ running: false })+ expect(send).toHaveBeenCalledWith('also add a test')+ expect(useSteerStore.getState().queue.c1).toEqual([])+ })++ it('a view that mounts on an idle chat with a leftover line sends it', () => {+ useSteerStore.getState().add('c2', 'left behind while I was in another tab')+ const send = vi.fn()+ renderHook(() => useSteerQueue('c2', false, true, send))+ expect(send).toHaveBeenCalledWith('left behind while I was in another tab')+ })++ it('switching back to a chat whose run ended elsewhere sends its line', () => {+ useSteerStore.getState().add('c3', 'queued in c3')+ const send = vi.fn()+ const h = renderHook(({ conv }) => useSteerQueue(conv, false, true, send), { initialProps: { conv: 'other' } })+ expect(send).not.toHaveBeenCalled()+ h.rerender({ conv: 'c3' })+ expect(send).toHaveBeenCalledWith('queued in c3')+ })++ it('sends each line once', () => {+ useSteerStore.getState().add('c4', 'once')+ const send = vi.fn()+ const h = renderHook(() => useSteerQueue('c4', false, true, send))+ h.rerender()+ h.rerender()+ expect(send).toHaveBeenCalledTimes(1)+ })+})diff --git a/src/hooks/__tests__/agent-setup-never-locks-the-chat.test.ts b/src/hooks/__tests__/agent-setup-never-locks-the-chat.test.tsnew file mode 100644index 00000000..55228353--- /dev/null+++ b/src/hooks/__tests__/agent-setup-never-locks-the-chat.test.ts@@ -0,0 +1,31 @@+/**+ * CA (13.11.2026), support case "the app answers once, then never again":+ * about 800 lines of Agent setup ran before the loop's own try/finally. A+ * throw there left the conversation claimed and isAgentRunning true, and+ * every later send was refused without a word. The run in the lane is now+ * wrapped, and a claim still held by this run afterwards is freed.+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'++const src = readFileSync(new URL('../useAgentChat.ts', import.meta.url), 'utf8')++describe('the Agent run setup cannot lock a chat', () => {+ it('the lane body sits inside a try with a catch that tells the user', () => {+ const tryAt = src.indexOf(' try {\n laneOutcome = await runInLane(')+ expect(tryAt).toBeGreaterThan(0)+ const catchAt = src.indexOf("log.warn('agent.setup_threw'", tryAt)+ expect(catchAt).toBeGreaterThan(tryAt)+ expect(src.slice(catchAt, catchAt + 600)).toMatch(/'agent-start-failed'/)+ })++ it('afterwards a claim still held by this run is freed, identity checked', () => {+ const after = src.slice(src.indexOf("log.warn('agent.setup_threw'"))+ const release = after.indexOf('if (activeAgentRuns.get(convId) === runState) {')+ expect(release).toBeGreaterThan(0)+ const body = after.slice(release, release + 1200)+ expect(body).toMatch(/activeAgentRuns\.delete\(convId\)/)+ expect(body).toMatch(/setIsAgentRunning\(activeAgentRuns\.size > 0\)/)+ expect(body).toMatch(/await endTurnDurably\(\(\) => \{ useGenerationStore\.getState\(\)\.setGenerating\(convId, false\) \}\)/)+ })+})diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 98dcfe96..01bfd99c 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -904,7 +904,15 @@ export function useAgentChat() {// still in the waiting room: the body (and its own finally below) never// ran, so the guard this call claimed above has to be freed here instead.const lane = laneOf(activeModel, currentLaneFacts())- const laneOutcome = await runInLane(+ // Safety net (CA, 13.11.2026, support case "the app answers once, then+ // never again"): about 800 lines of setup run before the loop's own+ // try/finally, and a throw there left this conversation claimed and+ // `isAgentRunning` true for good. Every later Enter was then refused+ // without a word or parked in a steer queue no run would ever read, and+ // Stop showed in every chat. The Code tab has had this net for a while.+ let laneOutcome: Awaited<ReturnType<typeof runInLane>> | undefined+ try {+ laneOutcome = await runInLane({ conversationId: convId, lane, abort: () => abort.abort() },async (heldLocalLane) => {@@ -4019,15 +4027,33 @@ export function useAgentChat() {}},)- if (laneOutcome === 'cancelled-while-queued' && activeAgentRuns.get(convId) === runState) {+ } catch (err) {+ log.warn('agent.setup_threw', { convId, message: err instanceof Error ? err.message.slice(0, 300) : String(err).slice(0, 300) })+ // Say it where the user is looking, once, in their words.+ useChatNoticeStore.getState().show(+ 'agent-start-failed',+ 'The agent could not start this time. Send your message again; if it keeps happening, start a new chat.',+ 'fehler',+ CHAT_NOTICE_MS,+ )+ } finally {+ // Whatever way the body ended, a claim still held by THIS run is a leak:+ // the loop's own finally deletes it on every path it reaches. Identity+ // checked, so a newer run on the same conversation is never touched.+ if (activeAgentRuns.get(convId) === runState) {// Stop pulled this run out of the local lane's waiting room before its- // own finally ever ran (that finally lives inside the body above), so- // the guard this call claimed synchronously at the top has to be freed- // here instead. Nothing else needs undoing: the body never started, so- // it never added a message, registered its own aborter, or booked a- // loop timer.+ // own finally ever ran ('cancelled-while-queued'), or the setup threw+ // before reaching it: the guard claimed synchronously at the top has to+ // be freed here instead.activeAgentRuns.delete(convId)setIsAgentRunning(activeAgentRuns.size > 0)+ if (laneOutcome !== 'cancelled-while-queued') {+ abort.abort()+ // Through the same contract as every other end of a turn: whatever+ // the setup stored is on disk before the chat says it is done.+ await endTurnDurably(() => { useGenerationStore.getState().setGenerating(convId, false) })+ }+ }}}, [])diff --git a/src/hooks/useBackgroundAgentWake.ts b/src/hooks/useBackgroundAgentWake.tsindex e35b5afc..4c9ffa23 100644--- a/src/hooks/useBackgroundAgentWake.ts+++ b/src/hooks/useBackgroundAgentWake.ts@@ -2,6 +2,7 @@ import { useEffect, useRef } from 'react'import { useAgentTaskStore } from '../stores/agentTaskStore'import { useGenerationStore } from '../stores/generationStore'import { useModelStore } from '../stores/modelStore'+import { useChatStore } from '../stores/chatStore'import { createWakeWatcher } from '../lib/agent-wake'import { isRunStopped } from '../lib/run-stop'@@ -65,6 +66,14 @@ export function useBackgroundAgentWake(// geschrieben hat. Was er sieht, ist die Notiz des fertigen Agenten und// danach die Antwort darauf.send: (text) => sendenRef.current(text, undefined, { hiddenUser: true }),+ lastUserTurn: (id) => {+ const msgs = useChatStore.getState().conversations.find((c) => c.id === id)?.messages ?? []+ for (let i = msgs.length - 1; i >= 0; i--) {+ const m = msgs[i]+ if (m.role === 'user' && !m.hidden) return m.id+ }+ return null+ },})// ZWEI Quellen, und die zweite ist die, an der die erste Fassung scheiterte.diff --git a/src/hooks/useSteerQueue.ts b/src/hooks/useSteerQueue.tsindex e804c64d..76827b09 100644--- a/src/hooks/useSteerQueue.ts+++ b/src/hooks/useSteerQueue.ts@@ -18,17 +18,21 @@ export function useSteerQueue(sendNext: (text: string) => void,): { queue: QueuedSteer[]; steer?: (text: string) => void; unsteer: (id: string) => void } {const queue = useSteerStore((s) => (convId ? s.queue[convId] ?? EMPTY : EMPTY))- const wasRunning = useRef(running)const send = useRef(sendNext)useEffect(() => { send.current = sendNext })+ // Whatever is left in this chat's queue while nothing runs here goes out as+ // the next message. Not only at the moment a run ends while this view+ // watches it: a user who queued a line, switched chats or tabs and came back+ // found it gone for good, because the old rule fired on the running-to-idle+ // edge alone, and that edge happened while another view was mounted (CA,+ // support case "answers once, then never again"). Now any idle moment with a+ // non-empty queue sends it, on mount and on a chat switch back too.useEffect(() => {- const ended = wasRunning.current && !running- wasRunning.current = running- if (!ended || !convId) return+ if (running || !convId || queue.length === 0) returnconst left = useSteerStore.getState().take(convId)if (left.length) send.current(left.map((m) => m.text).join('\n\n'))- }, [running, convId])+ }, [running, convId, queue.length])return {queue,diff --git a/src/lib/__tests__/wakes-stop-after-three.test.ts b/src/lib/__tests__/wakes-stop-after-three.test.tsnew file mode 100644index 00000000..6187624e--- /dev/null+++ b/src/lib/__tests__/wakes-stop-after-three.test.ts@@ -0,0 +1,51 @@+/**+ * CA (13.11.2026): every wake is a full paid agent run nobody typed, and it may+ * order new background agents whose end wakes again. At most three in a row,+ * then the watcher waits for the user's next own message.+ */+import { describe, it, expect } from 'vitest'+import { createWakeWatcher, MAX_WAKES_IN_A_ROW } from '../agent-wake'+import type { AgentTask } from '../agent-tasks'++function rig() {+ const st = { userTurn: 'u1' as string | null, tasks: [] as AgentTask[] }+ const sent: string[] = []+ const timers: Array<() => void> = []+ const w = createWakeWatcher({+ conversationId: () => 'c',+ tasks: () => st.tasks,+ isRunning: () => false,+ isStopped: () => false,+ activeModel: () => 'lu-cloud::x',+ send: async (t) => { sent.push(t); st.tasks = st.tasks.map((x) => ({ ...x, reported: true })) },+ lastUserTurn: () => st.userTurn,+ setTimer: (fn) => { timers.push(fn); return timers.length },+ clearTimer: () => {},+ bundleMs: 1,+ })+ const finishOne = async (n: number) => {+ st.tasks = [...st.tasks, { id: `t${n}`, status: 'done', reported: false } as unknown as AgentTask]+ w.check()+ while (timers.length) timers.shift()!()+ await Promise.resolve(); await Promise.resolve()+ }+ return { st, sent, finishOne }+}++describe('background wakes in a row', () => {+ it('stop after three, without the user in between', async () => {+ const r = rig()+ for (let i = 0; i < 6; i++) await r.finishOne(i)+ expect(MAX_WAKES_IN_A_ROW).toBe(3)+ expect(r.sent).toHaveLength(3)+ })++ it('a new message from the user starts the count again', async () => {+ const r = rig()+ for (let i = 0; i < 4; i++) await r.finishOne(i)+ expect(r.sent).toHaveLength(3)+ r.st.userTurn = 'u2'+ await r.finishOne(9)+ expect(r.sent).toHaveLength(4)+ })+})diff --git a/src/lib/agent-wake.ts b/src/lib/agent-wake.tsindex 81770075..56d27465 100644--- a/src/lib/agent-wake.ts+++ b/src/lib/agent-wake.ts@@ -139,6 +139,14 @@ export interface WakeWatcherPorts {activeModel: () => string | null | undefined/** Der Weckzug. Fehler daraus dürfen den Wächter nicht umbringen. */send: (text: string) => Promise<unknown>+ /**+ * Kennung der letzten Nachricht, die der Mensch selbst geschickt hat (keine+ * versteckte Weck-Nachricht). Aendert sie sich, zaehlt die Weckreihe neu.+ * Ohne diesen Anschluss gilt die Grenze pro Waechter-Leben.+ */+ lastUserTurn?: (convId: string) => string | null+ /** Hoechstens so viele Weckzuege hintereinander ohne Menschen dazwischen. */+ maxWakesInARow?: number/** Nur für Tests austauschbar; sonst die echten Zeitgeber. */setTimer?: (fn: () => void, ms: number) => unknownclearTimer?: (h: unknown) => void@@ -168,6 +176,9 @@ export interface WakeWatcher {** Der Hook drumherum reicht nur noch Stores und einen Sendeweg herein.*/+/** Weckzuege hintereinander, ohne dass der Mensch dazwischen etwas schickt. */+export const MAX_WAKES_IN_A_ROW = 3+export function createWakeWatcher(ports: WakeWatcherPorts): WakeWatcher {const setTimer = ports.setTimer ?? ((fn, ms) => setTimeout(fn, ms))const clearTimer = ports.clearTimer ?? ((h) => clearTimeout(h as ReturnType<typeof setTimeout>))@@ -175,6 +186,24 @@ export function createWakeWatcher(ports: WakeWatcherPorts): WakeWatcher {let timer: unknown = nulllet busy = false+ // CA (13.11.2026): jeder Weckzug ist ein voller, bezahlter Agentenlauf, den+ // niemand getippt hat, und er darf neue Hintergrundagenten bestellen, deren+ // Abschluss wieder weckt. Ohne Obergrenze lief eine Kette aus Bestellen,+ // Wecken, Bestellen so lange, bis das Modell von selbst aufhoerte. Jetzt:+ // hoechstens drei in Folge, dann wartet der Waechter auf den Menschen.+ const maxRow = ports.maxWakesInARow ?? MAX_WAKES_IN_A_ROW+ const reihe = new Map<string, { turn: string | null; n: number }>()+ const reiheVoll = (convId: string) => {+ const turn = ports.lastUserTurn?.(convId) ?? null+ const r = reihe.get(convId)+ if (!r || r.turn !== turn) return false+ return r.n >= maxRow+ }+ const zaehlen = (convId: string) => {+ const turn = ports.lastUserTurn?.(convId) ?? null+ const r = reihe.get(convId)+ reihe.set(convId, r && r.turn === turn ? { turn, n: r.n + 1 } : { turn, n: 1 })+ }const urteilen = (convId: string) => shouldWakeParent({conversationId: convId,@@ -188,6 +217,7 @@ export function createWakeWatcher(ports: WakeWatcherPorts): WakeWatcher {const convId = ports.conversationId()if (!convId) returnif (!urteilen(convId).wake) return+ if (reiheVoll(convId)) return// Sammelfrist, bei jedem weiteren Abschluss neu gesetzt: es weckt erst,// wenn eine Weile lang keiner mehr fertig geworden ist.@@ -203,6 +233,8 @@ export function createWakeWatcher(ports: WakeWatcherPorts): WakeWatcher {// beschlossen, aber noch nicht abgeschickt ist, und ein Zug, der eine// Sekunde NACH Stop losgeht, ist genau der, den niemand bestellt hat.if (!urteilen(jetzt).wake) return+ if (reiheVoll(jetzt)) return+ zaehlen(jetzt)// `busy` deckt die Luecke zwischen "wir schicken los" und "der// Generierungs-Schalter steht auf an". Genau darin saehe ein zweiterdiff --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.tsindex 55242be1..73897a69 100644--- 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.ts@@ -349,7 +349,7 @@ describe('the turn end starts the write before it starts anything else', () => {// and useAgentChat after it, and neither costs the write anything — pinning// that difference would be pinning noise.- it('all five turn ends were found and parsed', () => {+ it('all six turn ends were found and parsed', () => {// `useCodex/runInstruction` und nicht mehr `sendInstruction`: 2.6.8 hat den// grossen useCallback in `runInstruction` umbenannt und `sendInstruction`// zur duennen Huelle mit beginSend/endSend gemacht. Das Rundenende sitzt@@ -369,6 +369,9 @@ describe('the turn end starts the write before it starts anything else', () => {'useChat/sendMessage','useCodex/runInstruction','useAgentChat/sendAgentMessage',+ // CA (13.11.2026): the safety net around the Agent run setup. A setup+ // that threw ends its turn here, through the same contract.+ 'useAgentChat/sendAgentMessage',])})diff --git a/src/stores/chatNoticeStore.ts b/src/stores/chatNoticeStore.tsindex 8b486349..e2f0d871 100644--- a/src/stores/chatNoticeStore.ts+++ b/src/stores/chatNoticeStore.ts@@ -34,7 +34,7 @@ import { useChatStore } from './chatStore'/** Die Zeilen, die es gibt. Kein freier Schluessel: eine Aufzaehlung laesst* sich nachzaehlen, ein String-Schluessel waechst unbemerkt. */-export type ChatNoticeId = 'document-belongs-in-docs' | 'model-cannot-see-images' | 'image-attach' | 'file-attach' | 'binary-summary-only' | 'file-cut' | 'agent-outside-workspace' | 'agent-for-local-files' | 'create-save' | 'file-mention' | 'rewind'+export type ChatNoticeId = 'document-belongs-in-docs' | 'model-cannot-see-images' | 'image-attach' | 'file-attach' | 'binary-summary-only' | 'file-cut' | 'agent-outside-workspace' | 'agent-for-local-files' | 'create-save' | 'file-mention' | 'rewind' | 'agent-start-failed'export interface ChatNotice {id: ChatNoticeId