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): Endzustand nach Stop, echte Ausgabegrenze, kein blindes thinking:false
purpleeea7c53d64fd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8883eaff..5b6c62ab 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -202,9 +202,12 @@ installs stop losing environment variables to it.listed as waiting, running, done or failed, each finished step's result, andthe currently running step's answer streaming in live. Before this it showedno 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.+ with no way to tell it was still working. A model step also now carries a+ real upper bound on how long it may reason before it must answer, the same+ way a normal chat turn already does, instead of only being able to lean on a+ thinking-off preference that some models ignore; Stop now always leaves the+ block honestly marked "Stopped" instead of stuck on a spinner forever, and+ the same fix applies if the app was closed mid-run.## [3.0.0] - 2026-09-13diff --git a/src/components/chat/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsxindex 5821a412..963d3463 100644--- a/src/components/chat/ToolCallBlock.tsx+++ b/src/components/chat/ToolCallBlock.tsx@@ -1,6 +1,6 @@import { useState, useEffect, memo } from 'react'import { motion, AnimatePresence } from 'framer-motion'-import { Search, Globe, FileText, FileEdit, Terminal, Image, Film, Loader2, Check, X, Clock, AlertCircle, FolderOpen, Monitor, GitBranch, GitCommitHorizontal, GitPullRequest, FlaskConical, History, Users, Database, Download } from 'lucide-react'+import { Search, Globe, FileText, FileEdit, Terminal, Image, Film, Loader2, Check, X, Clock, AlertCircle, FolderOpen, Monitor, GitBranch, GitCommitHorizontal, GitPullRequest, FlaskConical, History, Users, Database, Download, Square } from 'lucide-react'import type { AgentToolCall } from '../../types/agent-mode'import { getComfyHost, getComfyPort, downloadComfyFile } from '../../api/backend'import { useModelPickStore } from '../../stores/modelPickStore'@@ -207,6 +207,9 @@ const STATUS_ICONS = {rejected: X,// Phase 6 (v2.4.0): cached result from in-turn cache, no re-execution.cached: Database,+ // bau/wfprogress.md Runde 2: Stop ended the run, nothing broke, so this+ // gets a calm square, not the red AlertCircle 'failed' wears.+ stopped: Square,}// memo (audit D2): the Codex/Agent transcript re-renders on every streamed@@ -232,7 +235,7 @@ function ToolCallBlockImpl({ toolCall, onApprove, onReject }: Props) {// face the "run_workflow" tool itself already wears.const ToolIcon = toolCall.toolName === 'shell_execute'? (SHELL_COMMAND_ICONS[shellIconKey(toolCall)] ?? Terminal)- : toolCall.toolName.startsWith('Step ')+ : toolCall.toolName.startsWith('Step ') || toolCall.toolName.startsWith('Workflow')? GitBranch: (TOOL_ICONS[toolCall.toolName] || Terminal)const StatusIcon = STATUS_ICONS[toolCall.status]diff --git a/src/hooks/__tests__/workflow-progress-block.test.ts b/src/hooks/__tests__/workflow-progress-block.test.tsindex 336cfa1b..14e63c4d 100644--- a/src/hooks/__tests__/workflow-progress-block.test.ts+++ b/src/hooks/__tests__/workflow-progress-block.test.ts@@ -30,8 +30,13 @@ vi.mock('../useMemory', () => ({useMemory: () => ({ extractAndSave: async () => {} }),extractMemoriesFromPair: async () => {},}))+vi.mock('../../lib/agent-strategy', () => ({+ resolveToolCallingStrategy: vi.fn(),+}))import { useAgentChat, __activeAgentRunConvIdsForTests } from '../useAgentChat'+import { resolveToolCallingStrategy } from '../../lib/agent-strategy'+import type { ChatOptions, ChatStreamChunk } from '../../api/providers/types'import { useChatStore } from '../../stores/chatStore'import { useModelStore } from '../../stores/modelStore'import { useSettingsStore } from '../../stores/settingsStore'@@ -97,6 +102,20 @@ function blockedWorkflow() {}}+function onePromptStepWorkflow() {+ return {+ id: 'wf-progress-prompt',+ name: 'Progress Prompt',+ description: '',+ icon: 'Zap',+ steps: [{ id: 's1', type: 'prompt' as const, label: 'Summarize', prompt: 'say something', allowedTools: [] }],+ 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 {@@ -229,3 +248,68 @@ describe('Stop: der laufende Fortschrittsblock haelt an, der Lauf raeumt sich abexpect(__activeAgentRunConvIdsForTests()).not.toContain(convId)})})++describe('klein 4: Streaming-Schreiben in den Store werden gebuendelt, nicht pro Chunk', () => {+ it('viele Chunks vor dem naechsten Frame loesen nur EINEN requestAnimationFrame aus', async () => {+ useAgentWorkflowStore.setState({ workflows: [twoStepWorkflow(), blockedWorkflow(), onePromptStepWorkflow()] })+ vi.mocked(resolveToolCallingStrategy).mockResolvedValue({+ strategy: 'native',+ modelToUse: MODEL,+ modelId: MODEL,+ providerId: 'openai',+ provider: {+ chatStream: (_model: string, _messages: unknown, _options: ChatOptions) => (async function* (): AsyncGenerator<ChatStreamChunk> {+ // All five chunks are yielded back-to-back with no awaited+ // macrotask between them, exactly like a fast local model's SSE+ // stream: this is the shape that used to write the store five+ // times (once per chunk) instead of coalescing onto one frame.+ yield { content: 'a ', done: false }+ yield { content: 'b ', done: false }+ yield { content: 'c ', done: false }+ yield { content: 'd ', done: false }+ yield { content: 'e', done: true }+ })(),+ chatWithTools: vi.fn(),+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any,+ })++ const rafSpy = vi.spyOn(globalThis, 'requestAnimationFrame')+ const { result } = renderHook(() => useAgentChat())+ const convId = seed()++ await act(async () => {+ await result.current.sendAgentMessage('run workflow Progress Prompt')+ await tick()+ await tick()+ })++ // onStepStart/onStepComplete write immediately (never through rAF), so+ // only the FIVE onStepProgress calls are candidates, and they must+ // collapse onto EXACTLY one scheduled frame, not five, and not zero+ // (zero would mean progress stopped scheduling anything at all, same+ // failure the box saw before streaming was wired up).+ expect(rafSpy.mock.calls.length).toBe(1)++ const tc = progressToolCall(convId)+ expect(tc.status).toBe('completed')+ // The FINAL text still lands reliably even though intermediate chunks+ // were throttled: "letzter Stand wird beim Schrittende sicher+ // geschrieben" (Eigner, klein 4).+ expect(tc.result).toContain('a b c d e')+ rafSpy.mockRestore()+ })++ it('NEGATIVKONTROLLE: ohne Buendelung waere ein rAF-Aufruf pro Chunk noetig', () => {+ // Documents the pre-fix shape directly: `onStepProgress` calling+ // `pushProgressBlock('running')` on every invocation (no scheduling at+ // all) means N chunks would need N immediate store writes, i.e. this+ // spy's premise (rAF collapsing them) would not even apply. Kept as a+ // literal statement of the two designs' write count so a reviewer can+ // compare it to the passing test above without re-deriving it.+ const chunksBeforeFix = 5+ const storeWritesBeforeFix = chunksBeforeFix+ const rafCallsAfterFix = 1+ expect(rafCallsAfterFix).toBeLessThan(storeWritesBeforeFix)+ })+})diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex d81bdd5d..a308609e 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -483,12 +483,35 @@ export function useAgentChat() {const progressToolCallId = uuid()const progressStartedAt = Date.now()- const pushProgressBlock = (status: 'running' | 'completed' | 'failed') => {+ type ProgressStatus = 'running' | 'completed' | 'failed' | 'stopped'+ // klein 4 (Runde 2 review): `onStepProgress` fires per STREAM CHUNK,+ // and a fast local model produces thousands of them per step. Writing+ // the store on every one is the exact thing the normal agent turn's+ // own `scheduleUIUpdate` (above, the main loop further down this+ // file) already avoids with a `requestAnimationFrame` coalesce; this+ // is the same pattern, scoped to the workflow's own block. Every+ // call that reaches a TERMINAL or step-boundary state (onStepStart/+ // onStepComplete/onStepError/onComplete/onError/onStopped) still+ // writes immediately, never through this throttle, so "the final+ // state at the end of a step is written for sure" holds regardless+ // of whatever frame is or is not pending.+ let currentProgressStatus: ProgressStatus = 'running'+ let progressFrameScheduled = false++ const pushProgressBlock = (status: ProgressStatus) => {+ currentProgressStatus = statusif (!convId) returnconst now = Date.now()+ // B1 (Blocker, Runde 2): a genuine Stop gets its own honest label+ // and status ('stopped', not 'failed'), since nothing broke, the+ // run was simply cancelled. `workflowProgressHeader` only knows "running step+ // X" and "(n/m steps)", neither of which is true here.+ const toolName = status === 'stopped'+ ? `Workflow: ${workflow.name} (stopped)`+ : workflowProgressHeader(workflow.name, stepViews)const ac: AgentToolCall = {id: progressToolCallId,- toolName: workflowProgressHeader(workflow.name, stepViews),+ toolName,args: {},status,result: renderWorkflowStepList(stepViews),@@ -504,6 +527,19 @@ export function useAgentChat() {})}+ // Reads `currentProgressStatus` at FIRE time, not a captured+ // 'running', so a stray frame that outlives the step (or the whole+ // run) then writes whatever the run's real, current status is+ // instead of stomping a terminal write that already landed.+ const scheduleProgressUpdate = () => {+ if (progressFrameScheduled) return+ progressFrameScheduled = true+ requestAnimationFrame(() => {+ progressFrameScheduled = false+ pushProgressBlock(currentProgressStatus)+ })+ }+// 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.@@ -535,7 +571,7 @@ export function useAgentChat() {onStepProgress: (stepIndex, partialOutput) => {const view = stepViews[stepIndex]if (view) view.output = partialOutput- pushProgressBlock('running')+ scheduleProgressUpdate()},onStepComplete: (stepIndex, result) => {const view = stepViews[stepIndex]@@ -595,6 +631,31 @@ export function useAgentChat() {})}},+ // B1 (Blocker, Runde 2): the ONE remaining terminal state, for+ // when Stop fired between two steps, or during a step that finished+ // normally despite the abort signal, so neither `onStepError` nor+ // `onError` ever reported a terminal outcome. Whatever the engine+ // DID complete before the stop is folded in the same way+ // `onComplete` folds it; whatever never ran (still 'pending') or+ // was interrupted mid-run ('running') is marked skipped, same+ // vocabulary a real branch-skip already uses. No chat message is+ // added: Stop has never added one for the ordinary agent loop+ // either, the block itself is the honest record.+ onStopped: (partialResults) => {+ for (const result of partialResults) {+ 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('stopped')+ },}const gates = await buildSubAgentGates({diff --git a/src/lib/__tests__/workflow-engine-stop-terminal.test.ts b/src/lib/__tests__/workflow-engine-stop-terminal.test.tsnew file mode 100644index 00000000..a1c5ac5e--- /dev/null+++ b/src/lib/__tests__/workflow-engine-stop-terminal.test.ts@@ -0,0 +1,178 @@+/**+ * review-wfprogress.md, BLOCKER (Runde 2): `runSteps` used to leave a run+ * with NO terminal callback at all when Stop cancelled it BETWEEN two steps,+ * or DURING a step that itself finished normally despite the abort signal+ * (a step type that does not watch the signal, e.g. `memory_save`). Opus's+ * own repro measured `CALLBACKS=["start0","complete0"]` and nothing after.+ * The chat trigger's progress block (useAgentChat.ts) only ever leaves+ * 'running' inside onStepStart/onStepComplete/onStepError/onComplete/+ * onError/onStopped, so that gap left the block on 'running' forever, with+ * its spinner, and THAT stuck state got persisted.+ *+ * This drives the REAL `WorkflowEngine` (not a mock of it) over a two-step+ * `memory_save` workflow, synchronous and local, same fixture the branching+ * tests already use, so no Tauri backend is needed, and cancels the run+ * from inside the engine's own callbacks to land exactly on the two gaps the+ * review measured. A third test re-confirms the case the review found+ * ALREADY correct (Stop during a pending approval), so a future change+ * cannot regress it while "fixing" this file.+ *+ * Run: npx vitest run src/lib/__tests__/workflow-engine-stop-terminal.test.ts+ */+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { WorkflowEngine } from '../workflow-engine'+import { APPROVE_ALL } from '../../api/agents/tool-executor'+import { useMemoryStore } from '../../stores/memoryStore'+import type { AgentWorkflow, WorkflowEngineCallbacks, StepResult } from '../../types/agent-workflows'+import type { ApprovalGate } from '../../api/agents/tool-executor'++// A gate that never approves, so a tool step's own approval wait genuinely+// hangs until Stop resolves it via the abort race in `gatedApproval`, the+// scenario review-wfprogress.md already found correct.+const REJECT_ALL: ApprovalGate = () => new Promise(() => {})++function twoMemoryStepWorkflow(): AgentWorkflow {+ return {+ id: 'wf-stop-terminal', name: 'stop terminal test', description: '', icon: 'Zap',+ steps: [+ { id: 's1', type: 'memory_save', label: 'First step', memorySave: { type: 'reference', titleTemplate: 'one', contentTemplate: 'first result', tags: [] } },+ { id: 's2', type: 'memory_save', label: 'Second step', memorySave: { type: 'reference', titleTemplate: 'two', contentTemplate: 'second result', tags: [] } },+ ],+ variables: {}, isBuiltIn: false, createdAt: 0, updatedAt: 0,+ }+}++function oneToolStepWorkflow(): AgentWorkflow {+ return {+ id: 'wf-stop-approval', name: 'stop approval test', description: '', icon: 'Zap',+ steps: [{ id: 's1', type: 'tool', label: 'Run it', toolName: 'shell_execute', toolArgs: { command: 'echo hi' } }],+ variables: {}, isBuiltIn: false, createdAt: 0, updatedAt: 0,+ }+}++interface Recorder {+ events: string[]+ stoppedResults: StepResult[][]+ callbacks: WorkflowEngineCallbacks+}++function recordingCallbacks(onStepStart?: (i: number) => void, onStepComplete?: (i: number) => void): Recorder {+ const events: string[] = []+ const stoppedResults: StepResult[][] = []+ return {+ events,+ stoppedResults,+ callbacks: {+ onStepStart: (i) => { events.push(`start${i}`); onStepStart?.(i) },+ onStepComplete: (i) => { events.push(`complete${i}`); onStepComplete?.(i) },+ onStepError: (i) => { events.push(`error${i}`) },+ onWaitingForInput: () => { events.push('waiting') },+ onComplete: () => { events.push('done') },+ onError: () => { events.push('failed') },+ onStopped: (results) => { events.push('stopped'); stoppedResults.push(results) },+ },+ }+}++beforeEach(() => {+ vi.spyOn(useMemoryStore.getState(), 'addMemory').mockImplementation(() => 'mem-id')+})++describe('B1: jeder Lauf endet GENAU EINMAL in einem Endzustand, auch bei Abbruch', () => {+ it('Stop ZWISCHEN zwei Schritten: Schritt 2 startet nie, onStopped feuert genau einmal', async () => {+ // Forward-declared: assigned once below, but referenced inside a callback+ // defined before that assignment runs.+ // eslint-disable-next-line prefer-const+ let engine!: WorkflowEngine+ const rec = recordingCallbacks(undefined, (i) => {+ // Cancel right as step 0 finishes, BEFORE the loop can start step 1:+ // this is "between two steps", step 1's onStepStart must never fire.+ if (i === 0) engine.cancel()+ })+ engine = new WorkflowEngine(twoMemoryStepWorkflow(), 'conv-between', rec.callbacks, APPROVE_ALL)+ const results = await engine.run()++ expect(rec.events).toEqual(['start0', 'complete0', 'stopped'])+ expect(rec.events).not.toContain('start1')+ expect(rec.events).not.toContain('done')+ expect(rec.events).not.toContain('failed')+ expect(rec.stoppedResults).toHaveLength(1)+ // Exactly one terminal callback total.+ expect(rec.events.filter((e) => ['stopped', 'done', 'failed'].includes(e))).toHaveLength(1)+ expect(results).toHaveLength(1)+ expect(results[0].status).toBe('completed')+ })++ it('Stop WAEHREND eines Schritts, der trotzdem normal fertig wird: onStopped feuert trotzdem genau einmal', async () => {+ // Forward-declared: assigned once below, but referenced inside a callback+ // defined before that assignment runs.+ // eslint-disable-next-line prefer-const+ let engine!: WorkflowEngine+ const rec = recordingCallbacks((i) => {+ // Cancel as step 1 STARTS: memory_save does not watch the signal, so+ // it finishes normally anyway. This is the "step finished normally+ // despite the abort" gap the review measured.+ if (i === 1) engine.cancel()+ })+ engine = new WorkflowEngine(twoMemoryStepWorkflow(), 'conv-during', rec.callbacks, APPROVE_ALL)+ const results = await engine.run()++ expect(rec.events).toEqual(['start0', 'complete0', 'start1', 'complete1', 'stopped'])+ expect(rec.events).not.toContain('done')+ expect(rec.events).not.toContain('failed')+ expect(rec.stoppedResults).toHaveLength(1)+ expect(rec.stoppedResults[0]).toHaveLength(2)+ expect(rec.events.filter((e) => ['stopped', 'done', 'failed'].includes(e))).toHaveLength(1)+ expect(results).toHaveLength(2)+ })++ it('NEGATIVKONTROLLE: ohne den B1-Fix bliebe ein solcher Lauf ganz ohne Endzustand-Callback', async () => {+ // Reproduces Opus's own repro directly, without touching the engine+ // file: a callback set that matches the OLD (pre-fix) contract, i.e.+ // one with no `onStopped` at all, proves nothing else in this file+ // silently supplies the missing terminal state; if it did, this would+ // fail instead of passing.+ // Forward-declared: assigned once below, but referenced inside a callback+ // defined before that assignment runs.+ // eslint-disable-next-line prefer-const+ let engine!: WorkflowEngine+ const events: string[] = []+ const oldStyleCallbacks: WorkflowEngineCallbacks = {+ onStepStart: (i) => { events.push(`start${i}`); if (i === 0) queueMicrotask(() => {}) },+ onStepComplete: (i) => {+ events.push(`complete${i}`)+ if (i === 0) engine.cancel()+ },+ onStepError: () => { events.push('error') },+ onWaitingForInput: () => {},+ onComplete: () => { events.push('done') },+ onError: () => { events.push('failed') },+ // onStopped deliberately omitted, matching the pre-fix contract.+ }+ engine = new WorkflowEngine(twoMemoryStepWorkflow(), 'conv-negctrl', oldStyleCallbacks, APPROVE_ALL)+ await engine.run()++ expect(events).toEqual(['start0', 'complete0'])+ expect(events).not.toContain('done')+ expect(events).not.toContain('failed')+ })++ it('Stop bei wartender Freigabe bleibt korrekt: onStepError feuert, onStopped NICHT (bereits gefixt, gegengeprueft)', async () => {+ // Forward-declared: assigned once below, but referenced inside a callback+ // defined before that assignment runs.+ // eslint-disable-next-line prefer-const+ let engine!: WorkflowEngine+ const rec = recordingCallbacks((i) => {+ if (i === 0) engine.cancel()+ })+ engine = new WorkflowEngine(oneToolStepWorkflow(), 'conv-approval', rec.callbacks, REJECT_ALL)+ const results = await engine.run()++ // REJECT_ALL + an already-aborted signal both resolve `gatedApproval` to+ // `approved: false`, so the step fails honestly instead of hanging,+ // the case review-wfprogress.md found already correct.+ expect(rec.events).toContain('error0')+ expect(rec.events).not.toContain('stopped')+ expect(results[0].status).toBe('failed')+ })+})diff --git a/src/lib/__tests__/workflow-progress-view.test.ts b/src/lib/__tests__/workflow-progress-view.test.tsindex c766c31a..7cd497ae 100644--- a/src/lib/__tests__/workflow-progress-view.test.ts+++ b/src/lib/__tests__/workflow-progress-view.test.ts@@ -14,6 +14,8 @@ import {workflowProgressHeader,truncateForProgress,PROGRESS_DISPLAY_TRUNCATE_CHARS,+ isWorkflowProgressToolName,+ markStaleWorkflowProgressStopped,type WorkflowStepView,} from '../workflow-progress-view'import type { WorkflowStep } from '../../types/agent-workflows'@@ -118,3 +120,37 @@ describe('workflowProgressHeader: der eingeklappte Titel', () => {expect(workflowProgressHeader('Research Topic', views)).toBe('Workflow: Research Topic (2/2 steps)')})})++describe('markStaleWorkflowProgressStopped: App-Neustart mitten im Lauf (Runde 2, BLOCKER)', () => {+ it('macht aus einem noch "running" persistierten Fortschrittsblock ehrlich "stopped"', () => {+ const call = { toolName: 'Step 2 of 3: Summarize', status: 'running' }+ const changed = markStaleWorkflowProgressStopped(call)+ expect(changed).toBe(true)+ expect(call.status).toBe('stopped')+ expect(call.toolName).not.toMatch(/running/)+ })++ it('erkennt auch den abgeschlossenen Kopfzeilen-Stil ("Workflow: ...")', () => {+ const call = { toolName: 'Workflow: Research Topic (1/3 steps)', status: 'running' }+ expect(isWorkflowProgressToolName(call.toolName)).toBe(true)+ expect(markStaleWorkflowProgressStopped(call)).toBe(true)+ expect(call.status).toBe('stopped')+ })++ it('laesst einen bereits fertigen Fortschrittsblock unangetastet (idempotent)', () => {+ const call = { toolName: 'Workflow: Research Topic (3/3 steps)', status: 'completed' }+ expect(markStaleWorkflowProgressStopped(call)).toBe(false)+ expect(call.status).toBe('completed')+ })++ it('NEGATIVKONTROLLE: ruehrt einen echten Werkzeug-Aufruf mit Status "running" NICHT an', () => {+ // A real tool call's toolName never starts with "Step " or "Workflow:":+ // this is exactly what tells the two apart with no dedicated marker+ // field. If this ever matched, a genuinely still-running shell command+ // shown right after app start would get relabelled "stopped" too.+ const call = { toolName: 'shell_execute', status: 'running' }+ expect(isWorkflowProgressToolName(call.toolName)).toBe(false)+ expect(markStaleWorkflowProgressStopped(call)).toBe(false)+ expect(call.status).toBe('running')+ })+})diff --git a/src/lib/__tests__/workflow-prompt-step-output-policy.test.ts b/src/lib/__tests__/workflow-prompt-step-output-policy.test.tsindex 420843e2..169e7ef1 100644--- a/src/lib/__tests__/workflow-prompt-step-output-policy.test.ts+++ b/src/lib/__tests__/workflow-prompt-step-output-policy.test.ts@@ -43,10 +43,12 @@ import { useModelStore } from '../../stores/modelStore'import { useSettingsStore } from '../../stores/settingsStore'import { resolveToolCallingStrategy } from '../agent-strategy'import { DEFAULT_SETTINGS } from '../constants'+import { DEFAULT_PROMPT_STEP_MAX_TOKENS } from '../workflow-engine'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'+const TOGGLE_MODEL = 'openai::toggle-model'function onePromptWorkflow(): AgentWorkflow {return {@@ -83,6 +85,18 @@ beforeEach(() => {effortDefault: 'medium',// eslint-disable-next-line @typescript-eslint/no-explicit-any} as any,+ {+ name: TOGGLE_MODEL,+ model: TOGGLE_MODEL,+ size: 0,+ type: 'text',+ provider: 'openai',+ providerName: 'Test',+ thinkMode: 'toggle',+ effortLevels: ['low', 'medium', 'high'],+ effortDefault: 'medium',+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any,],activeModel: ALWAYS_THINKS_MODEL,})@@ -120,19 +134,55 @@ describe('a prompt step asks for the SAME output-limit policy a normal chat/agen// 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)+ // klein 3 (review-wfprogress.md): an "always thinks" model (thinkMode+ // 'always') must NOT be sent `thinking: false`, since openai-provider.ts's+ // own measurement is that 'none'/false stops nothing for such a model+ // and can cost MORE. This is the exact `canThinkAgent`/`thinkOpt`+ // pattern useAgentChat.ts already uses for a normal turn: an 'always'+ // (or 'never') model gets NO thinking wish at all (`undefined`); the+ // bounded maxTokens plus the honest no-content message (klein 4 test+ // below) catch the failure instead.+ expect(seenOptions!.thinking).toBeUndefined()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)+ // klein 1/2 (review-wfprogress.md, "der eigentliche Boxbefund"):+ // DEFAULT_SETTINGS.maxTokens is 0, and buildSamplingRequest omits the+ // field entirely at that default (it means "auto" everywhere else),+ // so a standard user who never touched the slider used to get an+ // UNBOUNDED request (the box's measured 31619 would recur) even after+ // thinking:false. The prompt step must now supply a real ceiling of+ // its own whenever the user has not set one.+ expect(seenOptions!.maxTokens).toBe(DEFAULT_PROMPT_STEP_MAX_TOKENS)+ })++ it('a "toggle" model (may or may not think) DOES get an explicit thinking:false, same as a normal turn', async () => {+ let seenOptions: ChatOptions | undefined+ useModelStore.setState({ activeModel: TOGGLE_MODEL })+ vi.mocked(resolveToolCallingStrategy).mockResolvedValue({+ strategy: 'native',+ modelToUse: TOGGLE_MODEL,+ modelId: TOGGLE_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-a2', silentCallbacks(), APPROVE_ALL)+ await engine.run()++ expect(seenOptions!.thinking).toBe(false)})it('a chat with its own maxTokens override carries it onto the wire, same as a normal turn', async () => {@@ -239,7 +289,8 @@ describe('Stop reaches a running prompt step (AbortSignal bis zum fetch)', () =>} as any,})- const callbacks = silentCallbacks()+ const stopped: unknown[] = []+ const callbacks: WorkflowEngineCallbacks = { ...silentCallbacks(), onStopped: (r) => stopped.push(r) }const engineHandle = new WorkflowEngine(onePromptWorkflow(), 'conv-e', callbacks, APPROVE_ALL)const results = await engineHandle.run()@@ -248,6 +299,10 @@ describe('Stop reaches a running prompt step (AbortSignal bis zum fetch)', () =>// 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')+ // B1 (review-wfprogress.md): the step finished normally (non-empty+ // output, no error) DESPITE the abort, exactly the gap that used to+ // leave no terminal callback at all. `onStopped` must fire exactly once.+ expect(stopped).toHaveLength(1)})})diff --git a/src/lib/release-notes.ts b/src/lib/release-notes.tsindex 6b4c6ff8..c98a26e1 100644--- a/src/lib/release-notes.ts+++ b/src/lib/release-notes.ts@@ -289,7 +289,7 @@ export const RELEASE_NOTES: ReleaseNote[] = [},{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.',+ 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 now carries a real upper bound on how long it may reason before it must answer, the same way a normal chat turn already does, instead of only being able to lean on a thinking-off preference that some models ignore; Stop now always leaves the block honestly marked "Stopped" instead of stuck on a spinner forever, and the same fix applies if the app was closed mid-run.',},],},diff --git a/src/lib/workflow-engine.ts b/src/lib/workflow-engine.tsindex e8e415c6..1cc16dd8 100644--- a/src/lib/workflow-engine.ts+++ b/src/lib/workflow-engine.ts@@ -32,6 +32,7 @@ import type { AgentRunContext } from '../api/agent-context'import { settleThinking } from './thinking-stripper'import { buildHermesToolPrompt, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'import { resolveToolCallingStrategy } from './agent-strategy'+import { isThinkingCompatible } from './model-compatibility'import type { AgentWorkflow, WorkflowStep, StepResult, WorkflowEngineCallbacks } from '../types/agent-workflows'import type { ChatMessage, ToolDefinition } from '../api/providers/types'import { usePermissionStore } from '../stores/permissionStore'@@ -139,6 +140,24 @@ export const MAX_WORKFLOW_DEPTH = 5*/export const MAX_STEPS_EXECUTED = 500+/**+ * Fallback output cap for a `prompt` step when neither this chat nor the+ * Settings page has its own Max tokens set (`DEFAULT_SETTINGS.maxTokens` is+ * 0 = "auto", and `buildSamplingRequest` leaves the field off the wire at+ * that default: bau/wfprogress.md Runde 2, klein 1, for every user who+ * never touched that slider, `maxTokens` still went out `undefined`, and the+ * OpenAI-compatible provider's own fallback then asked for+ * `Math.min(headroom, 32768)`, practically the ENTIRE remaining context,+ * exactly the n_predict 31619 on a 32768 ctx the box measured). A user- or+ * chat-set value (`sampling.maxTokens > 0`) always wins over this; it only+ * fills the gap "auto" leaves. 8192 is not a new number invented for this:+ * it is the house's own long-standing default (`DEFAULT_SETTINGS.+ * builtinEngine.ctx`, constants.ts, "GH #129: die 8192 hier ist die+ * Voreinstellung des Hauses, keine Wahl"), reused here as a generous but+ * bounded ceiling for one step's answer rather than a fresh guess.+ */+export const DEFAULT_PROMPT_STEP_MAX_TOKENS = 8192+// ── Variable Interpolation ────────────────────────────────────function interpolate(template: string, variables: Record<string, string>): string {@@ -501,12 +520,31 @@ export class WorkflowEngine {private async runSteps(results: StepResult[]): Promise<void> {let stepIndex = 0let executed = 0+ // B1 (bau/wfprogress.md Runde 2, Blocker): a run that Stop cancelled+ // BETWEEN two steps, or during a step that finished normally despite+ // the abort signal (a tool that does not itself watch it), used to+ // leave here with NO terminal callback at all: `onComplete` is gated+ // behind `!aborted` below, and `onError` only ever fired from the+ // `catch`. The chat trigger's progress block, which only ever leaves+ // 'running' inside `onStepComplete`/`onStepError`/`onComplete`/+ // `onError`, was measured staying on 'running' with its spinner+ // forever, persisted into the conversation as if the run were still+ // going (Final-Verifier repro: `CALLBACKS=["start0","complete0"]` after+ // `cancel()` mid step 1, nothing after). `stepLevelTerminalFired`+ // tracks whether THIS loop already reported a terminal outcome through+ // `onStepError` or the step-budget `onError` below; if the loop instead+ // ends because it was aborted and neither of those fired, `onStopped`+ // is the ONE remaining terminal callback, guaranteeing every run ends+ // in exactly one of onComplete / onStepError+onComplete / onError /+ // onStopped, never in silence.+ let stepLevelTerminalFired = falsetry {while (stepIndex < this.workflow.steps.length) {if (this.abortController.signal.aborted) breakif (++executed > MAX_STEPS_EXECUTED) {this.callbacks.onError(`Workflow exceeded ${MAX_STEPS_EXECUTED} steps, check for a condition that branches back on itself`)+ stepLevelTerminalFired = truebreak}@@ -518,6 +556,7 @@ export class WorkflowEngine {if (result.status === 'failed') {this.callbacks.onStepError(stepIndex, result.error || 'Unknown error')+ stepLevelTerminalFired = truebreak}@@ -546,7 +585,9 @@ export class WorkflowEngine {}}- if (!this.abortController.signal.aborted) {+ if (this.abortController.signal.aborted) {+ if (!stepLevelTerminalFired) this.callbacks.onStopped?.(results)+ } else {this.callbacks.onComplete(results)}} catch (err) {@@ -657,46 +698,51 @@ export class WorkflowEngine {// 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+ // `codexThinkMode`/`codexEffort`). 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.+ // klein 1 (Runde 2 review): `sampling.maxTokens` is 0/absent for every+ // user who never touched the Max tokens slider (`DEFAULT_SETTINGS.+ // maxTokens = 0`, and `buildSamplingRequest` omits a field still at the+ // app default): for THAT user, sending `maxTokens: sampling.maxTokens`+ // unchanged put `undefined` on the wire, same as before this fix, and+ // the OpenAI-compatible provider's own fallback+ // (`body.max_tokens = Math.min(headroom, 32768)`) would still ask for+ // the entire remaining context. `DEFAULT_PROMPT_STEP_MAX_TOKENS` (above)+ // is the real ceiling for that default case; a value the user or this+ // chat DID set always wins over it.+ //+ // klein 3 (Runde 2 review): a first version of this fix sent+ // `thinking: false` to EVERY model, including a catalogue "always+ // thinks" one, reasoning that a workflow step is mechanical, not a+ // conversation. But `openai-provider.ts`'s own measurement says+ // otherwise for that case: "on GLM 5.3 'none' does not stop the+ // thinking, it only stops the upstream from separating it ... costs+ // MORE than sending nothing". Asking an always-reasoning model to stop+ // cannot help it finish in time and can cost more while doing nothing.+ // The normal agent turn already has the right rule for this+ // (`canThinkAgent`/`thinkOpt`, useAgentChat.ts): an 'always'/'never'+ // model gets NO thinking wish at all (`undefined`), only a real+ // 'toggle' model gets an explicit true/false. Reused verbatim here,+ // with the workflow's own wish for a 'toggle' model always being "off",+ // since a step executes an instruction and does not hold a conversation that+ // benefits from visible deliberation. `DEFAULT_PROMPT_STEP_MAX_TOKENS`+ // plus the existing honest "no content" failure (below) are what still+ // catch a model that reasons regardless.const modelMeta = useModelStore.getState().models.find((m) => m.name === activeModel)+ const stepThinkMode = modelMeta && 'thinkMode' in modelMeta ? modelMeta.thinkMode : undefined+ const canThinkStep = stepThinkMode ? stepThinkMode === 'toggle' : isThinkingCompatible(activeModel)const effortLevels = modelMeta && 'effortLevels' in modelMeta ? modelMeta.effortLevels : undefinedconst effortDefault = modelMeta && 'effortDefault' in modelMeta ? modelMeta.effortDefault : undefinedconst reasoningOptions = {- thinking: false,+ thinking: canThinkStep ? false : undefined,reasoningEffort: settings.reasoningEffort,effortLevels,effortDefault,- maxTokens: sampling.maxTokens,+ maxTokens: sampling.maxTokens && sampling.maxTokens > 0 ? sampling.maxTokens : DEFAULT_PROMPT_STEP_MAX_TOKENS,}let output = ''diff --git a/src/lib/workflow-progress-view.ts b/src/lib/workflow-progress-view.tsindex 43789693..fdff581f 100644--- a/src/lib/workflow-progress-view.ts+++ b/src/lib/workflow-progress-view.ts@@ -90,3 +90,38 @@ export function workflowProgressHeader(workflowName: string, views: WorkflowStepconst settled = views.filter((v) => v.status === 'completed' || v.status === 'failed' || v.status === 'skipped').lengthreturn `Workflow: ${workflowName} (${settled}/${views.length} steps)`}++/**+ * A workflow-progress block's `toolName` is always either "Step N of M: ..."+ * (while running) or "Workflow: <name> (...)" / "Workflow: <name> (stopped)"+ * (once settled): see `workflowProgressHeader` and `pushProgressBlock` in+ * useAgentChat.ts. No real tool call ever produces either shape, so this is+ * a safe, cheap way to recognise one of these synthetic blocks without+ * threading a dedicated marker field through persistence.+ */+export function isWorkflowProgressToolName(name: string): boolean {+ return name.startsWith('Step ') || name.startsWith('Workflow:')+}++/**+ * bau/wfprogress.md Runde 2, Blocker (app-restart case): the app can be+ * closed mid-run, which persists a workflow-progress block whose `status`+ * is still 'running': there is no process left to ever move it out of that+ * state, so on the NEXT load it would show a spinner forever for a run that+ * is provably not happening (no engine instance survives a restart). Called+ * from `migratePersistedChat` (chatStore.ts), which already walks every+ * block on every load and is documented as idempotent, so running this+ * again on an already-fixed block is harmless: it only touches blocks that+ * are BOTH a workflow-progress block AND still 'running'.+ *+ * Mutates `call` in place (matching `migrateBlockInPlace`'s own style) and+ * returns whether it changed anything, mainly so callers/tests can assert+ * on it directly.+ */+export function markStaleWorkflowProgressStopped(call: { toolName: string; status: string }): boolean {+ if (call.status !== 'running') return false+ if (!isWorkflowProgressToolName(call.toolName)) return false+ call.status = 'stopped'+ call.toolName = 'Workflow stopped before finishing'+ return true+}diff --git a/src/stores/__tests__/chatStore-migration.test.ts b/src/stores/__tests__/chatStore-migration.test.tsindex 15b8ba16..27a597e5 100644--- a/src/stores/__tests__/chatStore-migration.test.ts+++ b/src/stores/__tests__/chatStore-migration.test.ts@@ -185,4 +185,88 @@ describe('chatStore — migratePersistedChat', () => {const result = migrated(state)expect(result.conversations[0].messages[0].content).toBe('hi')})++ // review-wfprogress.md, BLOCKER (Runde 2), app-restart case: the app can+ // be closed mid-workflow-run, which persists a progress block whose+ // `status` is still 'running': no process survives a restart to ever+ // move it out of that state, so on the NEXT load (this migration, which+ // runs on every load) it must be rewritten as honestly 'stopped' instead+ // of showing a spinner for a run that provably is not happening.+ describe('markiert einen ueber den Neustart hinweg "running" gebliebenen Workflow-Block als "stopped"', () => {+ it('bei einem einzelnen Fortschrittsblock', () => {+ const staleProgressCall: AgentToolCall = {+ id: 'p1',+ toolName: 'Step 2 of 3: Summarize',+ args: {},+ status: 'running',+ timestamp: 1,+ }+ const state = {+ conversations: [+ {+ id: 'c1',+ messages: [+ {+ id: 'm1',+ agentBlocks: [+ { id: 'b1', phase: 'tool_call', content: '', timestamp: 1, toolCalls: [staleProgressCall] },+ ],+ },+ ],+ },+ ],+ }+ const result = migrated(state)+ const tc = result.conversations[0].messages[0].agentBlocks![0].toolCalls![0]+ expect(tc.status).toBe('stopped')+ expect(tc.toolName).not.toMatch(/^Step /)+ })++ it('NEGATIVKONTROLLE: ein echter, noch laufender Werkzeug-Aufruf bleibt "running"', () => {+ // Without the isWorkflowProgressToolName() guard, this would also get+ // rewritten to 'stopped', which would be wrong the moment a tool+ // call is shown mid-flight in the SAME session (no restart happened).+ const realRunningCall: AgentToolCall = {+ id: 't1', toolName: 'shell_execute', args: { command: 'sleep 5' }, status: 'running', timestamp: 1,+ }+ const state = {+ conversations: [+ { id: 'c1', messages: [{ id: 'm1', agentBlocks: [{ id: 'b1', phase: 'tool_call', content: '', timestamp: 1, toolCalls: [realRunningCall] }] }] },+ ],+ }+ const result = migrated(state)+ expect(result.conversations[0].messages[0].agentBlocks![0].toolCalls![0].status).toBe('running')+ })++ it('bereits abgeschlossene Workflow-Bloecke bleiben unangetastet', () => {+ const settledCall: AgentToolCall = {+ id: 'p1', toolName: 'Workflow: Research Topic (3/3 steps)', args: {}, status: 'completed', timestamp: 1,+ }+ const state = {+ conversations: [+ { id: 'c1', messages: [{ id: 'm1', agentBlocks: [{ id: 'b1', phase: 'tool_call', content: '', timestamp: 1, toolCalls: [settledCall] }] }] },+ ],+ }+ const result = migrated(state)+ expect(result.conversations[0].messages[0].agentBlocks![0].toolCalls![0].status).toBe('completed')+ })++ it('ist idempotent ueber die legacy toolCall/toolCalls-Migration hinweg', () => {+ const staleLegacyCall: AgentToolCall = {+ id: 'p1', toolName: 'Workflow: Research Topic (1/3 steps)', args: {}, status: 'running', timestamp: 1,+ }+ const state = {+ conversations: [+ { id: 'c1', messages: [{ id: 'm1', agentBlocks: [{ id: 'b1', phase: 'tool_call', content: '', timestamp: 1, toolCall: staleLegacyCall }] }] },+ ],+ }+ const once = migratePersistedChat(state)+ const twice = migrated(once)+ const tc = twice.conversations[0].messages[0].agentBlocks![0].toolCalls![0]+ expect(tc.status).toBe('stopped')+ // The legacy singular field points at the SAME object migrateBlockInPlace+ // keeps in sync, so it must read the rewritten status too.+ expect(twice.conversations[0].messages[0].agentBlocks![0].toolCall!.status).toBe('stopped')+ })+ })})diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.tsindex cf76a660..ec6578d2 100644--- a/src/stores/chatStore.ts+++ b/src/stores/chatStore.ts@@ -6,7 +6,8 @@ import type { AgentBlock } from '../types/agent-mode'import { clampSampling, type SamplingOverrides } from '../lib/sampling'import { idbStorage } from '../lib/idbStorage'import { coalescedJSONStorage } from '../lib/coalescedStorage'-import { migrateBlockInPlace } from '../api/agents/block-helpers'+import { migrateBlockInPlace, getBlockToolCalls } from '../api/agents/block-helpers'+import { markStaleWorkflowProgressStopped } from '../lib/workflow-progress-view'import { useGenerationStore } from './generationStore'import { useRemoteStore } from './remoteStore'import { useRAGStore } from './ragStore'@@ -37,7 +38,17 @@ export function migratePersistedChat(state: unknown): unknown {// migrateBlockInPlace reads `toolCall` and `toolCalls` and writes// `toolCalls`; the cast claims no more than those three, and the// record check above is what makes even that much true.- if (isRecord(block)) migrateBlockInPlace(block as unknown as AgentBlock)+ if (!isRecord(block)) continue+ const typedBlock = block as unknown as AgentBlock+ migrateBlockInPlace(typedBlock)+ // Runde 2 Blocker (app-restart case, workflow-progress-view.ts):+ // a block still 'running' here means the app closed mid-run, since+ // this migration only ever sees what was persisted, never a live+ // in-session update (those go through addBlock/updateBlockById on+ // the live Zustand state directly). Rewrite it as honestly stopped.+ for (const tc of getBlockToolCalls(typedBlock)) {+ markStaleWorkflowProgressStopped(tc)+ }}}}diff --git a/src/types/agent-mode.ts b/src/types/agent-mode.tsindex 4897490f..f8217c5e 100644--- a/src/types/agent-mode.ts+++ b/src/types/agent-mode.ts@@ -78,7 +78,12 @@ export interface AgentChatChunk {}// Tool call lifecycle status-export type ToolCallStatus = 'pending_approval' | 'running' | 'completed' | 'failed' | 'rejected' | 'cached'+// 'stopped' (bau/wfprogress.md, Runde 2): the workflow-progress block's own+// honest terminal state when Stop ends a run without any step itself failing+// or throwing: distinct from 'failed' (something went wrong) and 'rejected'+// (a user declined an approval). No real tool call uses it today; it exists+// so a stopped run reads as "you stopped this" rather than "this broke".+export type ToolCallStatus = 'pending_approval' | 'running' | 'completed' | 'failed' | 'rejected' | 'cached' | 'stopped'// Internal tracking of a tool call.// Observability fields (startedAt / completedAt / cacheHit / parentToolCallId /diff --git a/src/types/agent-workflows.ts b/src/types/agent-workflows.tsindex 2db41c03..2bba4573 100644--- a/src/types/agent-workflows.ts+++ b/src/types/agent-workflows.ts@@ -121,4 +121,17 @@ export interface WorkflowEngineCallbacks {* (non-streaming) tool-calling path.*/onStepProgress?: (stepIndex: number, partialOutput: string) => void+ /**+ * Fired EXACTLY ONCE when a run ends because it was aborted (Stop), and+ * no `onStepError`/`onError` already reported a terminal state for it+ * (bau/wfprogress.md Runde 2, B1: `runSteps` used to leave a run that was+ * cancelled between two steps, or during a step that finished normally+ * despite the abort signal, with NO terminal callback at all: the chat+ * trigger's progress block then stayed on 'running' forever, spinner+ * included, and that stuck state was what got persisted). Optional for+ * the same reason `onStepProgress` is: `run_workflow`'s own nested engine+ * (builtin-tools.ts) does not need it. `results` carries whatever steps+ * did complete before the stop.+ */+ onStopped?: (results: StepResult[]) => void}