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(workflow): dedupe nested Error: prefix, note the VRAM exception and the exit-time price, add a test resetter

purple1e75b4d927a2
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index 8e73271d..ae7a0631 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -1637,7 +1637,14 @@ async function executeRunWorkflow(args: ToolArgs, run?: AgentRunContext, abort?:
// THAT engine's own `onComplete` then wrapped it in its own
// "Workflow complete" header, a false positive one level removed from
// the one Auflage 2.1 fixed at the tool layer.
- finalOutput = `Error: ${describeWorkflowStepFailure(workflow, idx, error)}`
+ // R2-5 (lu-301/bau/review-offload2.md, Runde 2): `error` itself is
+ // often already the tool's own "Error: ..." text (see the comment
+ // above), so prefixing blindly used to read "Error: Workflow stopped
+ // at step 1 of 5: Error: Web search failed: ...". One "Error:" is the
+ // detection prefix this tool result needs, the other is noise; strip a
+ // leading one from the inner text before adding the outer one.
+ const innerError = error.startsWith('Error: ') ? error.slice('Error: '.length) : error
+ finalOutput = `Error: ${describeWorkflowStepFailure(workflow, idx, innerError)}`
},
onWaitingForInput: () => {},
onComplete: (allResults: StepResult[]) => {
diff --git a/src/lib/__tests__/run-workflow-nested-error-not-doubled.test.ts b/src/lib/__tests__/run-workflow-nested-error-not-doubled.test.ts
new file mode 100644
index 00000000..e69560e6
--- /dev/null
+++ b/src/lib/__tests__/run-workflow-nested-error-not-doubled.test.ts
@@ -0,0 +1,77 @@
+/**
+ * R2-5 (lu-301/bau/review-offload2.md, Runde 2, kosmetisch): `run_workflow`'s
+ * own tool result needs an "Error:" prefix so an OUTER engine's
+ * `executeToolStep` (`startsWith('Error:')`) recognizes a nested workflow
+ * failure (see the long comment on `onStepError` in
+ * `api/mcp/builtin-tools.ts`, `executeRunWorkflow`). The step's own `error`
+ * is often ALREADY a tool's raw "Error: ..." text (a failed `web_search` or
+ * `web_fetch`), so prefixing it a second time used to read "Error: Workflow
+ * stopped at step 1 of 1: Error: Web search failed: ...". This drives
+ * `run_workflow` for real over a workflow whose only step is a failing
+ * `web_search`, and checks the returned tool result carries "Error:" exactly
+ * once.
+ *
+ * Run: npx vitest run src/lib/__tests__/run-workflow-nested-error-not-doubled.test.ts
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+
+const backendCall = vi.fn(async (..._args: unknown[]) => ({}))
+
+vi.mock('../../api/backend', async () => {
+ const actual = await vi.importActual<typeof import('../../api/backend')>('../../api/backend')
+ return { ...actual, backendCall: (...a: unknown[]) => backendCall(...a) }
+})
+
+import { toolRegistry, registerBuiltinTools } from '../../api/mcp'
+import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'
+import { useModelStore } from '../../stores/modelStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import { __resetRunLanesForTests } from '../run-lanes'
+import type { AgentWorkflow, WorkflowStep } from '../../types/agent-workflows'
+
+function workflowOf(id: string, name: string, steps: WorkflowStep[]): AgentWorkflow {
+ return { id, name, description: '', icon: 'Zap', steps, variables: {}, isBuiltIn: false, createdAt: 0, updatedAt: 0 }
+}
+
+beforeEach(() => {
+ __resetRunLanesForTests()
+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
+ useModelStore.setState({ activeModel: 'anthropic::claude' })
+ backendCall.mockClear()
+ registerBuiltinTools(toolRegistry)
+ const inner = workflowOf('inner-fail-id', 'inner-fail', [
+ { id: 'search', type: 'tool', label: 'Search the web', toolName: 'web_search', toolArgTemplates: { query: '{{user_input}}' } },
+ ])
+ useAgentWorkflowStore.setState({ workflows: [inner] })
+})
+
+describe('a failing tool step inside a nested run_workflow carries exactly one "Error:"', () => {
+ it('the returned tool result is not doubled', async () => {
+ backendCall.mockImplementation(async (...args: unknown[]) => {
+ const cmd = args[0] as string
+ if (cmd === 'web_search') return { error: 'All search tiers failed' }
+ throw new Error(`unexpected backendCall: ${cmd}`)
+ })
+
+ const output = await toolRegistry.execute('run_workflow', { name: 'inner-fail', input: 'the history of tea' })
+
+ // Still detectable as a failure by an outer engine.
+ expect(output.startsWith('Error:')).toBe(true)
+ // But the word appears only once now, not doubled.
+ expect(output.match(/Error:/g)?.length).toBe(1)
+ expect(output).toBe('Error: Workflow stopped at step 1 of 1: Web search failed: All search tiers failed')
+ })
+
+ it('Gegenprobe: a working search reports completion with no "Error:" at all', async () => {
+ backendCall.mockImplementation(async (...args: unknown[]) => {
+ const cmd = args[0] as string
+ if (cmd === 'web_search') return { results: [{ title: 'Tea', url: 'https://tea.example', snippet: 'history of tea' }] }
+ throw new Error(`unexpected backendCall: ${cmd}`)
+ })
+
+ const output = await toolRegistry.execute('run_workflow', { name: 'inner-fail', input: 'the history of tea' })
+
+ expect(output).not.toContain('Error:')
+ expect(output).toContain('Workflow complete')
+ })
+})
diff --git a/src/lib/cloud-offload-defer.ts b/src/lib/cloud-offload-defer.ts
index 3b7e2d30..e96c718d 100644
--- a/src/lib/cloud-offload-defer.ts
+++ b/src/lib/cloud-offload-defer.ts
@@ -53,6 +53,13 @@
* ein haengender Lauf haelt jetzt VRAM fest statt eine fremde Unterhaltung
* zu toeten. Der einzige Ausweg aus diesem Zustand ist Stop auf dem
* haengenden Lauf selbst.
+ *
+ * Zweiter Preis (R2-4, lu-301/bau/review-offload2.md, Runde 2): beendet der
+ * Nutzer die App, waehrend ein Entladen wartet, raeumt `shutdown_subprocesses`
+ * nur die eigenen Kindprozesse des eingebauten Motors weg, nie ein
+ * LM-Studio- oder Ollama-Modell, das dadurch nie entladen wird. Ollama holt
+ * das ueber sein eigenes `keep_alive` irgendwann von selbst nach, LM Studio
+ * je nach dortiger Einstellung gar nicht.
*/
/** Die eine Tatsache, an der sich alles hier entscheidet. */
diff --git a/src/stores/__tests__/modelStore-defers-engine-stop-during-local-run.test.ts b/src/stores/__tests__/modelStore-defers-engine-stop-during-local-run.test.ts
index ec54657c..687cb4ef 100644
--- a/src/stores/__tests__/modelStore-defers-engine-stop-during-local-run.test.ts
+++ b/src/stores/__tests__/modelStore-defers-engine-stop-during-local-run.test.ts
@@ -39,7 +39,7 @@ vi.mock('../../api/lmstudio', () => ({
unloadLmStudioModel: (...a: unknown[]) => unloadLmStudioModel(...a),
}))
-import { useModelStore } from '../modelStore'
+import { useModelStore, __resetDeferredLocalUnloadsForTests } from '../modelStore'
import { useGenerationStore } from '../generationStore'
import type { AIModel } from '../../types/models'
@@ -61,6 +61,11 @@ beforeEach(() => {
backendCall.mockClear()
unloadModel.mockClear()
unloadLmStudioModel.mockClear()
+ // R2-6 (lu-301/bau/review-offload2.md, Runde 2): `pendingLocalUnloads` is
+ // module state with no test resetter until now. Every test below ends its
+ // own booking before it finishes, so nothing has leaked yet, but this
+ // guards the next test that does not.
+ __resetDeferredLocalUnloadsForTests()
useModelStore.setState({
models: [builtin('qwenA'), builtin('qwenB'), cloudModel('claude-x'), lmsModel('mistral'), ollamaModel('llama3')],
activeModel: 'openai::qwenA',
@@ -219,3 +224,29 @@ describe('the Ollama unload (Auflage 1.1)', () => {
expect(unloadModel).not.toHaveBeenCalledWith('llama3')
})
})
+
+describe('__resetDeferredLocalUnloadsForTests (R2-6)', () => {
+ it('cancels a pending unload left over from a run this test never ends', () => {
+ useModelStore.setState({ activeModel: 'llama3' })
+ useGenerationStore.getState().bookRun(CONV_ID, 'local', RUN_TOKEN)
+ useModelStore.getState().setActiveModel('claude-x') // defers, never ended
+ expect(unloadModel).not.toHaveBeenCalled()
+
+ __resetDeferredLocalUnloadsForTests()
+ // Ending the run now must NOT fire the cancelled unload: the reset threw
+ // away the subscription, so `offloadWhenLocalLaneFree`'s listener is gone
+ // and nothing is left to fire when the lane frees up.
+ useGenerationStore.getState().endRun(CONV_ID, RUN_TOKEN)
+ expect(unloadModel).not.toHaveBeenCalled()
+ })
+
+ it('Gegenprobe: without the reset, that same leftover unload DOES fire once the lane frees', () => {
+ useModelStore.setState({ activeModel: 'llama3' })
+ useGenerationStore.getState().bookRun(CONV_ID, 'local', RUN_TOKEN)
+ useModelStore.getState().setActiveModel('claude-x') // defers, never ended
+ expect(unloadModel).not.toHaveBeenCalled()
+
+ useGenerationStore.getState().endRun(CONV_ID, RUN_TOKEN)
+ expect(unloadModel).toHaveBeenCalledWith('llama3')
+ })
+})
diff --git a/src/stores/modelStore.ts b/src/stores/modelStore.ts
index 2da6e75c..c57e8e16 100644
--- a/src/stores/modelStore.ts
+++ b/src/stores/modelStore.ts
@@ -70,6 +70,17 @@ function deferLocalUnload(target: string, stillWanted: () => boolean, unload: ()
if (!fired) pendingLocalUnloads.set(target, cancel)
}
+/** Test-only (R2-6, lu-301/bau/review-offload2.md, Runde 2): forget every
+ * pending deferred unload so tests stay isolated, the same role
+ * `__resetBuiltinSlotOffloadForTests` plays for `builtin-slot-eviction.ts`'s
+ * own module state. Today's test file always ends its own bookings, so
+ * nothing leaks yet, but the next test that leaves a run unfinished would
+ * otherwise carry a stale cancel function into the following test. */
+export function __resetDeferredLocalUnloadsForTests(): void {
+ for (const cancel of pendingLocalUnloads.values()) cancel()
+ pendingLocalUnloads.clear()
+}
+
export interface PullState {
progress: PullProgress
controller: AbortController
@@ -289,7 +300,13 @@ export const useModelStore = create<ModelState>()(
// Exactly ONE local model stays in VRAM at a time (David 2026-06-12:
// "darf niemals 2 gleichzeitig geladen sein, außer man macht Compare").
// Compare uses its own store + provider calls, NOT setActiveModel, so it
- // is unaffected. Unload the PREVIOUS local model via the right provider.
+ // is unaffected. EXCEPTION (R2-3, lu-301/bau/review-offload2.md, Runde 2):
+ // while a deferred unload is waiting (see `deferLocalUnload` below), the
+ // old local model can briefly sit in VRAM alongside a newly activated
+ // one, because the old one's unload is held back until every local run
+ // still using it has ended. That is not a break of this rule; it is the
+ // documented price of never dropping a run out from under itself.
+ // Unload the PREVIOUS local model via the right provider.
// - Ollama (no provider prefix) → unloadModel
// - LM Studio (openai:: + LM-Studio providerName) → unloadLmStudioModel
// - Cloud (anthropic:: / OpenRouter / OpenAI etc.) → no local VRAM, skip