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): stop a workflow honestly when a step's tool or prompt output was never real

purple95d2d05c5e0d
diff --git a/src/api/mcp/__tests__/web-tools-fail-honestly.test.ts b/src/api/mcp/__tests__/web-tools-fail-honestly.test.ts
new file mode 100644
index 00000000..e6936295
--- /dev/null
+++ b/src/api/mcp/__tests__/web-tools-fail-honestly.test.ts
@@ -0,0 +1,84 @@
+/**
+ * Auflage 2.1 (lu-301/bau/review-offload2.md): `executeToolStep`
+ * (workflow-engine.ts) recognizes a failed tool call ONLY by
+ * `result.startsWith('Error:')`. `executeWebSearch` and `executeWebFetch`
+ * (builtin-tools.ts) used to return failure text that did NOT start with
+ * that prefix: a search failure ("Web search failed: ...") and a fetch
+ * that got a non-2xx status or an empty body both counted as
+ * `status: 'completed'`, so a workflow step that failed for a real reason
+ * ran on as if it had succeeded. This is the reviewer's explanation for the
+ * box's "Research Topic" run finishing in seconds with idle GPU: the chain
+ * never actually stopped on the broken step.
+ *
+ * These tests exercise the two executors directly through the real
+ * `ToolRegistry`, not a copy, same pattern as
+ * web-fetch-nennt-den-grund-des-fallbacks.test.ts.
+ *
+ * Run: npx vitest run src/api/mcp/__tests__/web-tools-fail-honestly.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const backendCall = vi.fn(async (..._args: unknown[]) => ({}))
+
+vi.mock('../../backend', () => ({
+ backendCall: (...a: unknown[]) => backendCall(...a),
+}))
+vi.mock('../../agents/sub-agent', () => ({
+ DELEGATE_TASK_TOOL_DEF: { name: 'delegate_task', description: '', category: 'system', inputSchema: {} },
+ buildDelegateExecutor: () => async () => 'stub',
+}))
+vi.mock('../../../lib/workflow-engine', () => ({ WorkflowEngine: class {} }))
+vi.mock('../../../stores/settingsStore', () => ({
+ useSettingsStore: { getState: () => ({ settings: {} }) },
+}))
+
+import { registerBuiltinTools } from '../builtin-tools'
+import { ToolRegistry } from '../tool-registry'
+
+const registry = new ToolRegistry()
+registerBuiltinTools(registry)
+
+/** The same check `executeToolStep` (workflow-engine.ts) runs on every tool
+ * result before deciding `status: 'completed'` vs `'failed'`. */
+const isMarkedAsFailed = (result: string) => result.startsWith('Error:')
+
+beforeEach(() => {
+ backendCall.mockClear()
+})
+
+describe('executeWebSearch: a search failure now reads as a real error', () => {
+ it('a provider error is marked failed (starts with "Error:")', async () => {
+ backendCall.mockResolvedValue({ error: 'All search tiers failed' })
+ const out = await registry.execute('web_search', { query: 'tea history' }) as string
+ expect(isMarkedAsFailed(out)).toBe(true)
+ expect(out).toContain('All search tiers failed')
+ })
+
+ it('Gegenprobe: real results are NOT marked failed', async () => {
+ backendCall.mockResolvedValue({ results: [{ title: 't', url: 'https://x', snippet: 's' }] })
+ const out = await registry.execute('web_search', { query: 'tea history' }) as string
+ expect(isMarkedAsFailed(out)).toBe(false)
+ })
+})
+
+describe('executeWebFetch: a bad response now reads as a real error', () => {
+ it('a non-2xx status is marked failed', async () => {
+ backendCall.mockResolvedValue({ url: 'https://x', status: 404, contentType: 'text/html', title: 'Not Found', text: 'nope', truncated: false })
+ const out = await registry.execute('web_fetch', { url: 'https://x' }) as string
+ expect(isMarkedAsFailed(out)).toBe(true)
+ expect(out).toContain('404')
+ })
+
+ it('an empty body is marked failed even with a 200 status', async () => {
+ backendCall.mockResolvedValue({ url: 'https://x', status: 200, contentType: 'text/html', title: '', text: '', truncated: false })
+ const out = await registry.execute('web_fetch', { url: 'https://x' }) as string
+ expect(isMarkedAsFailed(out)).toBe(true)
+ })
+
+ it('Gegenprobe: a real 200 with a body is NOT marked failed', async () => {
+ backendCall.mockResolvedValue({ url: 'https://x', status: 200, contentType: 'text/html', title: 'Tea', text: 'The history of tea spans centuries.', truncated: false })
+ const out = await registry.execute('web_fetch', { url: 'https://x' }) as string
+ expect(isMarkedAsFailed(out)).toBe(false)
+ expect(out).toContain('The history of tea spans centuries.')
+ })
+})
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index 011c3a09..8e73271d 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -11,7 +11,7 @@ import { backendCall, fetchExternal } from '../backend'
import { getActiveChatId, getActiveConversationId, getActiveWorkspace, isChatArtifactMode, captureChatArtifact, isReadOnlyShellTurn } from '../agent-context'
import type { AgentRunContext } from '../agent-context'
import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'
-import { WorkflowEngine, buildWorkflowApprovalGate, describeWorkflowCompletion } from '../../lib/workflow-engine'
+import { WorkflowEngine, buildWorkflowApprovalGate, describeWorkflowCompletion, describeWorkflowStepFailure } from '../../lib/workflow-engine'
import type { StepResult } from '../../types/agent-workflows'
import { DELEGATE_TASK_TOOL_DEF, buildDelegateExecutor } from '../agents/sub-agent'
import {
@@ -515,7 +515,13 @@ async function executeWebSearch(args: ToolArgs): Promise<string> {
}
if (typeof data.error === 'string' && data.error) {
const extra = typeof data.providerError === 'string' && data.providerError ? ` (${data.providerError})` : ''
- return `Web search failed: ${data.error}${extra}`
+ // Auflage 2.1 (lu-301/bau/review-offload2.md): this text used to read
+ // "Web search failed: ..." without the "Error:" prefix `executeToolStep`
+ // checks for, so a search failure inside a `tool` workflow step counted
+ // as `status: 'completed'` and the run carried on with a failure message
+ // as if it were a real result, exactly the silent, GPU-idle-in-seconds
+ // run the box measured for "Research Topic".
+ return `Error: Web search failed: ${data.error}${extra}`
}
return JSON.stringify(data)
}
@@ -531,12 +537,24 @@ async function executeWebFetch(args: ToolArgs): Promise<string> {
// complaining it "only sees the header" of the page.
try {
const data = await backendCall<WebFetchResult>('web_fetch', { url })
+ // Auflage 2.1 (lu-301/bau/review-offload2.md): every response from the
+ // Rust command used to render as the SAME "Title/URL/Status/..." block
+ // regardless of the actual HTTP status or an empty body, so a 404, a
+ // 403 or a blank page all counted as `status: 'completed'` for
+ // `executeToolStep`'s `startsWith('Error:')` check. A non-2xx status or
+ // an empty body is a failed fetch, not a thin result.
+ if (data.status < 200 || data.status >= 300) {
+ return `Error: web_fetch got HTTP ${data.status} for ${url}${data.title ? ` (${data.title})` : ''}`
+ }
+ if (!data.text) {
+ return `Error: web_fetch got an empty body from ${url} (status ${data.status})`
+ }
const parts: string[] = []
if (data.title) parts.push(`Title: ${data.title}`)
parts.push(`URL: ${data.url}`)
parts.push(`Status: ${data.status}`)
parts.push('')
- parts.push(data.text || '(empty body)')
+ parts.push(data.text)
if (data.truncated) parts.push('\n…(truncated to 24 000 chars)')
return parts.join('\n')
} catch (e) {
@@ -1601,12 +1619,25 @@ async function executeRunWorkflow(args: ToolArgs, run?: AgentRunContext, abort?:
const callbacks = {
onStepStart: () => {},
onStepComplete: () => {},
- onStepError: (_idx: number, error: string) => {
+ onStepError: (idx: number, error: string) => {
hadStepError = true
// The step's own `error` is already the gate's English message
// ("Tool call rejected: ... was not approved.", `gatedApproval` in
- // workflow-engine.ts).
- finalOutput = `Workflow error: ${error}`
+ // workflow-engine.ts) or, since Auflage 2.1 (review-offload2.md), a
+ // tool's own honest failure text (web_search/web_fetch). Named with
+ // its position now, not a bare "Workflow error: ...", so a caller
+ // sees WHERE in a multi-step chain things stopped.
+ //
+ // "Error: " prefix (on top of describeWorkflowStepFailure's own,
+ // chat-facing text): this return value is a TOOL RESULT, read back by
+ // `executeToolStep`'s `startsWith('Error:')` check whenever a workflow
+ // step calls `run_workflow` on ANOTHER workflow (third-degree nesting,
+ // workflow-engine-echte-kennung-bei-drittem-grad.test.ts). Without the
+ // prefix a nested failure read as a completed step one level up, and
+ // 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)}`
},
onWaitingForInput: () => {},
onComplete: (allResults: StepResult[]) => {
diff --git a/src/hooks/__tests__/workflow-trigger-echtes-gate-und-stop.test.ts b/src/hooks/__tests__/workflow-trigger-echtes-gate-und-stop.test.ts
index 44529fb1..18f689de 100644
--- a/src/hooks/__tests__/workflow-trigger-echtes-gate-und-stop.test.ts
+++ b/src/hooks/__tests__/workflow-trigger-echtes-gate-und-stop.test.ts
@@ -135,7 +135,7 @@ describe('Waechter: der Chat-Ausloeser "run workflow <name>" uebergibt ein ECHTE
expect(execSpy.mock.calls.map((c) => c[0])).not.toContain('shell_execute')
const conv = useChatStore.getState().conversations.find((c) => c.id === convId)!
const lastAssistant = [...conv.messages].reverse().find((m) => m.role === 'assistant')!
- expect(lastAssistant.content).toMatch(/Workflow error/)
+ expect(lastAssistant.content).toMatch(/Workflow stopped at step/)
})
})
@@ -263,7 +263,7 @@ describe('Nachtrag 1, bau/review-wfgate.md Runde 3: ein Ablaufname MIT Doppelpun
// Positivkontrolle: "Deploy: staging" wurde erkannt und sein blockiertes
// Werkzeug lief nie, meldet aber den Ablehnungsfehler statt zu haengen.
expect(execSpy.mock.calls.map((c) => c[0])).not.toContain('shell_execute')
- expect(lastAssistant.content).toMatch(/Workflow error/)
+ expect(lastAssistant.content).toMatch(/Workflow stopped at step/)
})
it('Negativkontrolle: ohne den passenden Namen "Deploy: staging" im Store faellt der alte Doppelpunkt-Split wieder zum kuerzeren Namen zurueck', async () => {
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index a31acc63..7cbfe57a 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -57,7 +57,7 @@ import { getProviderIdFromModel } from '../api/providers'
import { markToolsUnsupported } from '../api/tool-capability'
import { extractMemoriesFromPair } from './useMemory'
import { useAgentWorkflowStore } from '../stores/agentWorkflowStore'
-import { WorkflowEngine, describeWorkflowCompletion } from '../lib/workflow-engine'
+import { WorkflowEngine, describeWorkflowCompletion, describeWorkflowStepFailure } from '../lib/workflow-engine'
import type { AgentBlock, AgentToolCall } from '../types/agent-mode'
import { selectRelevantToolsAsync, toolSelectionOpts, ALWAYS_INCLUDE } from '../lib/tool-selection'
import { renderToolRoster, renderToolNames } from '../lib/tool-roster'
@@ -416,19 +416,27 @@ export function useAgentChat() {
// `builtin-tools.ts`'s `run_workflow` tool so the two do not drift.
//
// `hadStepError` mirrors that same shared engine's other caller: a
- // failed step's `onStepError` already posts "Workflow error: ...",
- // and `runSteps` (workflow-engine.ts) still calls `onComplete`
- // right after that break, so without this flag a second message
- // would follow, repeating whatever ran before the failure.
+ // failed step's `onStepError` already posts a message, and `runSteps`
+ // (workflow-engine.ts) still calls `onComplete` right after that
+ // break, so without this flag a second message would follow,
+ // repeating whatever ran before the failure.
+ //
+ // Auflage 2.1 (review-offload2.md): the box's "Research Topic" run
+ // finished "successfully" in seconds with idle GPU because
+ // `executeWebSearch`/`executeWebFetch` returned failure text that did
+ // not start with "Error:", so `executeToolStep` never marked the step
+ // failed. Those tool responses are fixed at the source now
+ // (builtin-tools.ts), and a failure IS reported here with WHERE it
+ // happened, not a bare "Workflow error: ...".
let hadStepError = false
const callbacks: WorkflowEngineCallbacks = {
onStepStart: () => {},
onStepComplete: () => {},
- onStepError: (_i, error) => {
+ onStepError: (i, error) => {
hadStepError = true
if (convId) {
useChatStore.getState().addMessage(convId, {
- id: uuid(), role: 'assistant', content: `Workflow error: ${error}`, timestamp: Date.now(),
+ id: uuid(), role: 'assistant', content: describeWorkflowStepFailure(workflow, i, error), timestamp: Date.now(),
})
}
},
diff --git a/src/lib/__tests__/build-workflow-approval-gate.test.ts b/src/lib/__tests__/build-workflow-approval-gate.test.ts
index b87cb3be..2ab9d109 100644
--- a/src/lib/__tests__/build-workflow-approval-gate.test.ts
+++ b/src/lib/__tests__/build-workflow-approval-gate.test.ts
@@ -213,7 +213,7 @@ describe('Waechter: `run_workflow` (builtin-tools.ts) uebergibt ein ECHTES Gate,
// spy sees its own outer call too); shell_execute must never be among
// the calls the workflow's own step made.
expect(execSpy.mock.calls.map((c) => c[0])).not.toContain('shell_execute')
- expect(output).toMatch(/Workflow error/)
+ expect(output).toMatch(/Workflow stopped at step/)
expect(output).toMatch(/not approved|rejected/i)
})
})
diff --git a/src/lib/__tests__/workflow-completion-message.test.ts b/src/lib/__tests__/workflow-completion-message.test.ts
index 4341d0ef..49f9c937 100644
--- a/src/lib/__tests__/workflow-completion-message.test.ts
+++ b/src/lib/__tests__/workflow-completion-message.test.ts
@@ -5,16 +5,22 @@
* The tester's "run workflow Research Topic: the history of tea" showed only
* a second line, "Saved to memory: Research: the history of tea", and then
* nothing for 5+ minutes with the send button back to idle, read as a hang.
- * Quelltextlage: it was not a hang. `runSteps` (workflow-engine.ts) only
- * reaches `onComplete` after every step has run (or one of them failed, in
- * which case `onStepError` already posted "Workflow error: ..." first), and
- * the built-in "Research Topic" workflow ends in a `memory_save` step whose
- * own output is, by construction, never empty ("Saved to memory: ${title}",
- * `executeMemorySaveStep`). The old `onComplete` in BOTH callers
- * (`useAgentChat.ts`'s chat trigger and `builtin-tools.ts`'s `run_workflow`
- * tool) picked `results.filter(r => r.output).pop()`, the LAST step with
- * any output, which for a workflow ending in `memory_save` is ALWAYS that
- * receipt, never the actual content a `prompt` step produced.
+ * Quelltextlage: it was not a hang for a run where every step genuinely
+ * succeeded. `runSteps` (workflow-engine.ts) only reaches `onComplete` after
+ * every step has run, and the built-in "Research Topic" workflow ends in a
+ * `memory_save` step whose own output is, by construction, never empty
+ * ("Saved to memory: ${title}", `executeMemorySaveStep`). The old
+ * `onComplete` in BOTH callers (`useAgentChat.ts`'s chat trigger and
+ * `builtin-tools.ts`'s `run_workflow` tool) picked
+ * `results.filter(r => r.output).pop()`, the LAST step with any output,
+ * which for a workflow ending in `memory_save` is ALWAYS that receipt,
+ * never the actual content a `prompt` step produced.
+ *
+ * A run that stops on a genuine step failure (a broken web search, an empty
+ * model answer) is a SEPARATE concern, covered in
+ * workflow-stops-honestly-on-tool-failure.test.ts and
+ * web-tools-fail-honestly.test.ts (review-offload2.md Auflage 2.1): this
+ * file only covers the "everything genuinely worked" completion message.
*
* This test drives the REAL `WorkflowEngine`, not a copy: a `prompt` step
* (real `chatStream` inference, mocked only at the provider boundary, same
@@ -150,12 +156,4 @@ describe('describeWorkflowCompletion: the real content wins over a trailing memo
expect(message).toContain('Saved to memory: Research: tea')
})
- it('a failed step is named honestly in the fallback when nothing else produced content', () => {
- const workflow = workflowOf([{ id: 'x', type: 'tool', label: 'x', toolName: 'shell_execute' }])
- const results = [
- { stepId: 'x', status: 'failed' as const, output: '', startedAt: 0, completedAt: 1, error: 'not approved' },
- ]
- const message = describeWorkflowCompletion(workflow, results)
- expect(message).toContain('the last one failed: not approved')
- })
})
diff --git a/src/lib/__tests__/workflow-engine-echte-kennung-bei-drittem-grad.test.ts b/src/lib/__tests__/workflow-engine-echte-kennung-bei-drittem-grad.test.ts
index 3d9943c3..3875f88d 100644
--- a/src/lib/__tests__/workflow-engine-echte-kennung-bei-drittem-grad.test.ts
+++ b/src/lib/__tests__/workflow-engine-echte-kennung-bei-drittem-grad.test.ts
@@ -98,7 +98,7 @@ describe('dritter Verschachtelungsgrad reicht die ECHTE Unterhaltung durch, nich
dequeueApproval('real-conv-2')?.resolve(false)
const output = await outputPromise
- expect(output).toMatch(/Workflow error/)
+ expect(output).toMatch(/Workflow stopped at step/)
expect(output).toMatch(/not approved|rejected/i)
})
})
diff --git a/src/lib/__tests__/workflow-stops-honestly-on-tool-failure.test.ts b/src/lib/__tests__/workflow-stops-honestly-on-tool-failure.test.ts
new file mode 100644
index 00000000..5f6a67fc
--- /dev/null
+++ b/src/lib/__tests__/workflow-stops-honestly-on-tool-failure.test.ts
@@ -0,0 +1,205 @@
+/**
+ * B1-2 (lu-301/bau/review-offload2.md, Auflage 2.1): the reviewer's actual
+ * explanation for the box's "run workflow Research Topic: the history of
+ * tea" finishing in seconds with idle GPU and only a memory_save receipt to
+ * show. `executeWebSearch`/`executeWebFetch` (builtin-tools.ts) used to
+ * return failure text that did not start with "Error:", so `executeToolStep`
+ * (workflow-engine.ts) never marked the step `status: 'failed'` and the
+ * chain ran on to `memory_save` on a failure-shaped string as if it were a
+ * real search result. Commit c3e4bf0c fixed the completion MESSAGE without
+ * fixing this, which the reviewer called "a LOUDER false statement than
+ * before" ("Workflow complete (6/6 steps)." over a run that never really
+ * worked).
+ *
+ * This drives the REAL `WorkflowEngine` over a workflow shaped exactly like
+ * the built-in "Research Topic" (tool -> prompt -> tool -> prompt ->
+ * memory_save), with `backendCall('web_search', ...)` mocked to answer the
+ * way a bad search provider key does: `{ error: '...' }`. Only the provider
+ * boundary (`resolveToolCallingStrategy`) and the Tauri bridge
+ * (`backendCall`) are mocked; `executeWebSearch` and `executeToolStep` run
+ * for real.
+ *
+ * Run: npx vitest run src/lib/__tests__/workflow-stops-honestly-on-tool-failure.test.ts
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+
+const backendCall = vi.fn(async (..._args: unknown[]) => ({}))
+
+vi.mock('../agent-strategy', () => ({
+ resolveToolCallingStrategy: vi.fn(),
+}))
+vi.mock('../../api/backend', async () => {
+ const actual = await vi.importActual<typeof import('../../api/backend')>('../../api/backend')
+ return { ...actual, backendCall: (...a: unknown[]) => backendCall(...a) }
+})
+
+import { WorkflowEngine, describeWorkflowStepFailure, describeWorkflowCompletion } from '../workflow-engine'
+import { APPROVE_ALL } from '../../api/agents/tool-executor'
+import { toolRegistry, registerBuiltinTools } from '../../api/mcp'
+import { useModelStore } from '../../stores/modelStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import { __resetRunLanesForTests } from '../run-lanes'
+import { resolveToolCallingStrategy } from '../agent-strategy'
+import type { AgentWorkflow, WorkflowStep, WorkflowEngineCallbacks, StepResult } from '../../types/agent-workflows'
+
+const CLOUD_MODEL = 'anthropic::claude'
+
+function researchTopicShaped(): AgentWorkflow {
+ const steps: WorkflowStep[] = [
+ { id: 'search', type: 'tool', label: 'Search the web', toolName: 'web_search', toolArgTemplates: { query: '{{user_input}}' } },
+ { id: 'pick', type: 'prompt', label: 'Pick best URL', prompt: 'pick a url', allowedTools: [] },
+ { id: 'fetch', type: 'tool', label: 'Fetch page content', toolName: 'web_fetch', toolArgTemplates: { url: '{{last_output}}' } },
+ { id: 'summarize', type: 'prompt', label: 'Summarize findings', prompt: 'summarize', allowedTools: [] },
+ { id: 'save', type: 'memory_save', label: 'Save to memory', memorySave: { type: 'reference', titleTemplate: 'Research: {{user_input}}', contentTemplate: '{{last_output}}', tags: [] } },
+ ]
+ return { id: 'wf', name: 'Research Topic', description: '', icon: 'Search', steps, variables: {}, isBuiltIn: true, createdAt: 0, updatedAt: 0 }
+}
+
+/** Production's own callback shape (useAgentChat.ts / builtin-tools.ts):
+ * onStepError posts the honest per-step message and sets `hadStepError`;
+ * onComplete bails out when it fires, so at most ONE final message ever
+ * reaches the user. */
+function productionShapedCallbacks(workflow: AgentWorkflow) {
+ let hadStepError = false
+ const messages: string[] = []
+ const callbacks: WorkflowEngineCallbacks = {
+ onStepStart: () => {},
+ onStepComplete: () => {},
+ onStepError: (i, error) => {
+ hadStepError = true
+ messages.push(describeWorkflowStepFailure(workflow, i, error))
+ },
+ onWaitingForInput: () => {},
+ onComplete: (allResults: StepResult[]) => {
+ if (hadStepError) return
+ messages.push(describeWorkflowCompletion(workflow, allResults))
+ },
+ onError: (err) => { messages.push(`Workflow error: ${err}`) },
+ }
+ return { callbacks, messages }
+}
+
+beforeEach(() => {
+ __resetRunLanesForTests()
+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
+ useModelStore.setState({ activeModel: CLOUD_MODEL })
+ backendCall.mockClear()
+ registerBuiltinTools(toolRegistry)
+ vi.mocked(resolveToolCallingStrategy).mockResolvedValue({
+ strategy: 'native',
+ modelToUse: 'claude',
+ modelId: 'claude',
+ providerId: 'anthropic',
+ // A prompt step should never be reached once the search step fails and
+ // the run breaks; this stub only exists so the test fails loudly (a
+ // thrown error, not a false pass) if that assumption is ever wrong.
+ provider: {
+ chatStream: async function* () { yield { content: 'unexpected: a prompt step ran', done: true } },
+ chatWithTools: vi.fn(),
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ } as any,
+ })
+})
+
+describe('a broken web search stops the run honestly instead of a false "complete"', () => {
+ it('the search step is marked failed, the run stops at step 1, and later steps never run', 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 workflow = researchTopicShaped()
+ const { callbacks, messages } = productionShapedCallbacks(workflow)
+ const engine = new WorkflowEngine(workflow, 'conv-a', callbacks, APPROVE_ALL, { user_input: 'the history of tea' })
+ const results = await engine.run()
+
+ // Only the search step ran; runSteps breaks on its failure.
+ expect(results).toHaveLength(1)
+ expect(results[0].status).toBe('failed')
+
+ // Exactly one message reached the user, and it is the honest one.
+ expect(messages).toHaveLength(1)
+ expect(messages[0]).toBe('Workflow stopped at step 1 of 5: Error: Web search failed: All search tiers failed')
+
+ // The false positive this fixes: it must NOT claim completion.
+ expect(messages[0]).not.toContain('Workflow complete')
+ expect(messages[0]).not.toContain('Saved to memory')
+ })
+
+ it('Gegenprobe: a working search lets the run reach memory_save and report completion', 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' }] }
+ if (cmd === 'web_fetch') return { url: 'https://tea.example', status: 200, contentType: 'text/html', title: 'Tea', text: 'Tea has a long history.', truncated: false }
+ throw new Error(`unexpected backendCall: ${cmd}`)
+ })
+ vi.mocked(resolveToolCallingStrategy).mockResolvedValue({
+ strategy: 'native',
+ modelToUse: 'claude',
+ modelId: 'claude',
+ providerId: 'anthropic',
+ provider: {
+ chatStream: async function* () { yield { content: 'Tea has a long and storied history.', done: true } },
+ chatWithTools: vi.fn(),
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ } as any,
+ })
+ const workflow = researchTopicShaped()
+ const { callbacks, messages } = productionShapedCallbacks(workflow)
+ const engine = new WorkflowEngine(workflow, 'conv-b', callbacks, APPROVE_ALL, { user_input: 'the history of tea' })
+ const results = await engine.run()
+
+ expect(results).toHaveLength(5)
+ expect(results.every((r) => r.status === 'completed')).toBe(true)
+ expect(messages).toHaveLength(1)
+ expect(messages[0]).toContain('Workflow complete (5/5 steps).')
+ expect(messages[0]).toContain('Tea has a long and storied history.')
+ })
+})
+
+describe('a prompt step with no output is a failed step, not a completed one with nothing to say', () => {
+ it('an empty model answer stops the run and is named honestly', async () => {
+ vi.mocked(resolveToolCallingStrategy).mockResolvedValue({
+ strategy: 'native',
+ modelToUse: 'claude',
+ modelId: 'claude',
+ providerId: 'anthropic',
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ provider: { chatStream: async function* () { yield { content: '', done: true } }, chatWithTools: vi.fn() } as any,
+ })
+ const workflow: AgentWorkflow = {
+ id: 'wf2', name: 'test', description: '', icon: 'Zap',
+ steps: [{ id: 'p', type: 'prompt', label: 'p', prompt: 'say something', allowedTools: [] }],
+ variables: {}, isBuiltIn: false, createdAt: 0, updatedAt: 0,
+ }
+ const { callbacks, messages } = productionShapedCallbacks(workflow)
+ const engine = new WorkflowEngine(workflow, 'conv-c', callbacks, APPROVE_ALL)
+ const results = await engine.run()
+
+ expect(results).toHaveLength(1)
+ expect(results[0].status).toBe('failed')
+ expect(messages).toEqual(['Workflow stopped at step 1 of 1: The model returned no content for this prompt step.'])
+ })
+
+ it('Gegenprobe: a non-empty model answer completes normally', async () => {
+ vi.mocked(resolveToolCallingStrategy).mockResolvedValue({
+ strategy: 'native',
+ modelToUse: 'claude',
+ modelId: 'claude',
+ providerId: 'anthropic',
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ provider: { chatStream: async function* () { yield { content: 'a real answer', done: true } }, chatWithTools: vi.fn() } as any,
+ })
+ const workflow: AgentWorkflow = {
+ id: 'wf3', name: 'test', description: '', icon: 'Zap',
+ steps: [{ id: 'p', type: 'prompt', label: 'p', prompt: 'say something', allowedTools: [] }],
+ variables: {}, isBuiltIn: false, createdAt: 0, updatedAt: 0,
+ }
+ const { callbacks, messages } = productionShapedCallbacks(workflow)
+ const engine = new WorkflowEngine(workflow, 'conv-d', callbacks, APPROVE_ALL)
+ const results = await engine.run()
+
+ expect(results[0].status).toBe('completed')
+ expect(messages[0]).toContain('a real answer')
+ })
+})
diff --git a/src/lib/workflow-engine.ts b/src/lib/workflow-engine.ts
index 0447e758..c5dbd778 100644
--- a/src/lib/workflow-engine.ts
+++ b/src/lib/workflow-engine.ts
@@ -171,7 +171,10 @@ function evaluateCondition(
// ── Completion Message ──────────────────────────────────────────
/**
- * B1 (lu-301/bau/klaerung-n7.md): what a finished run tells the user.
+ * B1 (lu-301/bau/klaerung-n7.md): what a SUCCESSFULLY finished run tells the
+ * user (a run that stopped on a step failure never reaches this function;
+ * see `describeWorkflowStepFailure` below, which is what `onStepError` now
+ * shows instead).
*
* Both callers of this engine (`useAgentChat.ts`'s "run workflow" chat
* trigger and `builtin-tools.ts`'s `run_workflow` tool) used to pick the
@@ -191,8 +194,12 @@ function evaluateCondition(
* - The content is the LAST step with non-empty output that is not a
* memory_save receipt: a receipt is shown ALONGSIDE the content, never
* INSTEAD of it.
- * - No step produced any (non-receipt) output, or the run stopped on a
- * failure: say that plainly instead of ending on a bare header.
+ * - No step produced any (non-receipt) output: say that plainly instead
+ * of ending on a bare header. This branch used to also cover a FAILED
+ * step (review-offload2.md Auflage 2.4 found that branch unreachable in
+ * production, since both callers already bail out of `onComplete`
+ * before this runs whenever a step failed; removed rather than kept
+ * alive only by its own test).
*/
export function describeWorkflowCompletion(workflow: AgentWorkflow, results: StepResult[]): string {
const total = workflow.steps.length
@@ -212,13 +219,7 @@ export function describeWorkflowCompletion(workflow: AgentWorkflow, results: Ste
if (content) {
lines.push('', content.output)
} else {
- const failed = results.find((r) => r.status === 'failed')
- lines.push(
- '',
- failed
- ? `No step produced a result to show (the last one failed: ${failed.error || 'unknown error'}).`
- : 'No step produced any output to show.',
- )
+ lines.push('', 'No step produced any output to show.')
}
if (savedNote && savedNote !== content) {
lines.push('', savedNote.output)
@@ -226,6 +227,19 @@ export function describeWorkflowCompletion(workflow: AgentWorkflow, results: Ste
return lines.join('\n')
}
+/**
+ * B1 followup (Auflage 2.1, lu-301/bau/review-offload2.md): what a run that
+ * STOPPED ON A FAILURE tells the user, said honestly with its position
+ * ("Workflow stopped at step 2 of 6: ...") instead of the bare
+ * "Workflow error: ..." both callers used to show, which read identically
+ * whether step 1 or step 5 of a long chain had failed. `stepIndex` is
+ * 0-based, as `onStepError` receives it; the message is 1-based, matching
+ * how `describeWorkflowCompletion`'s own header counts steps.
+ */
+export function describeWorkflowStepFailure(workflow: AgentWorkflow, stepIndex: number, error: string): string {
+ return `Workflow stopped at step ${stepIndex + 1} of ${workflow.steps.length}: ${error}`
+}
+
// ── Engine ────────────────────────────────────────────────────
export class WorkflowEngine {
@@ -742,6 +756,23 @@ export class WorkflowEngine {
// and rides into every later step's prompt.
output = settleThinking(output, '', false).content
+ // Auflage 2.1 (lu-301/bau/review-offload2.md): a stream that ends with
+ // no content (thinking stripped away, or the model answered nothing)
+ // used to be `status: 'completed'` with `output: ''`. `runSteps` only
+ // carries `last_output` forward on a non-empty output, so the NEXT step
+ // silently kept working off whatever the step BEFORE this one produced,
+ // with nothing to say a step had come up empty in between.
+ if (!output.trim()) {
+ return {
+ stepId: step.id,
+ status: 'failed',
+ output: '',
+ startedAt,
+ completedAt: Date.now(),
+ error: 'The model returned no content for this prompt step.',
+ }
+ }
+
return {
stepId: step.id,
status: 'completed',