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): show a workflow's real result instead of a memory_save receipt

purple50ad23caa3bf
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index acb01a71..011c3a09 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 } from '../../lib/workflow-engine'
+import { WorkflowEngine, buildWorkflowApprovalGate, describeWorkflowCompletion } from '../../lib/workflow-engine'
import type { StepResult } from '../../types/agent-workflows'
import { DELEGATE_TASK_TOOL_DEF, buildDelegateExecutor } from '../agents/sub-agent'
import {
@@ -1583,7 +1583,6 @@ async function executeRunWorkflow(args: ToolArgs, run?: AgentRunContext, abort?:
return `Error: Workflow "${workflow.name}" starts by asking "${firstAsk.userInputPrompt || 'for input'}", and nothing can answer that while it runs. Call run_workflow again with an "input" argument that answers it.`
}
- const results: StepResult[] = []
let finalOutput = ''
// Auflage 4, bau/review-wfgate.md: a no-op `onStepError` (the old body)
// left `finalOutput` empty on a rejected approval, so `run_workflow`
@@ -1591,15 +1590,17 @@ async function executeRunWorkflow(args: ToolArgs, run?: AgentRunContext, abort?:
// again. `runSteps` (workflow-engine.ts) calls `onStepError` and BREAKS
// the step loop on a failure, but still calls `onComplete` afterward (it
// is not the same as `onError`, which fires only on a thrown exception),
- // and that handler's own fallback ("Workflow completed with no output.")
- // would otherwise silently overwrite the error message set here, since a
- // failed step's own `output` is '' and gets filtered out by
- // `results.filter(r => r.output)`. `hadStepError` keeps `onComplete` from
- // clobbering it.
+ // so without `hadStepError` that handler would overwrite the error
+ // message set here with whatever ran before the failure. B1
+ // (lu-301/bau/klaerung-n7.md): the message itself now comes from
+ // `describeWorkflowCompletion` (workflow-engine.ts), shared with
+ // `useAgentChat.ts`'s "run workflow" chat trigger; the old
+ // `results.filter(r => r.output).pop()` here always picked a trailing
+ // `memory_save` step's own receipt over the actual content.
let hadStepError = false
const callbacks = {
onStepStart: () => {},
- onStepComplete: (_idx: number, result: StepResult) => { results.push(result) },
+ onStepComplete: () => {},
onStepError: (_idx: number, error: string) => {
hadStepError = true
// The step's own `error` is already the gate's English message
@@ -1608,10 +1609,9 @@ async function executeRunWorkflow(args: ToolArgs, run?: AgentRunContext, abort?:
finalOutput = `Workflow error: ${error}`
},
onWaitingForInput: () => {},
- onComplete: () => {
+ onComplete: (allResults: StepResult[]) => {
if (hadStepError) return
- const lastOutput = results.filter(r => r.output).pop()
- finalOutput = lastOutput?.output || 'Workflow completed with no output.'
+ finalOutput = describeWorkflowCompletion(workflow, allResults)
},
onError: (error: string) => { finalOutput = `Workflow error: ${error}` },
}
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 8f398bb4..a31acc63 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 } from '../lib/workflow-engine'
+import { WorkflowEngine, describeWorkflowCompletion } 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'
@@ -85,7 +85,7 @@ import { toolCallCapMs, raceWithToolTimeout, SHELL_EXECUTE_DEFAULT_TIMEOUT_MS }
import { AgentLoopGuard } from '../lib/agent-loop-guard'
import { budgetFromSettings } from '../api/agents/budget'
import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'
-import type { StepResult, WorkflowEngineCallbacks } from '../types/agent-workflows'
+import type { WorkflowEngineCallbacks } from '../types/agent-workflows'
import { executeParallel, applyResultToToolCall, type ExecutionRequest } from '../api/agents/tool-executor'
import { useToolAuditStore } from '../stores/toolAuditStore'
import { makeInTurnCacheLookup } from '../api/agents/in-turn-cache'
@@ -405,17 +405,27 @@ export function useAgentChat() {
id: uuid(), role: 'assistant', content: `Running workflow: **${workflow.name}**...`, timestamp: Date.now(),
})
- const results: StepResult[] = []
+ // B1 (lu-301/bau/klaerung-n7.md): a workflow that ends in
+ // `memory_save` (every built-in one does) used to show only that
+ // step's own receipt ("Saved to memory: ...") at the end, because
+ // the old `onComplete` picked `results.filter(r => r.output).pop()`,
+ // the LAST step with any output, which memory_save always is.
+ // That buried the actual content (a `prompt` step's summary) behind
+ // a cryptic one-liner indistinguishable from a hang. Fix lives in
+ // `describeWorkflowCompletion` (workflow-engine.ts), shared with
+ // `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.
+ let hadStepError = false
const callbacks: WorkflowEngineCallbacks = {
onStepStart: () => {},
- onStepComplete: (_i, r) => { results.push(r) },
- // Same fix as Auflage 4, bau/review-wfgate.md (builtin-tools.ts's
- // `executeRunWorkflow`): `runSteps` calls `onStepError` and then
- // breaks WITHOUT calling `onComplete` or `onError`, so a no-op
- // here left a rejected approval's chat turn with no message at
- // all, the same silent-failure shape the review flagged for the
- // `run_workflow` tool's return value.
+ onStepComplete: () => {},
onStepError: (_i, error) => {
+ hadStepError = true
if (convId) {
useChatStore.getState().addMessage(convId, {
id: uuid(), role: 'assistant', content: `Workflow error: ${error}`, timestamp: Date.now(),
@@ -423,13 +433,11 @@ export function useAgentChat() {
}
},
onWaitingForInput: () => {},
- onComplete: () => {
- const lastOutput = results.filter(r => r.output).pop()
- if (lastOutput && convId) {
- useChatStore.getState().addMessage(convId, {
- id: uuid(), role: 'assistant', content: lastOutput.output, timestamp: Date.now(),
- })
- }
+ onComplete: (allResults) => {
+ if (hadStepError || !convId) return
+ useChatStore.getState().addMessage(convId, {
+ id: uuid(), role: 'assistant', content: describeWorkflowCompletion(workflow, allResults), timestamp: Date.now(),
+ })
},
onError: (err) => {
if (convId) {
diff --git a/src/lib/__tests__/workflow-completion-message.test.ts b/src/lib/__tests__/workflow-completion-message.test.ts
new file mode 100644
index 00000000..4341d0ef
--- /dev/null
+++ b/src/lib/__tests__/workflow-completion-message.test.ts
@@ -0,0 +1,161 @@
+/**
+ * B1 (lu-301/bau/klaerung-n7.md): what a workflow's LAST chat message says
+ * when it finishes.
+ *
+ * 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.
+ *
+ * This test drives the REAL `WorkflowEngine`, not a copy: a `prompt` step
+ * (real `chatStream` inference, mocked only at the provider boundary, same
+ * pattern as workflow-engine-approval-gate.test.ts) followed by a
+ * `memory_save` step, exactly the shape "Research Topic" ends in. It reads
+ * the result the same way both production callers now do: through
+ * `describeWorkflowCompletion`.
+ *
+ * Lauf: npx vitest run src/lib/__tests__/workflow-completion-message.test.ts
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+
+vi.mock('../agent-strategy', () => ({
+ resolveToolCallingStrategy: vi.fn(),
+}))
+
+import { WorkflowEngine, describeWorkflowCompletion } from '../workflow-engine'
+import { APPROVE_ALL } from '../../api/agents/tool-executor'
+import { useModelStore } from '../../stores/modelStore'
+import { useMemoryStore } from '../../stores/memoryStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import { __resetRunLanesForTests } from '../run-lanes'
+import { resolveToolCallingStrategy } from '../agent-strategy'
+import type { AgentWorkflow, WorkflowStep, WorkflowEngineCallbacks } from '../../types/agent-workflows'
+
+const CLOUD_MODEL = 'anthropic::claude'
+const REAL_CONTENT = 'the printing press changed everything'
+
+function workflowOf(steps: WorkflowStep[]): AgentWorkflow {
+ return { id: 'wf', name: 'test', description: '', icon: 'Zap', steps, variables: {}, isBuiltIn: false, createdAt: 0, updatedAt: 0 }
+}
+
+/** A single-chunk stream, same shape `executePromptStep`'s `for await`
+ * consumes off `provider.chatStream`. Reads the canned answer back out of
+ * the prompt itself (`promptStep` below writes it as `respond:<answer>`),
+ * so two prompt steps in one run can answer differently. */
+async function* respondToPrompt(_model: string, messages: Array<{ content: string }>) {
+ const sent = messages[messages.length - 1]?.content || ''
+ const answer = sent.startsWith('respond:') ? sent.slice('respond:'.length) : sent
+ yield { content: answer, done: true }
+}
+
+function promptStep(id: string, content: string): WorkflowStep {
+ // The prompt text itself carries which canned answer this step gets;
+ // `respondToPrompt` below reads it back out of the messages `chatStream`
+ // receives, so two prompt steps in the same run can answer differently.
+ return { id, type: 'prompt', label: id, prompt: `respond:${content}`, allowedTools: [] }
+}
+
+function memorySaveStep(id: string, titleTemplate = 'note'): WorkflowStep {
+ return {
+ id, type: 'memory_save', label: id,
+ memorySave: { type: 'reference', titleTemplate, contentTemplate: '{{last_output}}', tags: [] },
+ }
+}
+
+beforeEach(() => {
+ __resetRunLanesForTests()
+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
+ useModelStore.setState({ activeModel: CLOUD_MODEL })
+ vi.spyOn(useMemoryStore.getState(), 'addMemory').mockImplementation(() => 'mem-id')
+ // Every prompt step in these tests answers with REAL_CONTENT, good enough
+ // for a fixed-content stub, the point here is the SELECTION logic after
+ // the run, not varying what the model says.
+ vi.mocked(resolveToolCallingStrategy).mockResolvedValue({
+ strategy: 'native',
+ modelToUse: 'claude',
+ modelId: 'claude',
+ providerId: 'anthropic',
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ provider: { chatStream: respondToPrompt, chatWithTools: vi.fn() } as any,
+ })
+})
+
+function callbacksCollectingAllResults() {
+ const collected: { onComplete?: Parameters<WorkflowEngineCallbacks['onComplete']>[0] } = {}
+ const errors: string[] = []
+ const callbacks: WorkflowEngineCallbacks = {
+ onStepStart: () => {},
+ onStepComplete: () => {},
+ onStepError: (_i, e) => errors.push(e),
+ onWaitingForInput: () => {},
+ onComplete: (results) => { collected.onComplete = results },
+ onError: (e) => errors.push(e),
+ }
+ return { callbacks, collected, errors }
+}
+
+describe('describeWorkflowCompletion: the real content wins over a trailing memory_save receipt', () => {
+ it('a real WorkflowEngine.run() ending in memory_save: the chat message shows the prompt step\'s content, not just the receipt', async () => {
+ const workflow = workflowOf([promptStep('summary', REAL_CONTENT), memorySaveStep('save', 'Research: tea')])
+ const { callbacks, collected, errors } = callbacksCollectingAllResults()
+ const engine = new WorkflowEngine(workflow, 'conv-a', callbacks, APPROVE_ALL)
+ await engine.run()
+
+ expect(errors).toEqual([])
+ expect(collected.onComplete).toBeDefined()
+ const message = describeWorkflowCompletion(workflow, collected.onComplete!)
+
+ // The actual bug: before the fix this was ONLY "Saved to memory: ...".
+ expect(message).toContain(REAL_CONTENT)
+ expect(message).toContain('Workflow complete (2/2 steps).')
+ // The receipt is still shown, alongside the content, not instead of it.
+ expect(message).toContain('Saved to memory: Research: tea')
+ // And the content must come BEFORE the receipt, so a reader who only
+ // sees the first line still sees the actual answer.
+ expect(message.indexOf(REAL_CONTENT)).toBeLessThan(message.indexOf('Saved to memory:'))
+ })
+
+ it('Gegenprobe: a workflow with NO memory_save step keeps showing the last step\'s content unchanged', async () => {
+ const workflow = workflowOf([promptStep('first', 'ignored, not the last step'), promptStep('last', REAL_CONTENT)])
+ const { callbacks, collected, errors } = callbacksCollectingAllResults()
+ const engine = new WorkflowEngine(workflow, 'conv-b', callbacks, APPROVE_ALL)
+ await engine.run()
+
+ expect(errors).toEqual([])
+ const message = describeWorkflowCompletion(workflow, collected.onComplete!)
+ expect(message).toContain(REAL_CONTENT)
+ expect(message).not.toContain('ignored, not the last step')
+ expect(message).toContain('Workflow complete (2/2 steps).')
+ })
+
+ it('a step that produced no output at all is named honestly instead of ending on a bare header', () => {
+ const workflow = workflowOf([memorySaveStep('save', 'Research: tea')])
+ // Simulate a memory_save-only run where the receipt itself is excluded
+ // from "content" by design; the message must say so, not go silent.
+ const results = [
+ { stepId: 'save', status: 'completed' as const, output: 'Saved to memory: Research: tea', startedAt: 0, completedAt: 1 },
+ ]
+ const message = describeWorkflowCompletion(workflow, results)
+ expect(message).toContain('Workflow complete (1/1 step).')
+ expect(message).toContain('No step produced any output to show.')
+ 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/workflow-engine.ts b/src/lib/workflow-engine.ts
index 3dd27fd7..0447e758 100644
--- a/src/lib/workflow-engine.ts
+++ b/src/lib/workflow-engine.ts
@@ -168,6 +168,64 @@ function evaluateCondition(
}
}
+// ── Completion Message ──────────────────────────────────────────
+
+/**
+ * B1 (lu-301/bau/klaerung-n7.md): what a finished run tells the user.
+ *
+ * Both callers of this engine (`useAgentChat.ts`'s "run workflow" chat
+ * trigger and `builtin-tools.ts`'s `run_workflow` tool) used to pick the
+ * final message the same, slightly wrong way: `results.filter(r =>
+ * r.output).pop()`, the LAST step with any output at all. For every
+ * workflow that ends in `memory_save` (the built-in "Research Topic" among
+ * them) that step's own receipt (`executeMemorySaveStep` below, "Saved to
+ * memory: ...") is never empty by construction, so it always won `.pop()`
+ * and buried the actual content, a `prompt` step's summary, the thing the
+ * user sent the workflow to produce. A user who does not read the whole
+ * chat history cannot tell that cryptic one-liner from a hang.
+ *
+ * This is the one place both callers now read the result from, instead of
+ * each keeping its own near-identical copy. Rules:
+ * - Lead with a plain header naming how many of the workflow's steps ran,
+ * so "finished, short answer" never again looks like "stuck after one".
+ * - 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.
+ */
+export function describeWorkflowCompletion(workflow: AgentWorkflow, results: StepResult[]): string {
+ const total = workflow.steps.length
+ const ran = results.length
+ const header = `Workflow complete (${ran}/${total} step${total === 1 ? '' : 's'}).`
+
+ const stepTypeOf = (stepId: string) => workflow.steps.find((s) => s.id === stepId)?.type
+
+ // Most recent first, so a later step's output wins over an earlier one's,
+ // same as the old `.pop()` did, only now memory_save is excluded from
+ // this pick rather than being the one type of step it always found first.
+ const reversed = [...results].reverse()
+ const content = reversed.find((r) => r.output && stepTypeOf(r.stepId) !== 'memory_save')
+ const savedNote = reversed.find((r) => r.output && stepTypeOf(r.stepId) === 'memory_save')
+
+ const lines = [header]
+ 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.',
+ )
+ }
+ if (savedNote && savedNote !== content) {
+ lines.push('', savedNote.output)
+ }
+ return lines.join('\n')
+}
+
// ── Engine ────────────────────────────────────────────────────
export class WorkflowEngine {