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): "continue" kennt den bisherigen Lauf, auch nach Abbruch und Kuerzung

purple1193ec5f5018
diff --git a/e2e/cloud-agent-tab-switch.spec.ts b/e2e/cloud-agent-tab-switch.spec.ts
new file mode 100644
index 00000000..258cfb1a
--- /dev/null
+++ b/e2e/cloud-agent-tab-switch.spec.ts
@@ -0,0 +1,207 @@
+import { test, expect, type Page } from '@playwright/test'
+import { tauriMockInit, DEFAULT_MODEL_NAME, DEFAULT_ASSISTANT_REPLY } from './support/tauri-mock'
+import { seedOnboardingDone, routeCloud, signInViaGate, cloudSwitch } from './support/cloud-mock'
+
+/**
+ * Customer case 30.09.2026 (swift_maple90), second mail, the customer's own
+ * setup: LU Cloud model, desktop app, a run in progress, a trip to Settings.
+ * "task is stopped and start from begining again". Same checks as the
+ * built-in engine spec in coding-agent.spec.ts, over the cloud transport.
+ */
+const cors = { 'access-control-allow-origin': '*', 'access-control-allow-headers': 'authorization, content-type' }
+
+async function bootCloud(page: Page, bodies: string[], stepMs: number, failAt = -1, files: Record<string, string> = {}) {
+ await page.addInitScript(tauriMockInit, { assistantReply: DEFAULT_ASSISTANT_REPLY, modelName: DEFAULT_MODEL_NAME, files })
+ await seedOnboardingDone(page)
+ await page.addInitScript(() => {
+ window.localStorage.setItem('locally-uncensored-permissions', JSON.stringify({
+ state: {
+ globalPermissions: { filesystem: 'auto', terminal: 'auto', desktop: 'auto', web: 'auto', system: 'auto', image: 'auto', video: 'auto', workflow: 'auto' },
+ conversationOverrides: {}, perToolOverrides: {}, modeScope: 'agent',
+ },
+ version: 2,
+ }))
+ })
+ await routeCloud(page, { license: 'active', access: true, mediaLive: true, paidPlan: true })
+ await page.route('**/api/inference/v1/models', (route) => route.fulfill({
+ status: 200, headers: cors, contentType: 'application/json',
+ body: JSON.stringify({ object: 'list', data: [{
+ id: 'moonshotai/Kimi-K2.6', name: 'Kimi K2.6', context_length: 262144, supports_tools: true, think: 'never',
+ }] }),
+ }))
+ let n = 0
+ await page.route('**/api/inference/v1/chat/completions', async (route) => {
+ if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204, headers: cors })
+ bodies.push(route.request().postData() ?? '')
+ const i = n++
+ await new Promise((r) => setTimeout(r, stepMs))
+ // The line drops mid-run, the way the 60 s idle cut ended the customer's runs.
+ if (i === failAt) return route.abort('connectionreset').catch(() => {})
+ const call = { index: 0, id: `c${i}`, type: 'function', function: { name: 'file_read', arguments: JSON.stringify({ path: `src/file-${i}.ts` }) } }
+ const sse = [
+ { choices: [{ index: 0, delta: { role: 'assistant', content: `step ${i + 1}` }, finish_reason: null }] },
+ { choices: [{ index: 0, delta: { tool_calls: [call] }, finish_reason: null }] },
+ { choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }] },
+ ].map((c) => `data: ${JSON.stringify(c)}\n\n`).join('') + 'data: [DONE]\n\n'
+ return route.fulfill({ status: 200, headers: cors, contentType: 'text/event-stream', body: sse }).catch(() => {})
+ })
+ await page.goto('/')
+ await signInViaGate(page)
+ await expect(cloudSwitch(page)).toBeChecked()
+}
+
+async function pickKimi(page: Page) {
+ await page.getByRole('button', { name: 'Select chat model', exact: true }).click()
+ await page.getByRole('button', { name: /Kimi K2\.6/ }).first().click()
+}
+
+for (const mode of ['code', 'agent'] as const) {
+ test(`cloud ${mode}: a trip to Settings neither stops nor restarts the run`, async ({ page }) => {
+ const bodies: string[] = []
+ await bootCloud(page, bodies, 400)
+ // The model first, in the chat view: it is global, the Code tab then
+ // opens with it.
+ await page.getByRole('button', { name: /New Chat/i }).first().click()
+ await pickKimi(page)
+ if (mode === 'code') {
+ await page.getByRole('button', { name: 'Code', exact: true }).click()
+ await expect(async () => {
+ await page.getByRole('button', { name: /New Chat/i }).first().click()
+ await expect(page.locator('textarea').first()).toBeVisible({ timeout: 2_000 })
+ }).toPass({ timeout: 30_000 })
+ }
+ if (mode === 'agent') {
+ const toggle = page.getByRole('main').getByRole('button', { name: 'Agent', exact: true })
+ // The toggle needs a conversation; the model pick may have reset it.
+ await expect(async () => {
+ if (!(await toggle.isVisible().catch(() => false))) {
+ await page.getByRole('button', { name: /New Chat/i }).first().click()
+ }
+ await expect(toggle).toBeVisible({ timeout: 2_000 })
+ }).toPass({ timeout: 30_000 })
+ await toggle.click()
+ const sandbox = page.getByRole('button', { name: /^Sandbox/ })
+ await expect(sandbox).toBeVisible({ timeout: 15_000 })
+ await sandbox.click()
+ }
+ const composer = page.locator('textarea').first()
+ await expect(composer).toBeEnabled({ timeout: 20_000 })
+ await composer.fill('walk the whole source tree')
+ await composer.press('Enter')
+ await expect.poll(() => bodies.length, { timeout: 20_000 }).toBeGreaterThan(2)
+
+ const header = page.getByRole('banner')
+ const before = bodies.length
+ await header.getByRole('button', { name: 'Settings' }).click()
+ await page.waitForTimeout(3_000)
+ const whileAway = bodies.length
+ await header.getByRole('button', { name: 'Chat' }).click()
+
+ expect(whileAway, 'the run stopped while Settings was open').toBeGreaterThan(before)
+ await expect(page.getByRole('button', { name: /Stop/i })).toBeVisible({ timeout: 20_000 })
+ const back = bodies.length
+ await expect.poll(() => bodies.length, { timeout: 20_000 }).toBeGreaterThan(back)
+
+ const last = JSON.parse(bodies[bodies.length - 1])
+ expect(JSON.stringify(last.messages)).toContain('src/file-0.ts')
+ const asks = (last.messages as Array<{ role: string; content: unknown }>)
+ .filter((m) => m.role === 'user' && JSON.stringify(m.content).includes('walk the whole source tree'))
+ expect(asks.length).toBe(1)
+ await page.getByRole('button', { name: /Stop/i }).click()
+ })
+}
+
+for (const mode of ['code', 'agent'] as const) {
+ test(`cloud ${mode}: after a dropped run, "continue" picks up where it was`, async ({ page }) => {
+ const bodies: string[] = []
+ await bootCloud(page, bodies, 150, 4)
+ await page.getByRole('button', { name: /New Chat/i }).first().click()
+ await pickKimi(page)
+ if (mode === 'code') {
+ await page.getByRole('button', { name: 'Code', exact: true }).click()
+ await expect(async () => {
+ await page.getByRole('button', { name: /New Chat/i }).first().click()
+ await expect(page.locator('textarea').first()).toBeVisible({ timeout: 2_000 })
+ }).toPass({ timeout: 30_000 })
+ } else {
+ const toggle = page.getByRole('main').getByRole('button', { name: 'Agent', exact: true })
+ await expect(async () => {
+ if (!(await toggle.isVisible().catch(() => false))) {
+ await page.getByRole('button', { name: /New Chat/i }).first().click()
+ }
+ await expect(toggle).toBeVisible({ timeout: 2_000 })
+ }).toPass({ timeout: 30_000 })
+ await toggle.click()
+ const sandbox = page.getByRole('button', { name: /^Sandbox/ })
+ await expect(sandbox).toBeVisible({ timeout: 15_000 })
+ await sandbox.click()
+ }
+ const composer = page.locator('textarea').first()
+ await expect(composer).toBeEnabled({ timeout: 20_000 })
+ await composer.fill('walk the whole source tree')
+ await composer.press('Enter')
+
+ // The run dies on the fifth request and hands the composer back.
+ await expect.poll(() => bodies.length, { timeout: 30_000 }).toBeGreaterThanOrEqual(5)
+ await expect(page.getByRole('button', { name: 'Send message' })).toBeVisible({ timeout: 90_000 })
+ const beforeContinue = bodies.length
+
+ await composer.fill('continue')
+ await composer.press('Enter')
+ await expect.poll(() => bodies.length, { timeout: 30_000 }).toBeGreaterThan(beforeContinue)
+
+ // The first request of the new run still knows the steps already done:
+ // either the calls themselves, or the run ledger once the kept chain was
+ // capped (a long run keeps its last 30 steps and a ledger for the rest).
+ const first = JSON.stringify(JSON.parse(bodies[beforeContinue]).messages)
+ const doneSteps = beforeContinue - 1
+ if (doneSteps > 30) {
+ expect(first, '"continue" lost the earlier steps without a ledger').toContain('[Run ledger]')
+ expect(first).toMatch(/older steps/)
+ } else {
+ for (const done of ['src/file-0.ts', 'src/file-1.ts', 'src/file-2.ts', 'src/file-3.ts']) {
+ expect(first, `"continue" lost ${done}`).toContain(done)
+ }
+ }
+ const stop = page.getByRole('button', { name: /Stop/i })
+ if (await stop.isVisible().catch(() => false)) await stop.click()
+ })
+}
+
+test('cloud code: a long run that outgrew its window keeps a ledger for "continue"', async ({ page }) => {
+ const bodies: string[] = []
+ // 45 files of about 1.5k tokens each: the run passes the 32K send window and
+ // gets trimmed long before the line drops on request 46.
+ const files: Record<string, string> = {}
+ for (let i = 0; i < 60; i++) files[`file-${i}.ts`] = `// file ${i}\n` + 'const x = 1\n'.repeat(500)
+ await bootCloud(page, bodies, 60, 45, files)
+ await page.getByRole('button', { name: /New Chat/i }).first().click()
+ await pickKimi(page)
+ await page.getByRole('button', { name: 'Code', exact: true }).click()
+ await expect(async () => {
+ await page.getByRole('button', { name: /New Chat/i }).first().click()
+ await expect(page.locator('textarea').first()).toBeVisible({ timeout: 2_000 })
+ }).toPass({ timeout: 30_000 })
+ const composer = page.locator('textarea').first()
+ await expect(composer).toBeEnabled({ timeout: 20_000 })
+ await composer.fill('walk the whole source tree')
+ await composer.press('Enter')
+ await expect(page.getByRole('button', { name: 'Send message' })).toBeVisible({ timeout: 120_000 })
+ expect(bodies.length).toBeGreaterThanOrEqual(46)
+ // The run really was trimmed mid-way.
+ expect(bodies.some((b) => b.includes('[Run ledger]'))).toBe(true)
+
+ const beforeContinue = bodies.length
+ await composer.fill('continue')
+ await composer.press('Enter')
+ await expect.poll(() => bodies.length, { timeout: 30_000 }).toBeGreaterThan(beforeContinue)
+ const first = JSON.stringify(JSON.parse(bodies[beforeContinue]).messages)
+ expect(first, 'the persisted chain lost the ledger').toContain('[Run ledger]')
+ expect(first).toContain('src/file-0.ts')
+ // The newest steps are there as real calls, not only as ledger lines.
+ const calls = (JSON.parse(bodies[beforeContinue]).messages as Array<{ tool_calls?: Array<{ function: { arguments: string } }> }>)
+ .flatMap((m) => m.tool_calls ?? []).map((c) => c.function.arguments)
+ expect(calls.some((a) => a.includes('src/file-44.ts'))).toBe(true)
+ const stop = page.getByRole('button', { name: /Stop/i })
+ if (await stop.isVisible().catch(() => false)) await stop.click()
+})
diff --git a/e2e/coding-agent.spec.ts b/e2e/coding-agent.spec.ts
index a1b48a5d..f1bed8af 100644
--- a/e2e/coding-agent.spec.ts
+++ b/e2e/coding-agent.spec.ts
@@ -337,3 +337,58 @@ test('file_edit: several edits in one call, one of them with the indentation off
expect(content).toContain('line 9\nLINE TEN\nLINE ELEVEN\nline 12')
expect(content).toContain('line 149\nLINE 150\nline 151')
})
+
+/**
+ * Customer case 30.09.2026 (swift_maple90, Windows desktop), second mail: "if
+ * i go to any other tabs like setting or somewhere task is stopped and start
+ * from begining again". The spec above only walked Code → Models → back. This
+ * walks the customer's way, into Settings, in both loops, and checks the two
+ * halves of the complaint separately: the run keeps working while the user is
+ * away, and every later request still carries the steps before the switch.
+ */
+const bodies = (page: Page) =>
+ page.evaluate(() => ((window as unknown as { __E2E_CHAT_BODIES__?: string[] }).__E2E_CHAT_BODIES__ ?? []).slice())
+
+async function awayToSettingsAndBack(page: Page) {
+ const header = page.getByRole('banner')
+ const before = (await toolCalls(page)).length
+ await header.getByRole('button', { name: 'Settings' }).click()
+ await page.waitForTimeout(2_500)
+ const whileAway = (await toolCalls(page)).length
+ await header.getByRole('button', { name: 'Chat' }).click()
+ return { before, whileAway }
+}
+
+for (const mode of ['code', 'agent'] as const) {
+ test(`${mode}: a run keeps going through a trip to Settings and does not start over`, async ({ page }) => {
+ const turns: Turn[] = Array.from({ length: 60 }, (_, i) => ({
+ text: `step ${i + 1}`,
+ toolCalls: [{ name: 'file_read', args: { path: `src/file-${i}.ts` } }],
+ }))
+ if (mode === 'code') await boot(page, turns)
+ else await bootAgentMode(page, turns)
+
+ await instruct(page, 'walk the whole source tree')
+ await expect.poll(async () => (await toolCalls(page)).length, { timeout: 20_000 }).toBeGreaterThan(2)
+
+ const { before, whileAway } = await awayToSettingsAndBack(page)
+ // Not stopped while the user looked at Settings.
+ expect(whileAway).toBeGreaterThan(before)
+
+ // Back in the chat the run is still the same run: Stop is offered and it
+ // keeps working.
+ await expect(page.getByRole('button', { name: /Stop/i })).toBeVisible({ timeout: 20_000 })
+ const back = (await toolCalls(page)).length
+ await expect.poll(async () => (await toolCalls(page)).length, { timeout: 20_000 }).toBeGreaterThan(back)
+
+ // Not started over: the newest request still carries the first step.
+ const all = await bodies(page)
+ expect(all[all.length - 1]).toContain('src/file-0.ts')
+ // And the instruction went out once, not a second time as a fresh run.
+ const lastMsgs = JSON.parse(all[all.length - 1]).messages as Array<{ role: string; content: unknown }>
+ const asks = lastMsgs.filter((m) => m.role === 'user' && String(m.content).includes('walk the whole source tree'))
+ expect(asks.length).toBe(1)
+
+ await page.getByRole('button', { name: /Stop/i }).click()
+ })
+}
diff --git a/src/hooks/__tests__/decay-wiring.test.ts b/src/hooks/__tests__/decay-wiring.test.ts
index 7eca8405..75a6155f 100644
--- a/src/hooks/__tests__/decay-wiring.test.ts
+++ b/src/hooks/__tests__/decay-wiring.test.ts
@@ -89,8 +89,11 @@ describe.each([
})
describe('useCodex keeps the working history whole for the store', () => {
- it('still persists the hidden tool chain from the untouched array', () => {
- expect(codex).toMatch(/const toolHistoryAll = messages\.slice\(messagesStartLen\)/)
+ it('still persists the hidden tool chain, by identity across trims', () => {
+ // 30.09.2026: an index into `messages` pointed at the wrong place once a
+ // long run had been trimmed, and the chain lost its ledger.
+ expect(codex).toMatch(/const toolHistoryAll = runLog/)
+ expect(codex).toMatch(/logRun\(\)\s*\n\s*const beforeTrim = new Set\(messages\)/)
})
it('shortens restored tool messages of PREVIOUS turns', () => {
diff --git a/src/hooks/codex/__tests__/weiter-kennt-den-anfang.test.ts b/src/hooks/codex/__tests__/weiter-kennt-den-anfang.test.ts
new file mode 100644
index 00000000..b86effd3
--- /dev/null
+++ b/src/hooks/codex/__tests__/weiter-kennt-den-anfang.test.ts
@@ -0,0 +1,49 @@
+/**
+ * Kundenfall 30.09.2026 (swift_maple90, zweite Mail): "when it stopped i will
+ * continue the task then its start from again reapting same and same always".
+ * Am Ende eines Laufs bleiben nur die letzten 60 Nachrichten der Werkzeugkette
+ * gespeichert. Was davor lag, stand nirgends mehr, auch nicht im sichtbaren
+ * Verlauf, also fing der naechste Zug von vorn an.
+ *
+ * Run: npx vitest run src/hooks/codex/__tests__/weiter-kennt-den-anfang.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { capHiddenToolHistory } from '../hidden-history'
+import type { ChatMessage } from '../../../api/providers/types'
+
+function lauf(schritte: number): ChatMessage[] {
+ const out: ChatMessage[] = []
+ for (let i = 0; i < schritte; i++) {
+ out.push({
+ role: 'assistant', content: `step ${i}`,
+ tool_calls: [{ id: `c${i}`, type: 'function', function: { name: 'file_read', arguments: { path: `src/file-${i}.ts` } } }],
+ } as unknown as ChatMessage)
+ out.push({ role: 'tool', content: 'x', tool_call_id: `c${i}` } as unknown as ChatMessage)
+ }
+ return out
+}
+
+describe('die gekappte Werkzeugkette', () => {
+ it('traegt die weggeschnittenen Schritte als Protokoll', () => {
+ const kette = capHiddenToolHistory(lauf(100))
+ expect(kette.length).toBeLessThanOrEqual(60)
+ const erste = String(kette[0].content)
+ expect(erste).toContain('[Run ledger]')
+ // 70 Schritte fielen weg: die juengsten 40 namentlich, die aelteren gezaehlt.
+ expect(erste).toContain('(30 older steps)')
+ expect(erste).toContain('file_read: src/file-30.ts')
+ expect(erste).toContain('file_read: src/file-69.ts')
+ // Nichts doppelt: was behalten ist, steht nicht im Protokoll.
+ expect(erste).not.toContain('src/file-70.ts')
+ // Der Aufruf selbst ist unveraendert, die Paarung bleibt.
+ expect(kette[0].role).toBe('assistant')
+ expect((kette[0] as unknown as { tool_calls: unknown[] }).tool_calls).toHaveLength(1)
+ expect(kette[1].role).toBe('tool')
+ })
+
+ it('laesst eine kurze Kette ohne Protokoll', () => {
+ const kette = capHiddenToolHistory(lauf(10))
+ expect(kette).toHaveLength(20)
+ expect(String(kette[0].content)).toBe('step 0')
+ })
+})
diff --git a/src/hooks/codex/hidden-history.ts b/src/hooks/codex/hidden-history.ts
index e62fad08..ef25b491 100644
--- a/src/hooks/codex/hidden-history.ts
+++ b/src/hooks/codex/hidden-history.ts
@@ -1,4 +1,5 @@
import type { ChatMessage } from '../../api/providers/types'
+import { runLedger, type DecayMessage } from '../../lib/context-decay'
/**
* Die versteckte Werkzeugkette, die der naechste Zug wiederbekommt.
@@ -36,5 +37,18 @@ export function capHiddenToolHistory(
// Never start the kept slice on an orphan tool result — strict
// providers 422 a result whose call fell outside the window.
while (toolHistory.length > 0 && toolHistory[0].role === 'tool') toolHistory = toolHistory.slice(1)
+ // 3. DAS PROTOKOLL (Kundenfall 30.09.2026, swift_maple90: "when it stopped
+ // i will continue the task then its start from again"). Was hier
+ // wegfaellt, stand NICHT im sichtbaren Verlauf, die Blase zeigt nur den
+ // Schlusstext. Nach "continue" sah das Modell die letzten 30 Schritte und
+ // nichts davor, also fing es von vorn an. Die weggeschnittenen Aufrufe
+ // kommen deshalb als eine Zeile je Aufruf an die erste behaltene Nachricht.
+ const dropped = all.slice(0, all.length - toolHistory.length)
+ const ledger = dropped.length > 0 ? runLedger(dropped as unknown as DecayMessage[]) : null
+ if (ledger && toolHistory.length > 0) {
+ const [first, ...rest] = toolHistory
+ const body = typeof first.content === 'string' ? first.content : ''
+ toolHistory = [{ ...first, content: body ? `${ledger}\n\n${body}` : ledger }, ...rest]
+ }
return toolHistory
}
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index b24b8744..72ca76cd 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -2788,30 +2788,6 @@ export function useAgentChat() {
runState.content = closingSummary()
}
- // Die Werkzeugkette als versteckte Nachrichten ablegen, VOR der
- // Assistentenantwort — genau wie useCodex es tut (dieselbe Deckelung,
- // derselbe Waisenschnitt aus hooks/codex/hidden-history.ts: ein Fenster,
- // das mit einem Ergebnis ohne seinen Aufruf beginnt, laesst strenge
- // Anbieter mit 422 antworten). Ohne das hier sah die naechste Runde nur
- // noch den Antworttext und holte dieselbe Seite ein zweites Mal.
- if (werkzeugKette.length > 0 && convId) {
- const kette = capHiddenToolHistory(werkzeugKette)
- const store = useChatStore.getState()
- const convNow = store.conversations.find((c) => c.id === convId)
- const idx = convNow?.messages.findIndex((m) => m.id === assistantMessage.id) ?? -1
- if (kette.length > 0 && idx > 0) {
- store.insertMessagesBefore(convId, assistantMessage.id, kette.map((tm) => ({
- id: uuid(),
- role: tm.role as import('../types/chat').Message['role'],
- content: tm.content || '',
- timestamp: Date.now(),
- hidden: true,
- ...(tm.tool_calls ? { tool_calls: tm.tool_calls as import('../types/chat').Message['tool_calls'] } : {}),
- ...(tm.tool_call_id ? { tool_call_id: tm.tool_call_id } : {}),
- })))
- }
- }
-
// Final store update
useChatStore.getState().updateMessageContent(convId!, assistantMessage.id, runState.content)
if (runState.thinking) {
@@ -2959,6 +2935,32 @@ export function useAgentChat() {
useGenerationStore.getState().clearAborter(convId)
activeAgentRuns.delete(convId)
}
+ // Die Werkzeugkette als versteckte Nachrichten ablegen, VOR der
+ // Assistentenantwort. Im finally, nicht am Ende des Erfolgswegs: ein Lauf,
+ // der mit einem Fehler oder Abbruch endete, verlor sonst seine ganze Kette,
+ // und "continue" fing von vorn an (Kundenfall swift_maple90, 30.09.2026) — genau wie useCodex es tut (dieselbe Deckelung,
+ // derselbe Waisenschnitt aus hooks/codex/hidden-history.ts: ein Fenster,
+ // das mit einem Ergebnis ohne seinen Aufruf beginnt, laesst strenge
+ // Anbieter mit 422 antworten). Ohne das hier sah die naechste Runde nur
+ // noch den Antworttext und holte dieselbe Seite ein zweites Mal.
+ if (werkzeugKette.length > 0 && convId) {
+ const kette = capHiddenToolHistory(werkzeugKette)
+ const store = useChatStore.getState()
+ const convNow = store.conversations.find((c) => c.id === convId)
+ const idx = convNow?.messages.findIndex((m) => m.id === assistantMessage.id) ?? -1
+ if (kette.length > 0 && idx > 0) {
+ store.insertMessagesBefore(convId, assistantMessage.id, kette.map((tm) => ({
+ id: uuid(),
+ role: tm.role as import('../types/chat').Message['role'],
+ content: tm.content || '',
+ timestamp: Date.now(),
+ hidden: true,
+ ...(tm.tool_calls ? { tool_calls: tm.tool_calls as import('../types/chat').Message['tool_calls'] } : {}),
+ ...(tm.tool_call_id ? { tool_call_id: tm.tool_call_id } : {}),
+ })))
+ }
+ }
+
// Chat-tools artifact mode: attach any files the model "wrote" (captured
// in-memory, NOT on disk) to the assistant message so they render inline
// with a preview + Download button. takeChatArtifacts drains this run's
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 824624b7..f46b284e 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -893,7 +893,7 @@ export function useCodex() {
// from a history whose newest todo_write may have aged out or fallen off
// the 60-message persist cap below. Last in the array, so the stable head
// a prefix cache matches stays byte-identical (plan A5), and BEFORE
- // messagesStartLen so the anchor is never persisted back into the chat.
+ // the run log starts, so the anchor is never persisted back into the chat.
if (convId) {
const resume = planResumeAnchor(useTodoStore.getState().getTodos(convId))
if (resume) {
@@ -935,7 +935,23 @@ export function useCodex() {
}
}
- const messagesStartLen = messages.length
+ // What this run adds, by identity instead of by index. `messages` gets
+ // trimmed during a long run (trimWorkingHistory), so an index taken here
+ // pointed into the wrong place at the end: the persisted chain lost its
+ // older steps and the ledger with them, and "continue" started over
+ // (customer case swift_maple90, 30.09.2026). `runLog` keeps every message
+ // the run itself pushed, in order; a copy the trim makes (the pinned task
+ // with its ledger) is not the run's own and is kept out.
+ const notRunOwn = new Set<ChatMessage>(messages)
+ const runLog: ChatMessage[] = []
+ const logged = new Set<ChatMessage>()
+ const logRun = () => {
+ for (const m of messages) {
+ if (notRunOwn.has(m) || logged.has(m)) continue
+ logged.add(m)
+ runLog.push(m)
+ }
+ }
// Setup
const abort = new AbortController()
@@ -1264,7 +1280,10 @@ export function useCodex() {
// moves every step is a prompt prefix that is never the same twice.
// Whole messages are dropped here, never shortened: decay stays on
// the send copy alone, so the store keeps every result complete.
+ logRun()
+ const beforeTrim = new Set(messages)
messages = trimWorkingHistory(messages, sendWindow, { enabled: decayOn, hysteresis: decayOn }).messages
+ for (const m of messages) if (!beforeTrim.has(m)) notRunOwn.add(m)
const built = buildRequestMessages(messages, {
budgetTokens: sendWindow,
enabled: decayOn,
@@ -2520,7 +2539,8 @@ export function useCodex() {
// one-set()-per-message insert loop was the visible hang at run end.
// The most recent chain is what the next turn actually needs; older
// steps are summarised by the visible transcript anyway.
- const toolHistoryAll = messages.slice(messagesStartLen)
+ logRun()
+ const toolHistoryAll = runLog
// Deckelung UND Waisenschnitt gehoeren zusammen: hooks/codex/hidden-history.ts.
const toolHistory = capHiddenToolHistory(toolHistoryAll)
if (toolHistory.length > 0 && convId) {
diff --git a/src/lib/__tests__/plan-resume.test.ts b/src/lib/__tests__/plan-resume.test.ts
index 2fc0f70e..894cc346 100644
--- a/src/lib/__tests__/plan-resume.test.ts
+++ b/src/lib/__tests__/plan-resume.test.ts
@@ -151,10 +151,10 @@ describe('both surfaces are wired, in the request copy only', () => {
expect(codex).toContain('planResumeAnchor(useTodoStore.getState().getTodos(convId))')
const pushAt = codex.indexOf("messages.push({ role: 'user', content: resume.text })")
const builtAt = codex.indexOf('let messages: ChatMessage[] = [')
- const startLenAt = codex.indexOf('const messagesStartLen = messages.length')
+ const startLenAt = codex.indexOf('const notRunOwn = new Set<ChatMessage>(messages)')
expect(pushAt).toBeGreaterThan(builtAt)
- // Before the marker the hidden-history persist slices from: the anchor is
- // a request line, it must never be written back into the conversation.
+ // Before the run log starts: the anchor is a request line, it must never
+ // be written back into the conversation.
expect(pushAt).toBeLessThan(startLenAt)
})