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(workflow): Fortschritt statt drei Punkten beim Chat-Ausloeser "run workflow"
purple1a08d16cae6e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex eafaa1d6..8883eaff 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -197,6 +197,14 @@ installs stop losing environment variables to it.ComfyUI code back to the version it had before if you cancel partwaythrough; Python packages already installed during that attempt are notundone.+- **Running a workflow from chat ("run workflow ...") now shows its own+ progress**, clickable and expandable exactly like a tool call: every step+ listed as waiting, running, done or failed, each finished step's result, and+ the currently running step's answer streaming in live. Before this it showed+ no more than three static dots for the whole run, sometimes several minutes,+ with no way to tell it was still working. A model step also no longer+ reasons all the way to the end of its context window by default; it now asks+ for the same output limit a normal chat turn asks for.## [3.0.0] - 2026-09-13diff --git a/src/components/chat/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsxindex 40599e2c..5821a412 100644--- a/src/components/chat/ToolCallBlock.tsx+++ b/src/components/chat/ToolCallBlock.tsx@@ -226,9 +226,15 @@ function ToolCallBlockImpl({ toolCall, onApprove, onReject }: Props) {// Default: collapsed (closed)const [open, setOpen] = useState(toolCall.status === 'pending_approval')+ // A workflow-progress step (klein 2, bau/wfprogress.md) carries its own+ // dynamic label ("Step 2 of 6: <name>") as toolName, so it can never match+ // TOOL_ICONS by exact key the way a real tool call does. Same GitBranch+ // face the "run_workflow" tool itself already wears.const ToolIcon = toolCall.toolName === 'shell_execute'? (SHELL_COMMAND_ICONS[shellIconKey(toolCall)] ?? Terminal)- : (TOOL_ICONS[toolCall.toolName] || Terminal)+ : toolCall.toolName.startsWith('Step ')+ ? GitBranch+ : (TOOL_ICONS[toolCall.toolName] || Terminal)const StatusIcon = STATUS_ICONS[toolCall.status]const isRunning = toolCall.status === 'running'const isPending = toolCall.status === 'pending_approval'diff --git a/src/hooks/__tests__/workflow-progress-block.test.ts b/src/hooks/__tests__/workflow-progress-block.test.tsnew file mode 100644index 00000000..336cfa1b--- /dev/null+++ b/src/hooks/__tests__/workflow-progress-block.test.ts@@ -0,0 +1,231 @@+/**+ * @vitest-environment jsdom+ *+ * bau/wfprogress.md: the "run workflow <name>" chat trigger used to add ONE+ * static assistant message ("Running workflow: **X**...") that never changed+ * for the whole run — the only feedback a multi-minute workflow gave was+ * three static dots, unlike every real tool call, which shows a running/+ * working ToolCallBlock. This drives the REAL `useAgentChat` hook (the same+ * one ChatView uses) over real workflows and asserts on the progress+ * message's `agentBlocks`: a single AgentToolCall-shaped block that starts at+ * "waiting" for every step, updates to "running"/"done"/"failed" per step,+ * and ends up clickable/expandable with the full step list — reusing+ * ToolCallBlock, not a new component.+ *+ * Run: npx vitest run src/hooks/__tests__/workflow-progress-block.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { renderHook, act } from '@testing-library/react'++vi.mock('../../api/cloud/supabase', () => ({+ getAccessToken: async () => 'session-token-abc',+}))+vi.mock('../../api/rag', () => ({+ retrieveContext: async () => ({ context: { chunks: [], query: '', documentIds: [] }, scoredChunks: [] }),+ generateEmbeddings: async () => [[0.1, 0.2]],+}))+vi.mock('../../lib/ttsBridge', () => ({ autoSpeak: () => {} }))+vi.mock('../../api/vram-handoff', () => ({ requestGenerationCancel: () => {} }))+vi.mock('../useMemory', () => ({+ useMemory: () => ({ extractAndSave: async () => {} }),+ extractMemoriesFromPair: async () => {},+}))++import { useAgentChat, __activeAgentRunConvIdsForTests } from '../useAgentChat'+import { useChatStore } from '../../stores/chatStore'+import { useModelStore } from '../../stores/modelStore'+import { useSettingsStore } from '../../stores/settingsStore'+import { useProviderStore } from '../../stores/providerStore'+import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'+import { usePermissionStore } from '../../stores/permissionStore'+import { useAgentTaskStore } from '../../stores/agentTaskStore'+import { useAgentLoopStore } from '../../stores/agentLoopStore'+import { useGenerationStore } from '../../stores/generationStore'+import { useTodoStore } from '../../stores/todoStore'+import { useToolAuditStore } from '../../stores/toolAuditStore'+import { DEFAULT_SETTINGS } from '../../lib/constants'+import { __resetRunStopsForTests } from '../../lib/run-stop'+import { __resetRunLanesForTests } from '../../lib/run-lanes'+import { toolRegistry, registerBuiltinTools } from '../../api/mcp'+import { headApproval, resetApprovals } from '../../lib/approval-queue'+import { useMemoryStore } from '../../stores/memoryStore'+import type { AgentToolCall } from '../../types/agent-mode'++const MODEL = 'openai::local-builtin-model'+const tick = () => new Promise((r) => setTimeout(r, 0))++function seed(): string {+ const convId = useChatStore.getState().createConversation(MODEL, '')+ useChatStore.getState().setActiveConversation(convId)+ return convId+}++// Two `memory_save` steps: synchronous and local (no toolRegistry, no+// backend call), same as workflow-engine-branching.test.ts uses to exercise+// the real engine without a Tauri bridge. `shell_execute`/`web_search` would+// need a live backend this test environment does not have; the SUCCESS path+// only needs two steps that genuinely complete, and the progress block does+// not care which step type produced the output.+function twoStepWorkflow() {+ return {+ id: 'wf-progress-two-step',+ name: 'Progress Two Step',+ description: '',+ icon: 'Zap',+ steps: [+ { id: 's1', type: 'memory_save' as const, label: 'First step', memorySave: { type: 'reference' as const, titleTemplate: 'one', contentTemplate: 'first result', tags: [] } },+ { id: 's2', type: 'memory_save' as const, label: 'Second step', memorySave: { type: 'reference' as const, titleTemplate: 'two', contentTemplate: 'second result', tags: [] } },+ ],+ variables: {},+ isBuiltIn: false,+ createdAt: 0,+ updatedAt: 0,+ }+}++function blockedWorkflow() {+ return {+ id: 'wf-progress-blocked',+ name: 'Progress Blocked',+ description: '',+ icon: 'Zap',+ steps: [{ id: 's1', type: 'tool' as const, label: 'Run it', toolName: 'shell_execute', toolArgs: { command: 'echo hi' } }],+ variables: {},+ isBuiltIn: false,+ createdAt: 0,+ updatedAt: 0,+ }+}++/** The progress message is the assistant message right after the user's+ * "run workflow ..." turn, carrying the ONE evolving tool_call block. */+function progressToolCall(convId: string): AgentToolCall {+ const conv = useChatStore.getState().conversations.find((c) => c.id === convId)!+ const progressMsg = conv.messages.find((m) => m.role === 'assistant' && m.content.startsWith('Running workflow:'))!+ const block = progressMsg.agentBlocks!.find((b) => b.phase === 'tool_call')!+ return block.toolCalls![0]+}++beforeEach(() => {+ registerBuiltinTools(toolRegistry)+ __resetRunStopsForTests()+ __resetRunLanesForTests()+ resetApprovals()+ useChatStore.setState({ conversations: [], activeConversationId: null })+ useAgentTaskStore.setState({ byConv: {} })+ useAgentLoopStore.setState({ loops: {} })+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })+ useTodoStore.setState({ byConversation: {}, updatedAt: {} })+ useToolAuditStore.setState({ entries: {} })+ useSettingsStore.setState({+ settings: { ...DEFAULT_SETTINGS, appMode: 'local', cavemanMode: 'off' },+ })+ useProviderStore.setState((s) => ({+ providers: { ...s.providers, openai: { ...s.providers.openai, enabled: true } },+ }))+ useModelStore.setState({ models: [], activeModel: MODEL })+ useAgentWorkflowStore.setState({ workflows: [twoStepWorkflow(), blockedWorkflow()] })+ usePermissionStore.getState().setGlobalPermission('terminal', 'confirm')+ vi.spyOn(useMemoryStore.getState(), 'addMemory').mockImplementation(() => 'mem-id')+})++afterEach(() => {+ usePermissionStore.getState().resetToDefaults()+ vi.restoreAllMocks()+})++describe('Schritt 1 und Schritt n: die Stufenliste wird live aktualisiert', () => {+ it('endet mit BEIDEN Schritten als "done" und einer Zusammenfassung im Titel', async () => {+ const { result } = renderHook(() => useAgentChat())+ const convId = seed()++ await act(async () => {+ await result.current.sendAgentMessage('run workflow Progress Two Step')+ await tick()+ await tick()+ })++ const tc = progressToolCall(convId)+ expect(tc.status).toBe('completed')+ expect(tc.toolName).toBe('Workflow: Progress Two Step (2/2 steps)')+ expect(tc.result).toContain('Step 1 of 2: First step - done')+ expect(tc.result).toContain('Step 2 of 2: Second step - done')+ expect(tc.result).toContain('Saved to memory: one')+ expect(tc.result).toContain('Saved to memory: two')++ // The existing honest completion message is untouched by any of this.+ 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 complete \(2\/2 steps\)\./)+ })++ it('NEGATIVKONTROLLE: ohne den Fix gaebe es gar keinen agentBlocks-Eintrag auf der Fortschrittsnachricht', async () => {+ const { result } = renderHook(() => useAgentChat())+ const convId = seed()++ await act(async () => {+ await result.current.sendAgentMessage('run workflow Progress Two Step')+ await tick()+ await tick()+ })++ const conv = useChatStore.getState().conversations.find((c) => c.id === convId)!+ const progressMsg = conv.messages.find((m) => m.role === 'assistant' && m.content.startsWith('Running workflow:'))!+ // This is exactly what the old code left behind: a message with NO+ // agentBlocks at all, so the chat rendered nothing but its own static+ // "..." text for the whole run. The fix's whole point is that this is+ // no longer true.+ expect(progressMsg.agentBlocks?.length ?? 0).toBeGreaterThan(0)+ })+})++describe('Fehlerfall: ein blockiertes Werkzeug markiert seinen Schritt "failed"', () => {+ it('die bestehende Fehlermeldung bleibt unveraendert, UND der Block zeigt "failed"', async () => {+ usePermissionStore.getState().setGlobalPermission('terminal', 'blocked')+ const { result } = renderHook(() => useAgentChat())+ const convId = seed()++ await act(async () => {+ await result.current.sendAgentMessage('run workflow Progress Blocked')+ await tick()+ })++ const tc = progressToolCall(convId)+ expect(tc.status).toBe('failed')+ expect(tc.result).toContain('Step 1 of 1: Run it - failed')+ expect(tc.result).toMatch(/error: /)++ 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 stopped at step 1 of 1/)+ })+})++describe('Stop: der laufende Fortschrittsblock haelt an, der Lauf raeumt sich ab', () => {+ it('waehrend einer wartenden Freigabe zeigt der Block "running", und Stop beendet den Lauf', async () => {+ usePermissionStore.getState().setGlobalPermission('terminal', 'confirm')+ const { result } = renderHook(() => useAgentChat())+ const convId = seed()++ let sendDone!: Promise<void>+ await act(async () => {+ sendDone = result.current.sendAgentMessage('run workflow Progress Blocked')+ await tick()+ await tick()++ expect(__activeAgentRunConvIdsForTests()).toContain(convId)+ expect(headApproval(convId)).not.toBeNull()++ const tc = progressToolCall(convId)+ expect(tc.status).toBe('running')+ expect(tc.result).toContain('Step 1 of 1: Run it - running...')++ result.current.stopAgent(convId)+ await sendDone+ await tick()+ })++ expect(headApproval(convId)).toBeNull()+ expect(__activeAgentRunConvIdsForTests()).not.toContain(convId)+ })+})diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 7cbfe57a..d81bdd5d 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -86,6 +86,7 @@ import { AgentLoopGuard } from '../lib/agent-loop-guard'import { budgetFromSettings } from '../api/agents/budget'import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'import type { WorkflowEngineCallbacks } from '../types/agent-workflows'+import { renderWorkflowStepList, workflowProgressHeader, type WorkflowStepView } from '../lib/workflow-progress-view'import { executeParallel, applyResultToToolCall, type ExecutionRequest } from '../api/agents/tool-executor'import { useToolAuditStore } from '../stores/toolAuditStore'import { makeInTurnCacheLookup } from '../api/agents/in-turn-cache'@@ -401,8 +402,17 @@ export function useAgentChat() {useChatStore.getState().addMessage(convId, {id: uuid(), role: 'user', content: userContent, timestamp: Date.now(),})+ // klein 2 (bau/wfprogress.md): this message used to end on a bare+ // "..." that never changed for the whole run — the ONLY feedback a+ // multi-minute workflow gave was three static dots, unlike every+ // other tool call, which shows a running/working status block. The+ // trailing "..." is dropped here; `progressMessageId` below carries+ // the SAME per-step ToolCallBlock/ToolCallBand pattern real tool+ // calls use instead, updated live from the engine's onStepStart/+ // onStepComplete/onStepError callbacks.+ const progressMessageId = uuid()useChatStore.getState().addMessage(convId, {- id: uuid(), role: 'assistant', content: `Running workflow: **${workflow.name}**...`, timestamp: Date.now(),+ id: progressMessageId, role: 'assistant', content: `Running workflow: **${workflow.name}**`, timestamp: Date.now(),})// B1 (lu-301/bau/klaerung-n7.md): a workflow that ends in@@ -428,12 +438,122 @@ export function useAgentChat() {// 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: ...".+ // Nebenbefund, bau/review-wfplay.md Teil B: this trigger used to hand+ // the engine no gate at all, so a workflow's own tool steps ran+ // unattended. Reusing `buildSubAgentGates` (audit AGT-1's fix, same+ // approach a delegated sub-agent already gets) reaches the SAME+ // conversation-keyed approval queue and permission store the rest of+ // Agent mode uses, so the user sees the same "Requesting approval"+ // block, not a bespoke one for workflows.+ //+ // Auflage 8, bau/review-wfgate.md: without an `abortSignal` here, the+ // abort listener inside `buildSubAgentGates`'s gate never fired, and+ // this run was never registered in `activeAgentRuns`, so `stopAgent`+ // had no handle to actually cancel the engine's own in-flight prompt+ // step, only `drainApprovals` happened to also clear a QUEUED+ // approval as an accident of being keyed on the same `convId`.+ // Registering this run the same way every other agent turn does+ // gives Stop both a real `abortSignal` to close the gate with and a+ // live engine to call `cancel()` on.+ //+ // Declared here (before `callbacks`) because onStepStart/onStepComplete+ // below write into `workflowRunState.blocks` the same way the normal+ // tool-call loop writes into its own run state — see addBlock/+ // updateBlockById above.+ const workflowAbort = new AbortController()+ const workflowRunState: AgentRunState = { convId, content: '', thinking: '', blocks: [], abort: workflowAbort }++ // klein 2 (bau/wfprogress.md) + Zusatz vom Eigner, 20.09.2026: ONE+ // AgentToolCall-shaped block for the whole run, added once and+ // updated in place — the exact addBlock/updateBlockById pattern the+ // normal agent tool loop already uses (see the `run_workflow`-less+ // path below), so this is the SAME clickable, downward-expanding+ // ToolCallBlock a real tool call gets: same header/spinner while+ // running, same "click to expand" body. The body (`result`, rendered+ // in the block's existing details pane) is the full step list from+ // `workflow-progress-view.ts` — every step's status (waiting/running/+ // done/failed), each finished step's truncated args+result (tool+ // steps) or the start of the model's answer (prompt steps), and the+ // currently running step's LIVE text as it streams in+ // (`onStepProgress`). The block stays mounted and expandable after+ // the run ends; the existing honest completion/error message still+ // follows as its own chat message, unchanged.+ const stepViews: WorkflowStepView[] = workflow.steps.map((step) => ({ step, status: 'pending' as const }))+ const progressBlockId = uuid()+ const progressToolCallId = uuid()+ const progressStartedAt = Date.now()++ const pushProgressBlock = (status: 'running' | 'completed' | 'failed') => {+ if (!convId) return+ const now = Date.now()+ const ac: AgentToolCall = {+ id: progressToolCallId,+ toolName: workflowProgressHeader(workflow.name, stepViews),+ args: {},+ status,+ result: renderWorkflowStepList(stepViews),+ timestamp: progressStartedAt,+ startedAt: progressStartedAt,+ completedAt: status === 'running' ? undefined : now,+ duration: status === 'running' ? undefined : now - progressStartedAt,+ }+ updateBlockById(workflowRunState, convId, progressMessageId, progressBlockId, {+ content: ac.toolName,+ toolCall: ac,+ toolCalls: [ac],+ })+ }++ // Mounted once, before the engine starts, so the block exists and is+ // already expandable (every step listed as "waiting") the instant+ // the run begins, not only once the first step starts.+ addBlock(workflowRunState, convId, progressMessageId, {+ id: progressBlockId,+ phase: 'tool_call',+ content: workflowProgressHeader(workflow.name, stepViews),+ toolCall: {+ id: progressToolCallId, toolName: workflowProgressHeader(workflow.name, stepViews), args: {},+ status: 'running', result: renderWorkflowStepList(stepViews), timestamp: progressStartedAt, startedAt: progressStartedAt,+ },+ toolCalls: [{+ id: progressToolCallId, toolName: workflowProgressHeader(workflow.name, stepViews), args: {},+ status: 'running', result: renderWorkflowStepList(stepViews), timestamp: progressStartedAt, startedAt: progressStartedAt,+ }],+ timestamp: progressStartedAt,+ })+let hadStepError = falseconst callbacks: WorkflowEngineCallbacks = {- onStepStart: () => {},- onStepComplete: () => {},+ onStepStart: (stepIndex, step) => {+ const view = stepViews[stepIndex]+ if (view) {+ view.status = 'running'+ view.step = step+ }+ pushProgressBlock('running')+ },+ onStepProgress: (stepIndex, partialOutput) => {+ const view = stepViews[stepIndex]+ if (view) view.output = partialOutput+ pushProgressBlock('running')+ },+ onStepComplete: (stepIndex, result) => {+ const view = stepViews[stepIndex]+ if (view) {+ view.status = 'completed'+ view.output = result.output+ view.args = result.toolCalls?.[0]?.args+ }+ pushProgressBlock('running')+ },onStepError: (i, error) => {hadStepError = true+ const view = stepViews[i]+ if (view) {+ view.status = 'failed'+ view.error = error+ }+ pushProgressBlock('failed')if (convId) {useChatStore.getState().addMessage(convId, {id: uuid(), role: 'assistant', content: describeWorkflowStepFailure(workflow, i, error), timestamp: Date.now(),@@ -442,12 +562,33 @@ export function useAgentChat() {},onWaitingForInput: () => {},onComplete: (allResults) => {+ // Any step neither completed nor failed never ran (a condition+ // branched past it, or the chain stopped before reaching it) —+ // named "skipped" (the SAME StepStatus a real skip already uses)+ // instead of staying "waiting" forever after the run is over.+ for (const result of allResults) {+ const idx = workflow.steps.findIndex((s) => s.id === result.stepId)+ const view = idx >= 0 ? stepViews[idx] : undefined+ if (view && view.status !== 'failed') {+ view.status = result.status === 'failed' ? 'failed' : 'completed'+ view.output = result.output+ view.args = result.toolCalls?.[0]?.args ?? view.args+ }+ }+ for (const view of stepViews) {+ if (view.status === 'pending' || view.status === 'running') view.status = 'skipped'+ }+ pushProgressBlock(hadStepError ? 'failed' : 'completed')if (hadStepError || !convId) returnuseChatStore.getState().addMessage(convId, {id: uuid(), role: 'assistant', content: describeWorkflowCompletion(workflow, allResults), timestamp: Date.now(),})},onError: (err) => {+ for (const view of stepViews) {+ if (view.status === 'pending' || view.status === 'running') view.status = 'skipped'+ }+ pushProgressBlock('failed')if (convId) {useChatStore.getState().addMessage(convId, {id: uuid(), role: 'assistant', content: `Workflow error: ${err}`, timestamp: Date.now(),@@ -456,24 +597,6 @@ export function useAgentChat() {},}- // Nebenbefund, bau/review-wfplay.md Teil B: this trigger used to hand- // the engine no gate at all, so a workflow's own tool steps ran- // unattended. Reusing `buildSubAgentGates` (audit AGT-1's fix, same- // approach a delegated sub-agent already gets) reaches the SAME- // conversation-keyed approval queue and permission store the rest of- // Agent mode uses, so the user sees the same "Requesting approval"- // block, not a bespoke one for workflows.- //- // Auflage 8, bau/review-wfgate.md: without an `abortSignal` here, the- // abort listener inside `buildSubAgentGates`'s gate never fired, and- // this run was never registered in `activeAgentRuns`, so `stopAgent`- // had no handle to actually cancel the engine's own in-flight prompt- // step, only `drainApprovals` happened to also clear a QUEUED- // approval as an accident of being keyed on the same `convId`.- // Registering this run the same way every other agent turn does- // gives Stop both a real `abortSignal` to close the gate with and a- // live engine to call `cancel()` on.- const workflowAbort = new AbortController()const gates = await buildSubAgentGates({token: `workflow-trigger-${convId}`,chatId: null,@@ -495,7 +618,6 @@ export function useAgentChat() {: undefinedconst engine = new WorkflowEngine(workflow, convId, callbacks, gates.awaitApproval, initialVars)workflowAbort.signal.addEventListener('abort', () => engine.cancel(), { once: true })- const workflowRunState: AgentRunState = { convId, content: '', thinking: '', blocks: [], abort: workflowAbort }activeAgentRuns.set(convId, workflowRunState)setIsAgentRunning(true)try {diff --git a/src/lib/__tests__/workflow-progress-view.test.ts b/src/lib/__tests__/workflow-progress-view.test.tsnew file mode 100644index 00000000..c766c31a--- /dev/null+++ b/src/lib/__tests__/workflow-progress-view.test.ts@@ -0,0 +1,120 @@+/**+ * Pure-function tests for workflow-progress-view.ts (bau/wfprogress.md).+ *+ * This module builds the text a running workflow's ToolCallBlock shows once+ * expanded: every step's status, each finished step's truncated args/result,+ * and the running step's live text. Kept independent of React/the chat store+ * so the rendering logic itself is directly testable.+ *+ * Run: npx vitest run src/lib/__tests__/workflow-progress-view.test.ts+ */+import { describe, it, expect } from 'vitest'+import {+ renderWorkflowStepList,+ workflowProgressHeader,+ truncateForProgress,+ PROGRESS_DISPLAY_TRUNCATE_CHARS,+ type WorkflowStepView,+} from '../workflow-progress-view'+import type { WorkflowStep } from '../../types/agent-workflows'++function step(id: string, label: string): WorkflowStep {+ return { id, type: 'tool', label }+}++describe('renderWorkflowStepList: die vollstaendige Schrittliste', () => {+ it('zeigt ALLE Schritte, auch die, die noch nicht gelaufen sind (wartet)', () => {+ const views: WorkflowStepView[] = [+ { step: step('a', 'Search the web'), status: 'completed', output: 'found tea history' },+ { step: step('b', 'Summarize'), status: 'running', output: 'Tea has a' },+ { step: step('c', 'Save to memory'), status: 'pending' },+ ]+ const text = renderWorkflowStepList(views)+ expect(text).toContain('Step 1 of 3: Search the web - done')+ expect(text).toContain('Step 2 of 3: Summarize - running...')+ expect(text).toContain('Step 3 of 3: Save to memory - waiting')+ // The running step's partial text is labelled differently from a+ // finished step's result, so "still going" never reads as "done".+ expect(text).toContain('so far: Tea has a')+ expect(text).toContain('result: found tea history')+ })++ it('zeigt Argumente und Resultat fuer einen Werkzeug-Schritt, gekuerzt', () => {+ const views: WorkflowStepView[] = [+ {+ step: step('a', 'Search the web'),+ status: 'completed',+ args: { query: 'history of tea' },+ output: 'Tea originated in China thousands of years ago.',+ },+ ]+ const text = renderWorkflowStepList(views)+ expect(text).toContain('args: {"query":"history of tea"}')+ expect(text).toContain('result: Tea originated in China thousands of years ago.')+ })++ it('zeigt einen Fehler am fehlgeschlagenen Schritt', () => {+ const views: WorkflowStepView[] = [+ { step: step('a', 'Search the web'), status: 'failed', error: 'All search tiers failed' },+ ]+ const text = renderWorkflowStepList(views)+ expect(text).toContain('Step 1 of 1: Search the web - failed')+ expect(text).toContain('error: All search tiers failed')+ })++ it('markiert einen nie erreichten Schritt als uebersprungen, nicht als ewig wartend', () => {+ const views: WorkflowStepView[] = [+ { step: step('a', 'Ask'), status: 'failed', error: 'boom' },+ { step: step('b', 'Never runs'), status: 'skipped' },+ ]+ const text = renderWorkflowStepList(views)+ expect(text).toContain('Step 2 of 2: Never runs - skipped')+ })+})++describe('truncateForProgress: Kuerzung fuer die Chat-Anzeige', () => {+ it('laesst kurzen Text unveraendert', () => {+ expect(truncateForProgress('short result')).toBe('short result')+ })++ it('kuerzt langen Text auf das Anzeige-Budget und nennt die Restlaenge', () => {+ const long = 'x'.repeat(PROGRESS_DISPLAY_TRUNCATE_CHARS + 250)+ const truncated = truncateForProgress(long)+ expect(truncated.length).toBeLessThan(long.length)+ expect(truncated.startsWith('x'.repeat(PROGRESS_DISPLAY_TRUNCATE_CHARS))).toBe(true)+ expect(truncated).toContain('[250 more chars]')+ })++ it('NEGATIVKONTROLLE: ohne Kuerzung stuende der volle Text in der Stufenliste', () => {+ // Same assembly renderWorkflowStepList does, but skipping truncateForProgress+ // entirely — the shape a regression would take if someone inlined the+ // field instead of calling the helper.+ const long = 'y'.repeat(5000)+ const untouched = ` result: ${long}`+ expect(untouched.length).toBeGreaterThan(PROGRESS_DISPLAY_TRUNCATE_CHARS)+ // The real helper never lets that happen:+ const views: WorkflowStepView[] = [{ step: step('a', 'Fetch'), status: 'completed', output: long }]+ const rendered = renderWorkflowStepList(views)+ const resultLine = rendered.split('\n').find((l) => l.trim().startsWith('result:'))!+ expect(resultLine.length).toBeLessThan(long.length)+ })+})++describe('workflowProgressHeader: der eingeklappte Titel', () => {+ it('nennt den GERADE laufenden Schritt', () => {+ const views: WorkflowStepView[] = [+ { step: step('a', 'Search the web'), status: 'completed' },+ { step: step('b', 'Summarize'), status: 'running' },+ { step: step('c', 'Save'), status: 'pending' },+ ]+ expect(workflowProgressHeader('Research Topic', views)).toBe('Step 2 of 3: Summarize')+ })++ it('zeigt eine Zusammenfassung, sobald kein Schritt mehr laeuft', () => {+ const views: WorkflowStepView[] = [+ { step: step('a', 'Search the web'), status: 'completed' },+ { step: step('b', 'Summarize'), status: 'completed' },+ ]+ expect(workflowProgressHeader('Research Topic', views)).toBe('Workflow: Research Topic (2/2 steps)')+ })+})diff --git a/src/lib/__tests__/workflow-prompt-step-output-policy.test.ts b/src/lib/__tests__/workflow-prompt-step-output-policy.test.tsnew file mode 100644index 00000000..420843e2--- /dev/null+++ b/src/lib/__tests__/workflow-prompt-step-output-policy.test.ts@@ -0,0 +1,318 @@+/**+ * Harter Befund von der Box, 20.09.2026 (bau/wfprogress.md): while a workflow+ * ran "Research Topic", `llama-server`'s /slots endpoint showed one request at+ * n_decoded 30090 / n_predict 31619 on a 32768-token context, and the run+ * ended with "Workflow stopped at step 3 of 6: The model returned no content+ * for this prompt step." — the model spent its ENTIRE output budget inside+ * <think> and never reached an answer. The cause: `executePromptStep`+ * (workflow-engine.ts) built its `provider.chatStream` / `chatWithTools` /+ * `streamProviderTurn` options from `temperature` and `contextWindow` ONLY —+ * no `maxTokens` (so the OpenAI-compatible provider's own fallback,+ * `body.max_tokens = Math.min(headroom, 32768)`, asked for the entire+ * remaining context) and no `thinking` policy at all, so an "always thinks"+ * model (GLM-5.3, Flash, Qwen3.5 — memory index) reasoned at its own default+ * depth with the whole context to spend it in.+ *+ * The fix reuses the house's own answer to this exact failure:+ * `compact-run.ts`'s auto-compaction summarizer measured the SAME thing on+ * the SAME model family and asks for `thinking: false` outright, because its+ * call — like a workflow's prompt step — is a mechanical execution of an+ * instruction, not a conversation that benefits from visible deliberation. An+ * earlier version of this fix instead requested `thinking: true` for an+ * "always thinks" model (reasoning: "that is what the catalogue says"), which+ * a counter-check found makes the failure MORE likely under a bounded+ * `maxTokens`, not less — explicit full-depth reasoning burns the cap before+ * ever answering. `thinking: false` is what actually ships.+ *+ * This drives the REAL `WorkflowEngine` over a one-step prompt workflow with+ * a mocked provider that just records the options it received, so a+ * regression (someone drops a field again, or reintroduces `thinking: true`)+ * shows up as a wrong value here instead of a silent 13-minute run on the box.+ *+ * Run: npx vitest run src/lib/__tests__/workflow-prompt-step-output-policy.test.ts+ */+import { describe, it, expect, beforeEach, vi } from 'vitest'++vi.mock('../agent-strategy', () => ({+ resolveToolCallingStrategy: vi.fn(),+}))++import { WorkflowEngine } from '../workflow-engine'+import { APPROVE_ALL } from '../../api/agents/tool-executor'+import { useModelStore } from '../../stores/modelStore'+import { useSettingsStore } from '../../stores/settingsStore'+import { resolveToolCallingStrategy } from '../agent-strategy'+import { DEFAULT_SETTINGS } from '../constants'+import type { AgentWorkflow, WorkflowEngineCallbacks, StepResult } from '../../types/agent-workflows'+import type { ChatOptions, ChatStreamChunk } from '../../api/providers/types'++const ALWAYS_THINKS_MODEL = 'openai::always-thinks-model'++function onePromptWorkflow(): AgentWorkflow {+ return {+ id: 'wf-prompt', name: 'test prompt', description: '', icon: 'Zap',+ steps: [{ id: 'p', type: 'prompt', label: 'Summarize', prompt: 'say something', allowedTools: [] }],+ variables: {}, isBuiltIn: false, createdAt: 0, updatedAt: 0,+ }+}++function silentCallbacks(onProgress?: (i: number, text: string) => void): WorkflowEngineCallbacks {+ return {+ onStepStart: () => {},+ onStepComplete: () => {},+ onStepError: () => {},+ onWaitingForInput: () => {},+ onComplete: () => {},+ onError: () => {},+ onStepProgress: onProgress,+ }+}++beforeEach(() => {+ useModelStore.setState({+ models: [+ {+ name: ALWAYS_THINKS_MODEL,+ model: ALWAYS_THINKS_MODEL,+ size: 0,+ type: 'text',+ provider: 'openai',+ providerName: 'Test',+ thinkMode: 'always',+ effortLevels: ['low', 'medium', 'high'],+ effortDefault: 'medium',+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any,+ ],+ activeModel: ALWAYS_THINKS_MODEL,+ })+ useSettingsStore.setState({+ settings: { ...DEFAULT_SETTINGS },+ })+})++describe('a prompt step asks for the SAME output-limit policy a normal chat/agent turn asks for', () => {+ it('passes thinking:false + the effort ladder + maxTokens to chatStream, not just temperature/contextWindow', async () => {+ let seenOptions: ChatOptions | undefined+ vi.mocked(resolveToolCallingStrategy).mockResolvedValue({+ strategy: 'native',+ modelToUse: ALWAYS_THINKS_MODEL,+ modelId: ALWAYS_THINKS_MODEL,+ providerId: 'openai',+ provider: {+ chatStream: (_model: string, _messages: unknown, options: ChatOptions) => {+ seenOptions = options+ return (async function* (): AsyncGenerator<ChatStreamChunk> {+ yield { content: 'a short answer', done: true }+ })()+ },+ chatWithTools: vi.fn(),+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any,+ })++ const engine = new WorkflowEngine(onePromptWorkflow(), 'conv-a', silentCallbacks(), APPROVE_ALL)+ await engine.run()++ // NEGATIVKONTROLLE (bau/wfprogress.md): before the fix `executePromptStep`+ // sent only `{ temperature, contextWindow, signal }` — every one of these+ // was `undefined`/absent, and the model reasoned at its own unbounded+ // default. See bau/wfprogress.md for the counted red count on the+ // pre-fix copy.+ expect(seenOptions).toBeDefined()+ // klein 4 (bau/wfprogress.md, Eigner-Nachtrag): NOT `true` — an "always+ // thinks" model asked to reason explicitly under a bounded output is+ // exactly how the box's run died with no content at step 3 of 6.+ // `thinking: false` is the SAME policy compact-run.ts already ships for+ // this model family's measured failure.+ expect(seenOptions!.thinking).toBe(false)+ expect(seenOptions!.effortLevels).toEqual(['low', 'medium', 'high'])+ expect(seenOptions!.effortDefault).toBe('medium')+ // reasoningEffort itself may be undefined (the user never touched the+ // composer's slider) — what matters is the LADDER travels, which is what+ // lets the provider clamp onto a real rung instead of sending nothing.+ expect('reasoningEffort' in seenOptions!).toBe(true)+ expect('maxTokens' in seenOptions!).toBe(true)+ })++ it('a chat with its own maxTokens override carries it onto the wire, same as a normal turn', async () => {+ let seenOptions: ChatOptions | undefined+ vi.mocked(resolveToolCallingStrategy).mockResolvedValue({+ strategy: 'native',+ modelToUse: ALWAYS_THINKS_MODEL,+ modelId: ALWAYS_THINKS_MODEL,+ providerId: 'openai',+ provider: {+ chatStream: (_model: string, _messages: unknown, options: ChatOptions) => {+ seenOptions = options+ return (async function* (): AsyncGenerator<ChatStreamChunk> {+ yield { content: 'ok', done: true }+ })()+ },+ chatWithTools: vi.fn(),+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any,+ })+ useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, maxTokens: 512 } })++ const engine = new WorkflowEngine(onePromptWorkflow(), 'conv-b', silentCallbacks(), APPROVE_ALL)+ await engine.run()++ expect(seenOptions!.maxTokens).toBe(512)+ })+})++describe('klein 3: a streaming prompt step relays its growing answer', () => {+ it('onStepProgress fires with the cumulative text as chunks arrive', async () => {+ vi.mocked(resolveToolCallingStrategy).mockResolvedValue({+ strategy: 'native',+ modelToUse: ALWAYS_THINKS_MODEL,+ modelId: ALWAYS_THINKS_MODEL,+ providerId: 'openai',+ provider: {+ chatStream: () => (async function* (): AsyncGenerator<ChatStreamChunk> {+ yield { content: 'Tea ', done: false }+ yield { content: 'has a long history.', done: true }+ })(),+ chatWithTools: vi.fn(),+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any,+ })++ const progress: Array<{ i: number; text: string }> = []+ const engine = new WorkflowEngine(+ onePromptWorkflow(), 'conv-c',+ silentCallbacks((i, text) => progress.push({ i, text })),+ APPROVE_ALL,+ )+ await engine.run()++ expect(progress.length).toBeGreaterThanOrEqual(2)+ expect(progress[0]).toEqual({ i: 0, text: 'Tea ' })+ expect(progress[progress.length - 1].text).toBe('Tea has a long history.')+ })++ it('Negativkontrolle: a step with no onStepProgress callback never throws (optional callback)', async () => {+ vi.mocked(resolveToolCallingStrategy).mockResolvedValue({+ strategy: 'native',+ modelToUse: ALWAYS_THINKS_MODEL,+ modelId: ALWAYS_THINKS_MODEL,+ providerId: 'openai',+ provider: {+ chatStream: () => (async function* (): AsyncGenerator<ChatStreamChunk> {+ yield { content: 'ok', done: true }+ })(),+ chatWithTools: vi.fn(),+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any,+ })+ const engine = new WorkflowEngine(onePromptWorkflow(), 'conv-d', silentCallbacks(undefined), APPROVE_ALL)+ const results = await engine.run()+ expect(results[0].status).toBe('completed')+ })+})++describe('Stop reaches a running prompt step (AbortSignal bis zum fetch)', () => {+ it('the SAME AbortSignal object engine.cancel() aborts is the one handed to chatStream', async () => {+ let seenSignal: AbortSignal | undefined+ vi.mocked(resolveToolCallingStrategy).mockResolvedValue({+ strategy: 'native',+ modelToUse: ALWAYS_THINKS_MODEL,+ modelId: ALWAYS_THINKS_MODEL,+ providerId: 'openai',+ provider: {+ chatStream: (_model: string, _messages: unknown, options: ChatOptions) => {+ seenSignal = options.signal+ return (async function* (): AsyncGenerator<ChatStreamChunk> {+ // Real providers stop yielding once the signal aborts; this stub+ // checks the SAME thing the fetch layer checks, so a Stop that+ // never reached this call would leave `aborted` false here too.+ if (options.signal?.aborted) return+ yield { content: 'first chunk', done: false }+ engineHandle.cancel()+ if (options.signal?.aborted) return+ yield { content: ' second chunk should never arrive', done: true }+ })()+ },+ chatWithTools: vi.fn(),+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any,+ })++ const callbacks = silentCallbacks()+ const engineHandle = new WorkflowEngine(onePromptWorkflow(), 'conv-e', callbacks, APPROVE_ALL)+ const results = await engineHandle.run()++ expect(seenSignal).toBeDefined()+ expect(seenSignal!.aborted).toBe(true)+ // The stream stopped at the FIRST chunk once cancel() fired mid-loop —+ // the second chunk's text never reached the step's output.+ expect(results[0]?.output ?? '').not.toContain('second chunk')+ })+})++describe('Denk-Inhalt reist nicht als Schrittergebnis weiter (bereits gefixt, gegengeprueft)', () => {+ it('<think>...</think> is stripped from the output before it becomes last_output', async () => {+ vi.mocked(resolveToolCallingStrategy).mockResolvedValue({+ strategy: 'native',+ modelToUse: ALWAYS_THINKS_MODEL,+ modelId: ALWAYS_THINKS_MODEL,+ providerId: 'openai',+ provider: {+ chatStream: () => (async function* (): AsyncGenerator<ChatStreamChunk> {+ yield { content: '<think>long internal reasoning nobody should see</think>the real answer', done: true }+ })(),+ chatWithTools: vi.fn(),+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any,+ })+ const results: StepResult[] = []+ const engine = new WorkflowEngine(+ onePromptWorkflow(), 'conv-f',+ { ...silentCallbacks(), onComplete: (r) => results.push(...r) },+ APPROVE_ALL,+ )+ await engine.run()++ expect(results[0].output).toBe('the real answer')+ expect(results[0].output).not.toContain('think')+ expect(results[0].output).not.toContain('internal reasoning')+ })+})++describe('klein 4: ein Modell, das die ganze Ausgabelaenge im Denken verbraucht', () => {+ it('endet weiter mit der ehrlichen Fehlermeldung, nicht mit leerem "Erfolg"', async () => {+ // The exact shape the box measured: everything the model produced sat+ // inside <think>...</think> — no real answer ever followed, because the+ // model ran out of output budget while still reasoning. thinking:false+ // (klein 4's own fix) lowers how OFTEN this happens; it cannot promise it+ // never happens on a model that ignores the wish entirely, so the step+ // must still fail honestly here rather than report a false completion.+ vi.mocked(resolveToolCallingStrategy).mockResolvedValue({+ strategy: 'native',+ modelToUse: ALWAYS_THINKS_MODEL,+ modelId: ALWAYS_THINKS_MODEL,+ providerId: 'openai',+ provider: {+ chatStream: () => (async function* (): AsyncGenerator<ChatStreamChunk> {+ yield { content: '<think>reasoning that never resolves into an answer, the model just runs out of budget here', done: true }+ })(),+ chatWithTools: vi.fn(),+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any,+ })+ const results: StepResult[] = []+ const errors: string[] = []+ const engine = new WorkflowEngine(+ onePromptWorkflow(), 'conv-g',+ { ...silentCallbacks(), onStepError: (_i, e) => errors.push(e), onComplete: (r) => results.push(...r) },+ APPROVE_ALL,+ )+ await engine.run()++ expect(errors).toEqual(['The model returned no content for this prompt step.'])+ expect(results).toHaveLength(1)+ expect(results[0].status).toBe('failed')+ expect(results[0].output).toBe('')+ })+})diff --git a/src/lib/release-notes.ts b/src/lib/release-notes.tsindex 3c3c16de..6b4c6ff8 100644--- a/src/lib/release-notes.ts+++ b/src/lib/release-notes.ts@@ -287,6 +287,10 @@ export const RELEASE_NOTES: ReleaseNote[] = [title: 'A workflow now tells you where it stopped instead of claiming success.',detail: 'A step whose web search or page fetch failed, or whose model answered nothing, ends the run with "Workflow stopped at step 2 of 6: ..." instead of carrying on and finishing with "Workflow complete"; a run that really did finish leads with its actual result rather than the "Saved to memory" receipt.',},+ {+ title: 'Running a workflow from chat now shows its progress, step by step.',+ detail: 'Running a workflow from chat ("run workflow ...") now shows its own progress, clickable and expandable exactly like a tool call: every step listed as waiting, running, done or failed, each finished step\'s result, and the currently running step\'s answer streaming in live. Before this it showed no more than three static dots for the whole run, sometimes several minutes, with no way to tell it was still working. A model step also no longer reasons all the way to the end of its context window by default; it now asks for the same output limit a normal chat turn asks for.',+ },],},{diff --git a/src/lib/workflow-engine.ts b/src/lib/workflow-engine.tsindex c5dbd778..e8e415c6 100644--- a/src/lib/workflow-engine.ts+++ b/src/lib/workflow-engine.ts@@ -600,7 +600,7 @@ export class WorkflowEngine {try {switch (step.type) {case 'prompt':- return await this.executePromptStep(step, startedAt)+ return await this.executePromptStep(step, startedAt, stepIndex)case 'tool':return await this.executeToolStep(step, startedAt)@@ -634,7 +634,7 @@ export class WorkflowEngine {// ── Prompt Step ───────────────────────────────────────────- private async executePromptStep(step: WorkflowStep, startedAt: number): Promise<StepResult> {+ private async executePromptStep(step: WorkflowStep, startedAt: number, stepIndex: number): Promise<StepResult> {const { activeModel } = useModelStore.getState()if (!activeModel) throw new Error('No active model')@@ -652,6 +652,53 @@ export class WorkflowEngine {(c) => c.id === this.conversationId,)?.samplingconst sampling = buildSamplingRequest(settings, convSampling)++ // Harter Befund von der Box (bau/wfprogress.md, 20.09.2026): a prompt step+ // sent none of `maxTokens`/`thinking`/`reasoningEffort`/`effortLevels`/+ // `effortDefault` — every field a normal chat/agent turn resolves before+ // calling the SAME provider (useAgentChat.ts's `chatOptions`, useCodex.ts's+ // `codexThinkMode`/`codexEffort`). Without `maxTokens` the OpenAI-+ // compatible provider's own fallback (openai-provider.ts's+ // `body.max_tokens = Math.min(headroom, 32768)`) asks for the ENTIRE+ // remaining context window. Measured on the box: `llama-server` /slots+ // showed n_decoded 30090 at n_predict 31619 on a 32768 ctx, and the run+ // ended with "Workflow stopped at step 3 of 6: The model returned no+ // content for this prompt step." — the model spent the WHOLE budget+ // inside <think> and never reached an answer.+ //+ // Nachtrag (Eigner, 20.09.2026): raising the effort ladder for an+ // "always thinks" model (as an earlier version of this fix did, sending+ // `thinking: true` because the catalogue says thinkMode 'always') makes+ // that failure MORE likely under a bounded `maxTokens`, not less — the+ // model now explicitly reasons at full depth and can burn the entire cap+ // before ever emitting content. The house already has the right policy+ // for exactly this shape of call: `compact-run.ts`'s auto-compaction+ // summarizer measured the SAME failure on the SAME model family+ // (Qwen3.5-9B, "the model consumed all 1200 tokens in the think channel+ // — 4553 chars of reasoning — and wrote NOT ONE line of answer") and+ // fixed it by asking for `thinking: false` outright: a workflow step,+ // like a compaction summary, is a mechanical execution of the workflow+ // author's instruction, not a conversation the user is having WITH the+ // model that benefits from visible deliberation. The provider's own+ // effort-ladder clamp (`thinkingEffort`, openai-provider.ts) turns that+ // into `reasoning_effort: 'none'` (or the walked-down 'minimal' once a+ // server has already refused 'none' for this model) — on a model that+ // cannot truly disable reasoning ("on GLM 5.3 'none' does not stop the+ // thinking, it only stops the upstream from separating it" — same+ // provider comment) the monologue lands inline in `content` instead of a+ // separate channel this loop never read anyway, and `settleThinking`+ // below still strips it from the final output either way.+ const modelMeta = useModelStore.getState().models.find((m) => m.name === activeModel)+ const effortLevels = modelMeta && 'effortLevels' in modelMeta ? modelMeta.effortLevels : undefined+ const effortDefault = modelMeta && 'effortDefault' in modelMeta ? modelMeta.effortDefault : undefined+ const reasoningOptions = {+ thinking: false,+ reasoningEffort: settings.reasoningEffort,+ effortLevels,+ effortDefault,+ maxTokens: sampling.maxTokens,+ }+let output = ''if (step.allowedTools && step.allowedTools.length === 0) {@@ -662,12 +709,19 @@ export class WorkflowEngine {// 404s the moment the model lives on LM Studio.const stream = provider.chatStream(modelToUse, messages, {temperature: sampling.temperature,+ ...reasoningOptions,// Bug AA v2.5.0 — keep num_ctx override for workflow steps too.contextWindow: settings.contextWindowOverride || undefined,signal: this.abortController.signal,})for await (const chunk of stream) {- if (chunk.content) output += chunk.content+ if (chunk.content) {+ output += chunk.content+ // klein 3 (bau/wfprogress.md): relay the growing answer to whoever+ // is watching this run (the chat trigger's progress block), so a+ // long-thinking model shows LIVE text instead of a silent wait.+ this.callbacks.onStepProgress?.(stepIndex, output)+ }if (chunk.done) break}} else {@@ -690,11 +744,15 @@ export class WorkflowEngine {if (strategy === 'native') {const turn = await provider.chatWithTools(modelToUse, messages, allowedTools, {temperature: sampling.temperature,+ ...reasoningOptions,// Bug AA v2.5.0 — same num_ctx override on tool calls.contextWindow: settings.contextWindowOverride || undefined,signal: this.abortController.signal,})output = turn.content || ''+ // `chatWithTools` returns one turn, not a stream — no per-chunk+ // progress to relay, but the field the block shows still updates+ // once this call resolves (onStepComplete carries the final output).// Execute any tool calls, gated the same as a tool step (see// executeToolStep below): the catalog above already hides a blocked@@ -727,9 +785,16 @@ export class WorkflowEngine {hermesMessages.map(m => ({ role: m.role, content: m.content })),{temperature: sampling.temperature,+ ...reasoningOptions,contextWindow: settings.contextWindowOverride || undefined,signal: this.abortController.signal,},+ // klein 3: `streamProviderTurn` already streams under the hood+ // (it wraps `provider.chatStream`) — relaying its cumulative+ // content is the same live-progress hookup the plain-prompt+ // branch above gets, just through this transport's own callback+ // instead of a hand-rolled for-await loop.+ (full) => this.callbacks.onStepProgress?.(stepIndex, full),)const rawContent = hermesTurn.contentdiff --git a/src/lib/workflow-progress-view.ts b/src/lib/workflow-progress-view.tsnew file mode 100644index 00000000..43789693--- /dev/null+++ b/src/lib/workflow-progress-view.ts@@ -0,0 +1,92 @@+/**+ * Pure rendering for the workflow-progress ToolCallBlock (bau/wfprogress.md).+ *+ * klein 2 (Zusatz vom Eigner, 20.09.2026): the running workflow must be+ * clickable and expand DOWNWARD exactly like a real tool call, and the+ * expanded view must show every step (waiting/running/done/failed), each+ * finished step's truncated result (args + result for a tool step, the start+ * of the model's answer for a prompt step), and the currently running step's+ * live text. This module builds that text; the caller (useAgentChat.ts) only+ * has to keep a `WorkflowStepView[]` current and hand it to+ * `renderWorkflowStepList`, which becomes the SAME `AgentToolCall.result` a+ * real tool call already renders in its collapsible details pane — no new+ * component, no new expand pattern.+ *+ * Kept a separate leaf module (no React, no store) so the step-list text and+ * its truncation are unit-testable without mounting a hook.+ */++import type { StepStatus, WorkflowStep } from '../types/agent-workflows'++export interface WorkflowStepView {+ step: WorkflowStep+ status: StepStatus+ /** Tool-step args (from `StepResult.toolCalls[0].args`), when known. */+ args?: Record<string, unknown>+ /** Step output — the model's answer for a prompt step, or the tool+ * result for a tool step. Updated LIVE while a prompt step streams+ * (`onStepProgress`), then finalised on completion. */+ output?: string+ error?: string+}++/**+ * Long tool output already gets a head+tail truncation for the MODEL's own+ * context (`truncateToolResult`, lib/truncate-tool-result.ts). This is a+ * separate, much smaller budget for the CHAT TRANSCRIPT's own display only —+ * "lange Ausgaben kuerzen, damit der Chat nicht explodiert, und nichts davon+ * zusaetzlich in den Modellkontext schieben" (the Eigner's own wording): this+ * value never reaches a prompt, so it stays independent of the model-facing+ * caps in truncate-tool-result.ts. 400 chars is enough to recognise a result+ * (a search snippet, the opening of a summary) without one verbose step+ * pushing the whole transcript block off screen.+ */+export const PROGRESS_DISPLAY_TRUNCATE_CHARS = 400++export function truncateForProgress(text: string, max: number = PROGRESS_DISPLAY_TRUNCATE_CHARS): string {+ const t = (text ?? '').trim()+ if (t.length <= max) return t+ return `${t.slice(0, max)}... [${t.length - max} more chars]`+}++const STATUS_WORD: Record<StepStatus, string> = {+ pending: 'waiting',+ running: 'running...',+ completed: 'done',+ failed: 'failed',+ skipped: 'skipped',+}++/** One step's block in the expanded view: header line, then indented+ * args/result/error, each truncated for display. */+function renderStepView(view: WorkflowStepView, index: number, total: number): string {+ const header = `Step ${index + 1} of ${total}: ${view.step.label} - ${STATUS_WORD[view.status]}`+ const lines = [header]+ if (view.args && Object.keys(view.args).length > 0) {+ lines.push(` args: ${truncateForProgress(JSON.stringify(view.args), 200)}`)+ }+ if (view.output) {+ const label = view.status === 'running' ? 'so far' : 'result'+ lines.push(` ${label}: ${truncateForProgress(view.output)}`)+ }+ if (view.error) {+ lines.push(` error: ${truncateForProgress(view.error)}`)+ }+ return lines.join('\n')+}++/** The whole expanded body: every step, in order, blank-line separated. */+export function renderWorkflowStepList(views: WorkflowStepView[]): string {+ return views.map((v, i) => renderStepView(v, i, views.length)).join('\n\n')+}++/** The collapsed header text (`AgentToolCall.toolName`): the step currently+ * running, or a summary once nothing is. */+export function workflowProgressHeader(workflowName: string, views: WorkflowStepView[]): string {+ const runningIndex = views.findIndex((v) => v.status === 'running')+ if (runningIndex >= 0) {+ return `Step ${runningIndex + 1} of ${views.length}: ${views[runningIndex].step.label}`+ }+ const settled = views.filter((v) => v.status === 'completed' || v.status === 'failed' || v.status === 'skipped').length+ return `Workflow: ${workflowName} (${settled}/${views.length} steps)`+}diff --git a/src/types/agent-workflows.ts b/src/types/agent-workflows.tsindex 53d18c33..2db41c03 100644--- a/src/types/agent-workflows.ts+++ b/src/types/agent-workflows.ts@@ -110,4 +110,15 @@ export interface WorkflowEngineCallbacks {onWaitingForInput: (stepIndex: number, prompt: string) => voidonComplete: (results: StepResult[]) => voidonError: (error: string) => void+ /**+ * Fired with the CUMULATIVE output text as a `prompt` step's model answer+ * streams in (bau/wfprogress.md, harter Befund von der Box: a prompt step+ * used to give no feedback at all while the model produced tokens for+ * minutes). Optional so `builtin-tools.ts`'s `run_workflow` callers, which+ * do not need live text, need not implement it. Never fires for `tool`,+ * `condition`, `loop`, `user_input` or `memory_save` steps, and does not+ * fire for a `prompt` step that calls tools through the native+ * (non-streaming) tool-calling path.+ */+ onStepProgress?: (stepIndex: number, partialOutput: string) => void}