Skip to content

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.

fix(agent): a run LU Cloud cut for repeating, a /loop pass that hit a brake, and the credit limits with the guard off all stop (CA)

purple18227d2194cf
diff --git a/src/hooks/__tests__/the-15-11-agent-run-stops.test.ts b/src/hooks/__tests__/the-15-11-agent-run-stops.test.ts
new file mode 100644
index 00000000..3f9fa613
--- /dev/null
+++ b/src/hooks/__tests__/the-15-11-agent-run-stops.test.ts
@@ -0,0 +1,195 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * The case of 15.11.2026 (LU-Admin Wecker, web-1 metadata only, no chat
+ * content): a desktop agent on direct/deepseek-v4.1-flash ran 70 minutes,
+ * 535 requests, 524 of them ending in tool calls, 8 finished answers, about
+ * 125k input per request (peak 298k), ~729k credits. LU Cloud cut two steps
+ * for repeating (chat.loop_stopped), and the work went on after both.
+ *
+ * Driven through the real `useAgentChat().sendAgentMessage`, only the network
+ * replaced. Every call honestly differs (another page each time), so the
+ * near-copy detector has nothing to catch: what has to hold is the send cap,
+ * the cost brake, the server's loop stop and /loop.
+ *
+ * Run: npx vitest run src/hooks/__tests__/the-15-11-agent-run-stops.test.ts
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+
+vi.mock('../../api/cloud/supabase', () => ({ getAccessToken: async () => 'session-token-abc' }))
+vi.mock('../../api/rag', () => ({
+ retrieveContext: async () => ({ context: { chunks: [], query: '', documentIds: [] }, scoredChunks: [] }),
+ generateEmbeddings: async () => [[0.1, 0.2]],
+}))
+vi.mock('../../lib/ttsBridge', () => ({ autoSpeak: () => {} }))
+vi.mock('../../api/vram-handoff', () => ({ requestGenerationCancel: () => {} }))
+vi.mock('../useMemory', () => ({
+ useMemory: () => ({ extractAndSave: async () => {} }),
+ extractMemoriesFromPair: async () => {},
+}))
+
+/** A long page every time, different each time: ~40k characters. */
+const page = (url: string) => `${url}\n` + Array.from({ length: 500 }, (_, i) => `Line ${i} of ${url}: build log entry with a path and a number ${i * 7}.`).join('\n')
+
+vi.mock('../../api/backend', async () => {
+ const actual = await vi.importActual<typeof import('../../api/backend')>('../../api/backend')
+ return {
+ ...actual,
+ backendCall: vi.fn(async (cmd: string, args?: unknown) => {
+ if (cmd === 'web_fetch') {
+ const url = (args as { url: string }).url
+ return { url, status: 200, title: 'Log', text: page(url) }
+ }
+ return actual.backendCall(cmd as never, args as never)
+ }),
+ }
+})
+
+import { useAgentChat } from '../useAgentChat'
+import { useChatStore } from '../../stores/chatStore'
+import { useModelStore } from '../../stores/modelStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { useProviderStore } from '../../stores/providerStore'
+import { useAgentModeStore } from '../../stores/agentModeStore'
+import { useAgentTaskStore } from '../../stores/agentTaskStore'
+import { useAgentLoopStore } from '../../stores/agentLoopStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import { useTodoStore } from '../../stores/todoStore'
+import { useToolAuditStore } from '../../stores/toolAuditStore'
+import { DEFAULT_SETTINGS } from '../../lib/constants'
+import { DEFAULT_SEND_WINDOW_TOKENS } from '../../lib/send-window'
+import { __resetRunStopsForTests } from '../../lib/run-stop'
+import { _resetCreditLedger, hourCredits } from '../../lib/agent-core/credit-ledger'
+import { SERVER_LOOP_MESSAGE } from '../../lib/agent-core/server-loop-cut'
+import { toolRegistry, registerBuiltinTools } from '../../api/mcp'
+
+const MODEL = 'lu-cloud::direct/deepseek-v4.1-flash'
+const RATES = { inputPerMillion: 20_000, outputPerMillion: 60_000 }
+
+let requests = 0
+/** Characters of `messages` in each request the app sent. */
+let sentChars: number[] = []
+/** Requests LU Cloud cuts for repeating, by number. */
+let cutAt = new Set<number>()
+/** Input the server reports for request i: ~125k, once 298k. */
+const reported = (i: number) => (i === 6 ? 298_000 : 118_000 + ((i * 7919) % 14_000))
+let reportedSum = 0
+
+const sse = (chunks: unknown[]) =>
+ new Response(chunks.map((c) => `data: ${JSON.stringify(c)}\n\n`).join('') + 'data: [DONE]\n\n', {
+ status: 200, headers: { 'content-type': 'text/event-stream' },
+ })
+
+// Honest work: another place each time, and a line of its own about it.
+const HOSTS = ['ci.example.org', 'docs.example.net', 'status.example.com', 'git.example.io', 'artifacts.example.dev', 'wiki.example.org', 'tracker.example.net']
+const PATHS = ['nightly/build', 'release/notes', 'runners/macos', 'pipelines/lint', 'packages/core', 'issues/open', 'changelog', 'deps/lockfile', 'env/vars', 'tests/flaky', 'cache/keys']
+const STEPS = ['Reading the nightly log next.', 'Comparing with the release notes.', 'The runner image may be the cause.', 'Checking the lint stage.', 'Looking at the core package.', 'Open issues might mention it.', 'The changelog could explain the change.', 'Dependencies changed recently.', 'Maybe an environment variable.', 'Some tests are known to be flaky.', 'A stale cache key is possible.']
+const urlOf = (i: number) => `https://${HOSTS[i % HOSTS.length]}/${PATHS[(i * 3) % PATHS.length]}/${(i * 7919) % 100_000}`
+
+const toolCallSse = (i: number) => {
+ const call = { index: 0, id: `call_${i}`, type: 'function', function: { name: 'web_fetch', arguments: JSON.stringify({ url: urlOf(i) }) } }
+ reportedSum += reported(i)
+ return sse([
+ { choices: [{ delta: { role: 'assistant', content: `${STEPS[i % STEPS.length]} (${i})`, tool_calls: [call] } }] },
+ { choices: [{ delta: {}, finish_reason: 'tool_calls' }] },
+ { choices: [], usage: { prompt_tokens: reported(i), completion_tokens: 140, total_tokens: reported(i) + 140 } },
+ ])
+}
+
+// What the server sends when it cuts a step (server A41, lib/chat/loop-watch.ts).
+const loopCutSse = () => sse([{ error: { message: 'The model started repeating the same text.', type: 'stalled', code: 'stalled_loop' } }])
+
+beforeEach(() => {
+ requests = 0
+ sentChars = []
+ cutAt = new Set()
+ reportedSum = 0
+ _resetCreditLedger()
+ registerBuiltinTools(toolRegistry)
+ __resetRunStopsForTests()
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+ useAgentTaskStore.setState({ byConv: {} })
+ useAgentLoopStore.setState({ loops: {} })
+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
+ useAgentModeStore.setState({ agentModeActive: {}, workspaces: {}, workspaceSlugs: {} })
+ useTodoStore.setState({ byConversation: {}, updatedAt: {} })
+ useToolAuditStore.setState({ entries: {} })
+ useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, appMode: 'cloud', cavemanMode: 'off', webStrictUrls: false } })
+ useProviderStore.setState((s) => ({ providers: { ...s.providers, 'lu-cloud': { ...s.providers['lu-cloud'], enabled: true } } }))
+ useModelStore.setState({ models: [{ name: MODEL, creditRates: RATES } as never], activeModel: MODEL })
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input)
+ if (url.includes('/chat/completions')) {
+ requests++
+ if (requests > 80) throw new Error('the run did not stop')
+ const body = JSON.parse(String(init?.body ?? '{}')) as { messages?: unknown[] }
+ sentChars.push(JSON.stringify(body.messages ?? []).length)
+ return cutAt.has(requests) ? loopCutSse() : toolCallSse(requests)
+ }
+ return new Response('<html><body>log</body></html>', { status: 200, headers: { 'content-type': 'text/html' } })
+ })
+})
+afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+})
+
+async function run(loop?: { pass: number; intervalMs: number; task: string; startedAt: number }) {
+ const convId = useChatStore.getState().createConversation(MODEL, '')
+ useChatStore.getState().setActiveConversation(convId)
+ const { result } = renderHook(() => useAgentChat())
+ const task = 'Go through the build logs and find why the nightly build fails.'
+ await act(async () => {
+ await result.current.sendAgentMessage(task, undefined, { curatedTools: ['web_fetch'], chatToolsMode: true, ...(loop ? { loop } : {}) })
+ })
+ const conv = useChatStore.getState().conversations.find((c) => c.id === convId)!
+ const assistants = conv.messages.filter((m) => m.role === 'assistant')
+ const answer = assistants.at(-1)!
+ const runAnswer = assistants.find((m) => (m.agentBlocks ?? []).length > 0) ?? answer
+ const notes = (runAnswer.agentBlocks ?? []).filter((b) => b.phase === 'reflection').map((b) => b.content)
+ return { convId, answer, runAnswer, notes, assistants }
+}
+
+describe('15.11.2026: an agent run of that shape stops', () => {
+ it('every step stays within the send cap while the pages pile up, and the cost brake ends the run', { timeout: 120_000 }, async () => {
+ const { runAnswer, notes } = await run()
+ // The 70 minutes had 535 requests. Here the run ends at 2M input.
+ expect(requests).toBeLessThanOrEqual(17)
+ expect(notes.some((n) => /^⛔ Stopped to protect your credits/.test(n))).toBe(true)
+ expect(runAnswer.content).toMatch(/Stopped to protect your credits: this run has sent 2\.\dM tokens/)
+ // The pages add up to far more than the cap; what goes out does not.
+ expect(requests * 40_000).toBeGreaterThan(DEFAULT_SEND_WINDOW_TOKENS * 4 * 3)
+ const capChars = DEFAULT_SEND_WINDOW_TOKENS * 4 * 1.15
+ expect(Math.max(...sentChars)).toBeLessThan(capChars)
+ })
+
+ it('LU Cloud cuts a step for repeating: one more attempt, and the second cut ends the run with its sentence', { timeout: 60_000 }, async () => {
+ cutAt = new Set([3, 6])
+ const { runAnswer } = await run()
+ // 1, 2, cut 3, retry 4, 5, cut 6: and nothing after.
+ expect(requests).toBe(6)
+ expect(runAnswer.content).toContain(SERVER_LOOP_MESSAGE)
+ // The two cut steps were billed by the server without usage; the hour
+ // counts them at the step's estimate, on top of what the others reported.
+ const reportedCredits = (reportedSum * RATES.inputPerMillion + 4 * 140 * RATES.outputPerMillion) / 1_000_000
+ expect(hourCredits()).toBeGreaterThan(reportedCredits)
+ })
+
+ it('a /loop pass the cost brake ended does not start the next pass', { timeout: 120_000 }, async () => {
+ const { convId, assistants } = await run({ pass: 1, intervalMs: 1_000, task: 'check the build', startedAt: Date.now() })
+ const before = requests
+ expect(assistants.some((m) => m.content === 'The loop stopped because the run was paused to protect your credits. Start it again once that is sorted.')).toBe(true)
+ expect(useAgentLoopStore.getState().loops[convId]).toBeUndefined()
+ await new Promise((r) => setTimeout(r, 1_500))
+ expect(requests).toBe(before)
+ })
+
+ it('with the loop guard switched off, the credit limit still pauses the task', { timeout: 120_000 }, async () => {
+ useSettingsStore.setState((s) => ({ settings: { ...s.settings, agentLoopGuard: false } }))
+ const { runAnswer } = await run()
+ // ~125k at 20,000 credits per million: 100,000 credits after about 40 steps.
+ expect(requests).toBeLessThanOrEqual(45)
+ expect(runAnswer.content).toMatch(/Paused to protect your credits: this task has used up to/)
+ })
+})
diff --git a/src/hooks/__tests__/the-15-11-code-loop-stops.test.ts b/src/hooks/__tests__/the-15-11-code-loop-stops.test.ts
new file mode 100644
index 00000000..0187bbd7
--- /dev/null
+++ b/src/hooks/__tests__/the-15-11-code-loop-stops.test.ts
@@ -0,0 +1,112 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * The case of 15.11.2026 in the Code tab (see the-15-11-agent-run-stops.test.ts
+ * for the case itself): a `/loop` pass that ended on the cost brake or on
+ * LU Cloud's loop stop must not start the next pass, which would begin with a
+ * fresh brake and the same wall in front of it.
+ *
+ * Run: npx vitest run src/hooks/__tests__/the-15-11-code-loop-stops.test.ts
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+
+vi.mock('../../api/cloud/supabase', () => ({ getAccessToken: async () => 'session-token-abc' }))
+vi.mock('../../api/rag', () => ({
+ retrieveContext: async () => ({ context: { chunks: [], query: '', documentIds: [] }, scoredChunks: [] }),
+ generateEmbeddings: async () => [[0.1, 0.2]],
+}))
+vi.mock('../../lib/ttsBridge', () => ({ autoSpeak: () => {} }))
+vi.mock('../../api/vram-handoff', () => ({ requestGenerationCancel: () => {} }))
+vi.mock('../useMemory', () => ({
+ useMemory: () => ({ extractAndSave: async () => {} }),
+ extractMemoriesFromPair: async () => {},
+}))
+
+import { useCodex } from '../useCodex'
+import { useChatStore } from '../../stores/chatStore'
+import { useModelStore } from '../../stores/modelStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { useProviderStore } from '../../stores/providerStore'
+import { useAgentModeStore } from '../../stores/agentModeStore'
+import { useAgentTaskStore } from '../../stores/agentTaskStore'
+import { useAgentLoopStore } from '../../stores/agentLoopStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import { useTodoStore } from '../../stores/todoStore'
+import { useToolAuditStore } from '../../stores/toolAuditStore'
+import { DEFAULT_SETTINGS } from '../../lib/constants'
+import { __resetRunStopsForTests } from '../../lib/run-stop'
+import { _resetCreditLedger } from '../../lib/agent-core/credit-ledger'
+import { SERVER_LOOP_MESSAGE } from '../../lib/agent-core/server-loop-cut'
+import { toolRegistry, registerBuiltinTools } from '../../api/mcp'
+
+const MODEL = 'lu-cloud::direct/deepseek-v4.1-flash'
+let requests = 0
+let answerWith: (i: number) => Response
+
+const sse = (chunks: unknown[]) =>
+ new Response(chunks.map((c) => `data: ${JSON.stringify(c)}\n\n`).join('') + 'data: [DONE]\n\n', {
+ status: 200, headers: { 'content-type': 'text/event-stream' },
+ })
+
+beforeEach(() => {
+ requests = 0
+ _resetCreditLedger()
+ registerBuiltinTools(toolRegistry)
+ __resetRunStopsForTests()
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+ useAgentTaskStore.setState({ byConv: {} })
+ useAgentLoopStore.setState({ loops: {} })
+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
+ useAgentModeStore.setState({ agentModeActive: {} })
+ useTodoStore.setState({ byConversation: {}, updatedAt: {} })
+ useToolAuditStore.setState({ entries: {} })
+ useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, appMode: 'cloud', cavemanMode: 'off' } })
+ useProviderStore.setState((s) => ({ providers: { ...s.providers, 'lu-cloud': { ...s.providers['lu-cloud'], enabled: true } } }))
+ useModelStore.setState({ models: [], activeModel: MODEL })
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL) => {
+ if (!String(input).includes('/chat/completions')) return new Response('{}', { status: 200 })
+ requests++
+ if (requests > 20) throw new Error('the loop did not stop')
+ return answerWith(requests)
+ })
+})
+afterEach(() => vi.restoreAllMocks())
+
+async function loopPass() {
+ const { result } = renderHook(() => useCodex())
+ const convId = useChatStore.getState().createConversation(MODEL, '', 'codex')
+ useChatStore.getState().setActiveConversation(convId)
+ await act(async () => { await result.current.sendInstruction('/loop 1s go through the build logs and fix the nightly build') })
+ const assistants = useChatStore.getState().conversations.find((c) => c.id === convId)!.messages.filter((m) => m.role === 'assistant')
+ return { convId, assistants }
+}
+
+async function noFurtherPass(convId: string) {
+ const before = requests
+ expect(useAgentLoopStore.getState().loops[convId]).toBeUndefined()
+ await new Promise((r) => setTimeout(r, 1_500))
+ expect(requests).toBe(before)
+}
+
+describe('15.11.2026, Code tab: /loop ends where the pass hit a wall', () => {
+ it('LU Cloud cut the step for repeating: its sentence, and no next pass', { timeout: 30_000 }, async () => {
+ answerWith = () => sse([{ error: { message: 'The model started repeating the same text.', type: 'stalled', code: 'stalled_loop' } }])
+ const { convId, assistants } = await loopPass()
+ expect(assistants.some((m) => m.content.includes(SERVER_LOOP_MESSAGE))).toBe(true)
+ expect(assistants.some((m) => m.content === 'The loop stopped because the run was cut off by LU Cloud because the model kept repeating itself. Start it again once that is sorted.')).toBe(true)
+ await noFurtherPass(convId)
+ })
+
+ it('the cost brake ended the pass: no next pass with a fresh brake', { timeout: 30_000 }, async () => {
+ answerWith = (i) => sse([
+ { choices: [{ delta: { role: 'assistant', content: 'Listing the logs.', tool_calls: [{ index: 0, id: `c${i}`, type: 'function', function: { name: 'file_list', arguments: JSON.stringify({ path: `logs/${i}` }) } }] } }] },
+ { choices: [{ delta: {}, finish_reason: 'tool_calls' }] },
+ { choices: [], usage: { prompt_tokens: 2_100_000, completion_tokens: 50, total_tokens: 2_100_050 } },
+ ])
+ const { convId, assistants } = await loopPass()
+ expect(assistants.some((m) => /Stopped to protect your credits/.test(m.content))).toBe(true)
+ expect(assistants.some((m) => m.content === 'The loop stopped because the run was paused to protect your credits. Start it again once that is sorted.')).toBe(true)
+ await noFurtherPass(convId)
+ })
+})
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index e86bf489..75329366 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -1,5 +1,6 @@
import { stripSourcesMarker } from '../lib/web-evidence'
import { billingOf, creditRatesOf } from '../lib/agent-core/credit-rates'
+import { isServerLoopCut, LOOP_HALT_COST, LOOP_HALT_GUARD, LOOP_HALT_SERVER_LOOP, SERVER_LOOP_MESSAGE, SERVER_LOOP_RETRIES } from '../lib/agent-core/server-loop-cut'
import { canonicalArgs, repeatLabel, skippedRepeatsNote } from '../lib/agent-core/repeat-note'
import { replayableReasoning } from '../lib/agent-core/reasoning-replay'
import { useRef, useState, useCallback, useEffect } from 'react'
@@ -1726,6 +1727,8 @@ export function useAgentChat() {
runCreditLimit: useSettingsStore.getState().settings.agentRunCreditLimit,
hourCreditLimit: useSettingsStore.getState().settings.agentHourCreditLimit,
})
+ // Steps LU Cloud cut for repeating (lib/agent-core/server-loop-cut.ts).
+ let serverLoopCuts = 0
// The closing line a turn gets when the model itself said nothing usable.
// Read from the live counters at call time, so both the normal end of the
// run and the swallowed multimodal refusal below produce the same text.
@@ -2366,6 +2369,16 @@ export function useAgentChat() {
providerTurn = await streamProviderTurn(provider, modelToUse, sendMessages, { ...streamOpts, thinking: undefined as unknown as boolean }, onLiveContent, () => {}, onToolProgress)
break
}
+ // LU Cloud cut this step for repeating itself. The server billed
+ // its input and sent no usage, so it is counted here at the
+ // step's estimate; one more attempt per run, then the run ends.
+ if (isServerLoopCut(thinkErr)) {
+ costBrake.record(stepEstimate)
+ serverLoopCuts++
+ if (serverLoopCuts > SERVER_LOOP_RETRIES) throw thinkErr
+ log.warn('agent.server_loop_cut_retry', { provider: providerId, cuts: serverLoopCuts })
+ continue
+ }
const transient = asString(prop(thinkErr, 'name')) !== 'AbortError' && !isTerminalModelError(thinkErr) && !cutByModelSwitch(convId)
if (transient && connRetries < 2) {
connRetries++
@@ -3076,6 +3089,7 @@ export function useAgentChat() {
content: `⛔ Loop guard halted the run: ${batchVerdict.reason}.`,
timestamp: Date.now(),
})
+ loopHalt = LOOP_HALT_GUARD
break
}
// C83: the cost brake looks at what the backend reported, not at the
@@ -3088,6 +3102,7 @@ export function useAgentChat() {
id: uuid(), phase: 'reflection', content: `⛔ ${brake.message}`, timestamp: Date.now(),
})
log.warn('agent.cost_brake_halt', { provider: providerId, inputTokens: costBrake.inputTokens })
+ loopHalt = LOOP_HALT_COST
useChatNoticeStore.getState().show('cost-brake', brake.message, 'ruhig')
break
}
@@ -3589,6 +3604,7 @@ export function useAgentChat() {
const summary = (isLocalModelByName(activeModel) ? await finishWithoutTools({ provider, model: modelToUse, messages: agentMessages, signal: abort.signal }) : null)
if (summary) { runState.content += finishSection(summary); scheduleUIUpdate() }
}
+ loopHalt = LOOP_HALT_GUARD
break
}
@@ -3702,6 +3718,13 @@ export function useAgentChat() {
emptyAnswerExplanation({ finishReason: MODEL_SWITCH_FINISH, captured: false, keepThinking: false }),
)
}
+ } else if (isServerLoopCut(err)) {
+ // LU Cloud cut a step twice for repeating (lib/agent-core/server-loop-cut.ts).
+ loopHalt = LOOP_HALT_SERVER_LOOP
+ useChatStore.getState().updateMessageContent(
+ convId!, assistantMessage.id,
+ (runState.content ? runState.content + '\n\n' : '') + SERVER_LOOP_MESSAGE
+ )
} else if ((err as { code?: string })?.code === 'outage') {
// LU Cloud has an outage the server announced (lib/cloud-outage.ts).
// Its sentence instead of "Agent error: ...", and the loop stops:
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 2bc0b806..bde0dea6 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -1,5 +1,6 @@
import { stripSourcesMarker } from '../lib/web-evidence'
import { billingOf, creditRatesOf } from '../lib/agent-core/credit-rates'
+import { isServerLoopCut, LOOP_HALT_COST, LOOP_HALT_GUARD, LOOP_HALT_SERVER_LOOP, SERVER_LOOP_MESSAGE } from '../lib/agent-core/server-loop-cut'
import { replayableReasoning } from '../lib/agent-core/reasoning-replay'
import { NOT_IN_CODE_TAB } from '../lib/browser-tools'
import { useRef, useState, useCallback } from 'react'
@@ -1782,6 +1783,10 @@ export function useCodex() {
}
break
} catch (limitErr) {
+ // LU Cloud cut this step for repeating itself (lib/agent-core/
+ // server-loop-cut.ts): billed, no usage sent. Count it, then the
+ // run ends below with its own sentence.
+ if (isServerLoopCut(limitErr)) costBrake.record(stepPromptEstimate + stepToolsEstimate)
if (httpStatusOf(limitErr) !== 429 || isTerminalModelError(limitErr) || limitWaits >= 2 || abort.signal.aborted) throw limitErr
limitWaits++
const wait = retryDelayMs(limitErr, limitWaits)
@@ -2347,6 +2352,7 @@ export function useCodex() {
content: `⛔ Loop guard halted the run: ${batchVerdict.reason}.`,
timestamp: Date.now(),
})
+ loopHalt = LOOP_HALT_GUARD
break
}
// C83: the cost brake looks at what the backend reported, not at the
@@ -2357,6 +2363,7 @@ export function useCodex() {
useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent + `\n\n_(${brake.message})_`)
addBlock({ id: uuid(), phase: 'reflection', content: `⛔ ${brake.message}`, timestamp: Date.now() })
useChatNoticeStore.getState().show('cost-brake', brake.message, 'ruhig')
+ loopHalt = LOOP_HALT_COST
break
}
if (brake.action === 'warn') {
@@ -2814,6 +2821,7 @@ export function useCodex() {
content: `⛔ Loop guard halted the run: ${failVerdict.reason}.`,
timestamp: Date.now(),
})
+ loopHalt = LOOP_HALT_GUARD
break
}
@@ -2928,6 +2936,14 @@ export function useCodex() {
loopHalt = "too large for the model's context window"
hint = "\n\nHint: this step does not fit the model's context window, even with the history shortened. Give the model a larger context window (Settings, or where the server loads the model), or start a new chat for the next task."
}
+ // LU Cloud cut a step for repeating itself: its sentence, not a code.
+ if (isServerLoopCut(err)) {
+ loopHalt = LOOP_HALT_SERVER_LOOP
+ fullContent += `\n\n${SERVER_LOOP_MESSAGE}`
+ useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent)
+ codexStore.addEvent(convId, { id: uuid(), type: 'error', content: SERVER_LOOP_MESSAGE, timestamp: Date.now() })
+ return
+ }
// An empty wallet is not a crash and no retry fixes it. Replace the
// status-code line with the plain explanation the other surfaces use.
if (code === 'credits_exhausted') {
diff --git a/src/lib/__tests__/logic-notes.test.ts b/src/lib/__tests__/logic-notes.test.ts
index a0c0aead..4779af44 100644
--- a/src/lib/__tests__/logic-notes.test.ts
+++ b/src/lib/__tests__/logic-notes.test.ts
@@ -181,14 +181,15 @@ describe('guard: the hooks write the sentences this reader knows', () => {
expect(RATE_LIMIT_LITERAL.startsWith(RATE_LIMIT_HEAD)).toBe(true)
})
- it('the catch of a plain send has the seven branches read here, the catch of an agent run its twelve', () => {
+ it('the catch of a plain send has the seven branches read here, the catch of an agent run its thirteen', () => {
// A new branch writes a new sentence into the answer. It belongs into lib/logic-notes.ts and into the list above.
// The seventh and the twelfth (3.0.8, A28) are the LU Cloud outage: the server's sentence, so they write the field too.
// A22: the multimodal branch now asks why (api/image-part-heal); its sentences are read above.
+ // The thirteenth (15.11.2026): LU Cloud cut a step for repeating, SERVER_LOOP_MESSAGE.
const plain = catchOf(chatHook, 'await explainImageRefusal(activeModel)')
expect(plain.match(/updateMessageContent\(/g)).toHaveLength(7)
const agent = catchOf(agentHook, "'\\n\\nAgent error: ' + errorMsg")
- expect(agent.match(/updateMessageContent\(/g)).toHaveLength(12)
+ expect(agent.match(/updateMessageContent\(/g)).toHaveLength(13)
})
it('an empty turn is explained through one function, in both paths of the chat hook', () => {
@@ -198,6 +199,15 @@ describe('guard: the hooks write the sentences this reader knows', () => {
})
})
+describe('15.11.2026: the sentence of a step LU Cloud cut for repeating', () => {
+ it('is read as a note of the app, alone and after a partial answer', async () => {
+ const { SERVER_LOOP_MESSAGE } = await import('../agent-core/server-loop-cut')
+ const { splitLogicNote } = await import('../logic-notes')
+ expect(splitLogicNote(SERVER_LOOP_MESSAGE)?.kind).toBe('generic')
+ expect(splitLogicNote(`Checked the first two logs.\n\n${SERVER_LOOP_MESSAGE}`)?.body).toBe('Checked the first two logs.')
+ })
+})
+
describe('A22: the image part sentences are notes, not answers', () => {
it('each is read as a note of the app', async () => {
const { imagePartNotLoadedSentence, imagePartReloadedSentence, noImagePartSentence } = await import('../image-part-notes')
diff --git a/src/lib/agent-core/server-loop-cut.ts b/src/lib/agent-core/server-loop-cut.ts
new file mode 100644
index 00000000..7d41df50
--- /dev/null
+++ b/src/lib/agent-core/server-loop-cut.ts
@@ -0,0 +1,36 @@
+/**
+ * What an agent run does when it ends for a reason a next pass would hit again.
+ *
+ * LU Cloud ends a step in which the model repeats itself (server A41: SSE error
+ * code `stalled_loop`, logged as chat.loop_stopped). It bills the input of
+ * that step and the output before the repetition, and sends no usage, so the
+ * cost brake never saw that step. One more attempt can heal a one-off; a model
+ * that loops twice in one task is stuck on this context.
+ *
+ * Case 15.11.2026 (LU-Admin Wecker, metadata only): a desktop agent ran 70
+ * minutes on direct/deepseek-v4.1-flash, 535 requests, 524 of them tool
+ * calls, 8 finished answers, ~125k input per request, ~729k credits. The
+ * server cut two steps for repeating, and the work went on after both.
+ */
+
+export const SERVER_LOOP_CODE = 'stalled_loop'
+
+/** A step LU Cloud cut because the model repeated itself. */
+export function isServerLoopCut(err: unknown): boolean {
+ return !!err && typeof err === 'object' && (err as { code?: unknown }).code === SERVER_LOOP_CODE
+}
+
+/** Attempts a run may make after such a cut, over the whole run. */
+export const SERVER_LOOP_RETRIES = 1
+
+export const SERVER_LOOP_MESSAGE =
+ 'Stopped: the model got stuck repeating itself and LU Cloud cut it off. Send a message to go on, or try another model.'
+
+/**
+ * `/loop` reasons, read as "The loop stopped because the run was …". A pass
+ * that ended on one of these would start the next pass with a fresh brake and
+ * hit the same wall again, on the user's credits.
+ */
+export const LOOP_HALT_COST = 'paused to protect your credits'
+export const LOOP_HALT_GUARD = 'stuck repeating the same steps'
+export const LOOP_HALT_SERVER_LOOP = 'cut off by LU Cloud because the model kept repeating itself'
diff --git a/src/lib/agent-cost-brake.ts b/src/lib/agent-cost-brake.ts
index 85efe0be..aec5ef45 100644
--- a/src/lib/agent-cost-brake.ts
+++ b/src/lib/agent-cost-brake.ts
@@ -20,8 +20,11 @@ import { addHourCredits, creditFactor, hourPauseDue, markHourPause } from './age
*
* Only providers that bill (isPaidProvider) are braked; a model on this
* machine or in the LAN costs nothing per token. The loop guard switch (C44,
- * Settings → Agent Permissions) is respected: with the guard off, the brake
- * never ends a run, it only says once that the limit has been passed.
+ * Settings → Agent Permissions) is respected: with the guard off, the token
+ * limit never ends a run, it only says once that it has been passed. The two
+ * credit limits are not tied to that switch (CA, 15.11.2026): they have their
+ * own "No limit" in Settings → Agent, and a guard switched off against false
+ * loop stops must not also switch off the pause that protects the credits.
*/
// CA (14.11.2026): 400k and 3M let the incidents of that week through. The
@@ -130,7 +133,7 @@ export class AgentCostBrake {
// limit and not at half of it.
this.credits += step * creditFactor()
const hour = addHourCredits(step)
- if (this.mayHalt && this.runCreditLimit > 0 && this.credits >= this.runCreditLimit) {
+ if (this.runCreditLimit > 0 && this.credits >= this.runCreditLimit) {
this.pending = {
action: 'halt',
reason: `cost brake: this task used up to ${fmtCredits(this.credits)} credits in ${this.calls} steps (limit ${fmtCredits(this.runCreditLimit)})`,
@@ -140,7 +143,7 @@ export class AgentCostBrake {
}
return
}
- if (this.mayHalt && this.hourCreditLimit > 0 && hour >= this.hourCreditLimit && hourPauseDue()) {
+ if (this.hourCreditLimit > 0 && hour >= this.hourCreditLimit && hourPauseDue()) {
markHourPause()
this.pending = {
action: 'halt',
diff --git a/src/lib/logic-notes.ts b/src/lib/logic-notes.ts
index 5f78e7de..fd1a5f14 100644
--- a/src/lib/logic-notes.ts
+++ b/src/lib/logic-notes.ts
@@ -19,6 +19,7 @@
import type { MessageErrorKind } from '../types/chat'
import { DISCONNECT_WITHOUT_ANSWER } from './answer-notes'
import { CREDITS_EXHAUSTED_MESSAGE } from './credits-exhausted'
+import { SERVER_LOOP_MESSAGE } from './agent-core/server-loop-cut'
import { MULTIMODAL_UNSUPPORTED_MESSAGE } from './ollama-errors'
import { IMAGE_PART_NONE_HEAD, IMAGE_PART_NOT_LOADED_HEAD, IMAGE_PART_RELOADED_HEAD } from './image-part-notes'
import { PLATFORM_TEXTS } from './platform-text'
@@ -104,6 +105,8 @@ const TAIL_RULES: readonly TailRule[] = [
{ heads: [headOf(TEMPLATE_REFUSAL_SENTENCE), headOf(BAD_REQUEST_SENTENCE)], read: whole },
{ heads: [THINKING_UNSUPPORTED_HEAD], read: () => ({ kind: 'generic', detail: THINKING_UNSUPPORTED_DETAIL }) },
{ heads: [RATE_LIMIT_HEAD], read: whole },
+ // LU Cloud cut a step for repeating (agent-core/server-loop-cut.ts, 15.11.2026).
+ { heads: [headOf(SERVER_LOOP_MESSAGE)], read: whole },
{ heads: [REQUEST_LIMIT_FALLBACK_HEAD], read: (tail) => ({ kind: 'limit', detail: tail.trim() }) },
]