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 tool call cut off by the token limit does not run
purple41502046fcfa
diff --git a/src/hooks/__tests__/a-cut-off-call-does-not-run.test.ts b/src/hooks/__tests__/a-cut-off-call-does-not-run.test.tsnew file mode 100644index 00000000..9db0bb27--- /dev/null+++ b/src/hooks/__tests__/a-cut-off-call-does-not-run.test.ts@@ -0,0 +1,103 @@+/**+ * Bug hunt 01.10.2026 (A2). A step that runs into the token limit while it is+ * writing a tool call ends with finish_reason 'length' and a call whose+ * arguments stop halfway. The provider repairs what it gets, so the cut call+ * came out as a call with arguments the model never wrote, and the agent ran+ * it. Cut right after one element of a list, the same repair hands on a valid+ * call with the rest of the list missing: a file_edit that applies its first+ * edit and never the one after it.+ */+import { describe, it, expect, vi } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import type { ProviderConfig } from '../../api/providers/types'+import { dropCutOffCall } from '../codex/turn-cutoff'++const backendMock = (respond: () => Response) => ({+ isTauri: () => false,+ localFetch: vi.fn(async () => respond()),+ localFetchStream: vi.fn(async () => respond()),+ ollamaUrl: (path: string) => `http://localhost:11434/api${path}`,+ backendCall: vi.fn(),+ isPrivateOrLanHost: () => false,+ isDirectFetchAllowed: () => false,+ hostnameOf: (url: string) => new URL(url).hostname,+ ensureProxyAllowsHost: vi.fn(),+})++const sse = (o: unknown) => `data: ${JSON.stringify(o)}\n\n`++/** A native stream: one finished read, then an edit of two steps that the+ * limit cut right after the first. */+const MIDWAY = '{"path":"auth.ts","edits":[{"old_string":"checkToken(req)","new_string":"checkToken(req, { strict: false })"},{"old_string":"strict: false","new_str'+const AFTER_FIRST = '{"path":"auth.ts","edits":[{"old_string":"checkToken(req)","new_string":"checkToken(req, { strict: false })"}'++async function cutTurn(editArgs = MIDWAY) {+ vi.resetModules()+ const body =+ sse({ choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: 'c0', function: { name: 'file_read', arguments: '{"path":"a.ts"}' } }] } }] }) ++ sse({ choices: [{ index: 0, delta: { tool_calls: [{ index: 1, id: 'c1', function: { name: 'file_edit', arguments: editArgs } }] } }] }) ++ sse({ choices: [{ index: 0, delta: {}, finish_reason: 'length' }] }) ++ 'data: [DONE]\n\n'+ vi.doMock('../../api/backend', () => backendMock(() => new Response(body, { headers: { 'Content-Type': 'text/event-stream' } })))+ const { OpenAIProvider } = await import('../../api/providers/openai-provider')+ const config: ProviderConfig = { id: 'openai', name: 'LU Cloud', enabled: true, apiKey: 'x', baseUrl: 'https://lu-labs.test/api/inference/v1', isLocal: false }+ let last: { toolCalls?: { function: { name: string; arguments: Record<string, unknown> } }[]; finishReason?: string } = {}+ for await (const chunk of new OpenAIProvider(config).chatStream('m', [{ role: 'user', content: 'go' }])) {+ if (chunk.done) last = chunk+ }+ return last+}++describe('a turn cut off by the token limit', () => {+ it('reaches the agent as a call with arguments the model never wrote', async () => {+ const turn = await cutTurn()+ expect(turn.finishReason).toBe('length')+ const edit = turn.toolCalls!.find((c) => c.function.name === 'file_edit')!+ // The repair closed the brackets around the first edit and handed THAT on+ // as the whole argument object: no path, one edit of two. It ran, failed+ // or half applied, and the model sent the same long call into the same+ // limit again.+ expect(edit.function.arguments).toEqual({ old_string: 'checkToken(req)', new_string: 'checkToken(req, { strict: false })' })+ })++ it('or as a valid call with the rest of its list missing', async () => {+ const turn = await cutTurn(AFTER_FIRST)+ const edit = turn.toolCalls!.find((c) => c.function.name === 'file_edit')!+ // A valid edit that loosens the check, without the second edit that was+ // going to tighten it again.+ expect(edit.function.arguments).toEqual({+ path: 'auth.ts',+ edits: [{ old_string: 'checkToken(req)', new_string: 'checkToken(req, { strict: false })' }],+ })+ expect(dropCutOffCall(turn.toolCalls!, turn.finishReason).dropped).toBe(edit)+ })++ it('runs the finished calls and drops the one that was cut', async () => {+ const turn = await cutTurn()+ const { calls, dropped } = dropCutOffCall(turn.toolCalls!, turn.finishReason)+ expect(calls.map((c) => c.function.name)).toEqual(['file_read'])+ expect(dropped!.function.name).toBe('file_edit')+ })++ it('leaves a turn that ended on its own alone', () => {+ const calls = [{ id: 'a' }, { id: 'b' }]+ expect(dropCutOffCall(calls, 'tool_calls')).toEqual({ calls, dropped: null })+ expect(dropCutOffCall(calls, 'stop')).toEqual({ calls, dropped: null })+ expect(dropCutOffCall(calls, undefined)).toEqual({ calls, dropped: null })+ expect(dropCutOffCall([], 'length')).toEqual({ calls: [], dropped: null })+ })++ it('both loops drop it before anything runs, the Agent loop after its loose fallback', () => {+ const agent = readFileSync(resolve(__dirname, '../useAgentChat.ts'), 'utf8')+ const at = agent.indexOf('dropCutOffCall(toolCalls, turnFinishReason)')+ expect(at).toBeGreaterThan(agent.indexOf('parseLooseToolCalls(turnContent, knownToolNames)'))+ expect(at).toBeLessThan(agent.indexOf('// Over-loop guard'))+ expect(at).toBeLessThan(agent.indexOf('let isFinalTurn = toolCalls.length === 0'))++ const code = readFileSync(resolve(__dirname, '../useCodex.ts'), 'utf8')+ const cat = code.indexOf('dropCutOffCall(toolCalls, turnFinishReason)')+ expect(cat).toBeGreaterThan(code.indexOf('turnFinishReason = hermesTurn.finishReason'))+ expect(cat).toBeLessThan(code.indexOf(' if (toolCalls.length === 0) {'))+ })+})diff --git a/src/hooks/codex/turn-cutoff.ts b/src/hooks/codex/turn-cutoff.tsindex 8c91b6a8..abbb378b 100644--- a/src/hooks/codex/turn-cutoff.ts+++ b/src/hooks/codex/turn-cutoff.ts@@ -31,3 +31,21 @@ export function codexCutoffNote(finishReason: string | undefined, gap: PlanGap |? `${head} The plan stands at ${gap.done} of ${gap.total}, still open: "${gap.next}". ${tail}`: `${head} ${tail}`}++/**+ * The call a cut-off turn was writing when the limit hit.+ *+ * Bug hunt 01.10.2026 (A2). A turn that ends on 'length' can carry a tool call+ * whose arguments stop in the middle: a file_write with half the file, a shell+ * command without its end. Every path that builds calls repairs what it gets+ * (safeParseArgs, repairJson, a closed-off <tool_call>, the loose parser), so+ * the half call came out valid and ran: half a file on disk, reported as+ * written. Output is written in order, so only the LAST call can be the one+ * that was cut; the ones before it were finished before the model moved on.+ * The last one is dropped even when it happens to be whole, because nothing on+ * the wire says which, and one call written again costs less than half a file.+ */+export function dropCutOffCall<T>(calls: T[], finishReason: string | undefined): { calls: T[]; dropped: T | null } {+ if (finishReason !== 'length' || calls.length === 0) return { calls, dropped: null }+ return { calls: calls.slice(0, -1), dropped: calls[calls.length - 1] }+}diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 63a81296..be3bc825 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -108,7 +108,7 @@ import { capHiddenToolHistory } from './codex/hidden-history'// Derselbe Satz wie im Code Reiter, aus derselben Datei: der Fall ist// derselbe, und zwei Wortlaute fuer einen abgeschnittenen Zug waeren zwei// Stellen, von denen eine gepflegt wird.-import { codexCutoffNote } from './codex/turn-cutoff'+import { codexCutoffNote, dropCutOffCall } from './codex/turn-cutoff'import { asString, errorText, prop } from '../types/json-guards'import type { ToolArgs } from '../api/mcp/types'import { CREDITS_EXHAUSTED_MESSAGE } from '../lib/credits-exhausted'@@ -1982,6 +1982,17 @@ export function useAgentChat() {// agent's internal history; this only cleans the visible bubble.turnContent = stripToolCallText(turnContent, knownToolNames)+ // A turn cut off by the token limit: its last call may stop halfway+ // (dropCutOffCall). Checked after the loose fallback, which reads the+ // same cut text.+ {+ const cut = dropCutOffCall(toolCalls, turnFinishReason)+ if (cut.dropped) {+ toolCalls = cut.calls+ log.info('agent.cut_off_call_dropped', { name: cut.dropped.function.name })+ }+ }+// Over-loop guard: keep only the media the user asked for (once each) and// drop any tool call that exactly repeats one already run this turn.if (toolCalls.length > 0) {diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 62356cf8..d8dfddc6 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -103,7 +103,7 @@ import { shouldDowngradeThinking, engineDeniedThinking } from './codex/thinking-import { recoverToolCallsFromContent } from './codex/tool-call-recovery'import { codexStallVerdict } from './codex/stall-verdict'import { createStagedWriter } from './codex/staged-writes'-import { codexCutoffNote } from './codex/turn-cutoff'+import { codexCutoffNote, dropCutOffCall } from './codex/turn-cutoff'import { codexToolDiff, codexEventKind } from './codex/tool-result-view'import { capHiddenToolHistory } from './codex/hidden-history'import { withHouseConduct } from '../lib/system-prompt'@@ -1901,6 +1901,15 @@ export function useCodex() {}}+ // A turn cut off by the token limit: its last call may stop halfway.+ {+ const cut = dropCutOffCall(toolCalls, turnFinishReason)+ if (cut.dropped) {+ toolCalls = cut.calls+ diagLog('cut-off-call-dropped', { iter: i, name: (cut.dropped as { function?: { name?: string } }).function?.name })+ }+ }+// No tool calls in this turn. For a strong model that means "task// done". For a small local model it's usually a PREMATURE stop — it// narrated the next step or asked for info instead of acting. Nudge it