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(agent): stop a workflow trigger from displacing a live turn, and stop hanging without input
purple519fa7ba3ebb
diff --git a/src/api/mcp/__tests__/run-workflow-braucht-input-sofort.test.ts b/src/api/mcp/__tests__/run-workflow-braucht-input-sofort.test.tsnew file mode 100644index 00000000..d081506d--- /dev/null+++ b/src/api/mcp/__tests__/run-workflow-braucht-input-sofort.test.ts@@ -0,0 +1,54 @@+/**+ * bau/review-wfgate.md Runde 2, klein 2: `run_workflow` on a workflow whose+ * FIRST `user_input` step gets no `input` argument used to hang forever+ * (nothing wires `provideUserInput`), holding whatever lane it booked.+ * `executeRunWorkflow` (builtin-tools.ts) now refuses immediately, with a+ * message the model can act on, and honors `input` exactly as before when+ * it IS given.+ *+ * Run: npx vitest run src/api/mcp/__tests__/run-workflow-braucht-input-sofort.test.ts+ */+import { describe, it, expect, beforeEach } from 'vitest'+import { toolRegistry, registerBuiltinTools } from '../index'+import { useAgentWorkflowStore } from '../../../stores/agentWorkflowStore'+import { useModelStore } from '../../../stores/modelStore'+import type { AgentWorkflow, WorkflowStep } from '../../../types/agent-workflows'++function workflowOf(id: string, name: string, steps: WorkflowStep[]): AgentWorkflow {+ return { id, name, description: '', icon: 'Zap', steps, variables: {}, isBuiltIn: false, createdAt: 0, updatedAt: 0 }+}++beforeEach(() => {+ registerBuiltinTools(toolRegistry)+ useModelStore.setState({ activeModel: 'anthropic::claude' })+ const asksFirst = workflowOf('id-ask', 'Asks First', [+ { id: 's1', type: 'user_input', label: 'Ask', userInputPrompt: 'What topic?' },+ { id: 's2', type: 'memory_save', label: 'Save', memorySave: { type: 'reference', titleTemplate: '{{user_input}}', contentTemplate: '{{user_input}}', tags: [] } },+ ])+ const noAsk = workflowOf('id-noask', 'No Ask', [+ { id: 's1', type: 'memory_save', label: 'Save', memorySave: { type: 'reference', titleTemplate: 'x', contentTemplate: 'y', tags: [] } },+ ])+ useAgentWorkflowStore.setState({ workflows: [asksFirst, noAsk] })+})++describe('ein Ablauf mit user_input-Schritt ohne input: sofortiger Fehler statt Haengen', () => {+ it('run_workflow({ name }) ohne input liefert einen englischen Fehler, kein Haengen', async () => {+ const output = await toolRegistry.execute('run_workflow', { name: 'Asks First' })++ expect(output).toMatch(/^Error:/)+ expect(output).toMatch(/What topic\?/)+ expect(output).toMatch(/input/i)+ })++ it('NEGATIVKONTROLLE: mit input laeuft derselbe Ablauf ganz normal durch', async () => {+ const output = await toolRegistry.execute('run_workflow', { name: 'Asks First', input: 'quantum computing' })++ expect(output).not.toMatch(/^Error:/)+ })++ it('ein Ablauf ganz ohne user_input-Schritt braucht weiterhin kein input', async () => {+ const output = await toolRegistry.execute('run_workflow', { name: 'No Ask' })++ expect(output).not.toMatch(/^Error:/)+ })+})diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.tsindex 3ccf7536..c6f5b5b1 100644--- a/src/api/mcp/builtin-tools.ts+++ b/src/api/mcp/builtin-tools.ts@@ -465,12 +465,12 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = ['Execute a saved agent workflow by name. Runs a nested ReAct with a pre-built step chain. '+ 'USE for repeatable multi-step tasks: "Research Topic", "Summarize URL", "Code Review", plus any user-created workflows. '+ 'DO NOT call from inside another workflow tool — depth capped at 5 to prevent recursion fork-bombs. '- + 'Pass optional input as the starting variable. If the name is unknown, the error lists available names.',+ + 'input answers the first user_input step or fails fast; else seeds user_input/last_output.',inputSchema: {type: 'object',properties: {name: { type: 'string', description: 'Name of the workflow (case-insensitive match)' },- input: { type: 'string', description: 'Initial input passed as user_input / last_output' },+ input: { type: 'string', description: 'Answers first user_input step; else seeds user_input/last_output.' },},required: ['name'],},@@ -1572,6 +1572,17 @@ async function executeRunWorkflow(args: ToolArgs, run?: AgentRunContext): Promisreturn `Error: Workflow "${workflowName}" not found. Available: ${available}`}+ // R2, bau/review-wfgate.md klein 2: a workflow with a user_input step+ // cannot be answered mid-run (neither this executor nor the chat trigger+ // wires anything to provideUserInput), so without `input` the FIRST such+ // step would wait forever, all three built-in workflows included. Fail+ // immediately with a message the model can act on instead of hanging and+ // holding the lane on a question nobody will ever answer.+ const firstAsk = workflow.steps.find(s => s.type === 'user_input')+ if (firstAsk && !args.input) {+ return `Error: Workflow "${workflow.name}" starts by asking "${firstAsk.userInputPrompt || 'for input'}", and nothing can answer that while it runs. Call run_workflow again with an "input" argument that answers it.`+ }+const results: StepResult[] = []let finalOutput = ''// Auflage 4, bau/review-wfgate.md: a no-op `onStepError` (the old body)diff --git a/src/hooks/__tests__/workflow-trigger-echtes-gate-und-stop.test.ts b/src/hooks/__tests__/workflow-trigger-echtes-gate-und-stop.test.tsindex e78cd74d..623cb554 100644--- a/src/hooks/__tests__/workflow-trigger-echtes-gate-und-stop.test.ts+++ b/src/hooks/__tests__/workflow-trigger-echtes-gate-und-stop.test.ts@@ -70,6 +70,29 @@ function guardWorkflow() {}}+/** bau/review-wfgate.md Runde 2, klein 1: a workflow whose first step+ * genuinely asks a question, to test the chat trigger's colon syntax and+ * its up-front refusal when no answer is given at all. */+function guardAskWorkflow() {+ return {+ id: 'guard-wf-ask',+ name: 'Guard Ask Workflow',+ description: '',+ icon: 'Zap',+ steps: [+ { id: 's1', type: 'user_input' as const, label: 'Ask', userInputPrompt: 'What topic?' },+ {+ id: 's2', type: 'memory_save' as const, label: 'Save',+ memorySave: { type: 'reference' as const, titleTemplate: '{{user_input}}', contentTemplate: '{{user_input}}', tags: [] },+ },+ ],+ variables: {},+ isBuiltIn: false,+ createdAt: 0,+ updatedAt: 0,+ }+}+beforeEach(() => {registerBuiltinTools(toolRegistry)__resetRunStopsForTests()@@ -88,7 +111,7 @@ beforeEach(() => {providers: { ...s.providers, openai: { ...s.providers.openai, enabled: true } },}))useModelStore.setState({ models: [], activeModel: MODEL })- useAgentWorkflowStore.setState({ workflows: [guardWorkflow()] })+ useAgentWorkflowStore.setState({ workflows: [guardWorkflow(), guardAskWorkflow()] })})afterEach(() => {@@ -143,3 +166,41 @@ describe('Auflage 8: Stop erreicht den Chat-ausgeloesten Ablauf', () => {expect(__activeAgentRunConvIdsForTests()).not.toContain(convId)})})++describe('klein 1: "run workflow <name>: <input>" beantwortet den ersten user_input-Schritt', () => {+ it('ohne Doppelpunkt-Eingabe wird sauber abgewiesen statt zu haengen', async () => {+ const { result } = renderHook(() => useAgentChat())+ const convId = seed()++ await act(async () => {+ await result.current.sendAgentMessage('run workflow Guard Ask Workflow')+ await tick()+ })++ // NEGATIVKONTROLLE fuer klein 1 selbst: vor dem Fix haette dieser Aufruf+ // die Engine gestartet, die am user_input-Schritt fuer immer wartet+ // (nichts ruft `provideUserInput`), und den Lauf registriert gelassen.+ expect(__activeAgentRunConvIdsForTests()).not.toContain(convId)+ const conv = useChatStore.getState().conversations.find((c) => c.id === convId)!+ const lastAssistant = [...conv.messages].reverse().find((m) => m.role === 'assistant')!+ expect(lastAssistant.content).toMatch(/What topic\?/)+ expect(lastAssistant.content).toMatch(/run workflow Guard Ask Workflow:/)+ })++ it('mit "run workflow X: <eingabe>" beantwortet der Text nach dem Doppelpunkt den ersten Schritt, der Ablauf laeuft durch', async () => {+ const { result } = renderHook(() => useAgentChat())+ const convId = seed()++ await act(async () => {+ await result.current.sendAgentMessage('run workflow Guard Ask Workflow: quantum computing')+ await tick()+ await tick()+ })++ expect(__activeAgentRunConvIdsForTests()).not.toContain(convId)+ const conv = useChatStore.getState().conversations.find((c) => c.id === convId)!+ const lastAssistant = [...conv.messages].reverse().find((m) => m.role === 'assistant')!+ expect(lastAssistant.content).not.toMatch(/What topic\?/)+ expect(lastAssistant.content).toMatch(/Saved to memory: quantum computing/)+ })+})diff --git a/src/hooks/__tests__/workflow-trigger-verdraengt-keinen-laufenden-zug.test.ts b/src/hooks/__tests__/workflow-trigger-verdraengt-keinen-laufenden-zug.test.tsnew file mode 100644index 00000000..c0dc0960--- /dev/null+++ b/src/hooks/__tests__/workflow-trigger-verdraengt-keinen-laufenden-zug.test.ts@@ -0,0 +1,174 @@+/**+ * @vitest-environment jsdom+ *+ * bau/review-wfgate.md Runde 2, R2-1 (blockierend): the "run workflow+ * <name>" trigger registered its OWN `AgentRunState` in `activeAgentRuns`+ * BEFORE the standard re-entry guard (`activeAgentRuns.has(convId)`, further+ * down in `sendAgentMessage`) ever ran. A workflow message sent to a+ * conversation that already had a live agent turn running overwrote that+ * turn's entry: `stopAgent` then found only the workflow's `AgentRunState`,+ * and the displaced turn's own `finally` deleted ITS entry back out of the+ * map on completion, orphaning the running turn's abort handle entirely+ * (unreachable by Stop from that point on).+ *+ * This test drives a real streaming agent turn (task-A) via a controllable+ * SSE body, sends "run workflow ..." to the SAME conversation while it is+ * still streaming, and checks: the workflow is refused (no side effects, no+ * chat messages of its own), the ORIGINAL run stays the one entry in+ * `activeAgentRuns`, and it is still genuinely stoppable afterward (Stop+ * actually reaches the still-open SSE stream).+ *+ * Run: npx vitest run src/hooks/__tests__/workflow-trigger-verdraengt-keinen-laufenden-zug.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 { useAgentModeStore } from '../../stores/agentModeStore'+import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'+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 { toolRegistry, registerBuiltinTools } from '../../api/mcp'+import { log } from '../../lib/logger'++const MODEL = 'openai::local-builtin-model'++function controllableSSE() {+ let controller!: ReadableStreamDefaultController<Uint8Array>+ const readable = new ReadableStream<Uint8Array>({ start(c) { controller = c } })+ const enc = new TextEncoder()+ return {+ readable,+ pushContent(text: string) {+ controller.enqueue(enc.encode(`data: ${JSON.stringify({ choices: [{ delta: { content: text } }] })}\n\n`))+ },+ done() {+ controller.enqueue(enc.encode('data: [DONE]\n\n'))+ controller.close()+ },+ }+}++const tick = () => new Promise((r) => setTimeout(r, 0))++function seed(): string {+ const convId = useChatStore.getState().createConversation(MODEL, '')+ useChatStore.getState().setActiveConversation(convId)+ useAgentModeStore.getState().setAgentModeActive(convId, true)+ return convId+}++function guardWorkflow() {+ return {+ id: 'guard-wf-r2-1',+ name: 'Guard Displace Workflow',+ description: '',+ icon: 'Zap',+ steps: [{ id: 's1', type: 'memory_save' as const, label: 'save', memorySave: { type: 'reference' as const, titleTemplate: 't', contentTemplate: 'c', tags: [] } }],+ variables: {},+ isBuiltIn: false,+ createdAt: 0,+ updatedAt: 0,+ }+}++beforeEach(() => {+ registerBuiltinTools(toolRegistry)+ __resetRunStopsForTests()+ useChatStore.setState({ conversations: [], activeConversationId: null })+ useAgentTaskStore.setState({ byConv: {} })+ useAgentLoopStore.setState({ loops: {} })+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })+ useAgentModeStore.setState({ agentModeActive: {} })+ useTodoStore.setState({ byConversation: {}, updatedAt: {} })+ useToolAuditStore.setState({ entries: {} })+ useAgentWorkflowStore.setState({ workflows: [guardWorkflow()] })+ 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 })+})+afterEach(() => vi.restoreAllMocks())++describe('R2-1: ein "run workflow" mitten in einem laufenden Agentenzug derselben Unterhaltung', () => {+ it('wird abgewiesen, ohne den laufenden Zug zu verdraengen, und der laeuft danach immer noch stoppbar', async () => {+ const convId = seed()+ const streamA = controllableSSE()+ let callsA = 0++ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input)+ if (!url.includes('/chat/completions')) return new Response('{}', { status: 200 })+ const body = String(init?.body ?? '')+ if (body.includes('task-A')) {+ callsA+++ return new Response(streamA.readable, { status: 200, headers: { 'content-type': 'text/event-stream' } })+ }+ throw new Error('unexpected request body during this test: ' + body.slice(0, 200))+ })+ const logSpy = vi.spyOn(log, 'info')++ const { result } = renderHook(() => useAgentChat())++ let runA!: Promise<void>+ await act(async () => {+ runA = result.current.sendAgentMessage('task-A')+ await tick()+ })++ expect(callsA).toBe(1)+ expect(__activeAgentRunConvIdsForTests()).toEqual([convId])++ // NEGATIVKONTROLLE fuer R2-1 selbst: vor dem Fix haette dieser Aufruf+ // `activeAgentRuns.set(convId, workflowRunState)` OHNE Pruefung+ // ausgefuehrt und damit den laufenden Zug aus dem Register verdraengt.+ await act(async () => {+ await result.current.sendAgentMessage('run workflow Guard Displace Workflow')+ await tick()+ })++ expect(logSpy).toHaveBeenCalledWith('agent.duplicate_send_blocked', expect.objectContaining({ convId }))+ const conv = useChatStore.getState().conversations.find((c) => c.id === convId)!+ expect(conv.messages.some((m) => m.content.includes('Running workflow'))).toBe(false)+ // Genau EIN Eintrag, und es ist immer noch der urspruengliche Zug, nicht+ // durch den Ablauf ersetzt worden.+ expect(__activeAgentRunConvIdsForTests()).toEqual([convId])++ // Stoppbarkeit: Stop muss den urspruenglichen, noch offenen SSE-Strom+ // wirklich erreichen, nicht einen verwaisten Griff.+ await act(async () => {+ result.current.stopAgent(convId)+ streamA.done()+ await runA+ await tick()+ })++ expect(__activeAgentRunConvIdsForTests()).toEqual([])+ })+})diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 0bd6c72c..dc971836 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -312,9 +312,15 @@ export function useAgentChat() {if (!activeModel) return// ── Workflow trigger detection ──────────────────────────- const workflowMatch = userContent.match(/^run\s+workflow\s+(.+)$/i)+ // R2, bau/review-wfgate.md klein 1: "run workflow <name>: <input>" lets+ // the text after the FIRST colon answer the workflow's first+ // `user_input` step, the same convention `run_workflow`'s own `input`+ // argument uses (builtin-tools.ts). Optional and non-greedy on the name+ // so a colon-free name still matches unchanged.+ const workflowMatch = userContent.match(/^run\s+workflow\s+([^:]+?)\s*(?::\s*([\s\S]*))?$/i)if (workflowMatch) {const workflowName = workflowMatch[1].trim()+ const workflowInput = workflowMatch[2]?.trim()const wfStore = useAgentWorkflowStore.getState()const workflow = wfStore.workflows.find(w => w.name.toLowerCase() === workflowName.toLowerCase()@@ -325,6 +331,45 @@ export function useAgentChat() {if (!convId) {convId = store.createConversation(activeModel, persona?.systemPrompt || '')}++ // R2-1, bau/review-wfgate.md (blockierend): `activeAgentRuns` is the+ // re-entry guard documented above (a key present means THIS+ // conversation already has a live run), and this trigger used to+ // register its OWN run before that check ever ran, below at the+ // guard for the normal send path. A workflow started while an+ // ordinary agent turn (or a second workflow) was already running in+ // the SAME conversation overwrote that turn's `AgentRunState` in the+ // map: `stopAgent` then found only the new workflow, and the+ // displaced turn's own `finally` removed the entry out from under+ // it, orphaning its abort handle entirely. Same check as the+ // existing guard, moved in front of every side effect this trigger+ // has (the chat messages included), so a "run workflow" sent while a+ // turn is live is cleanly refused instead of stealing its slot.+ if (activeAgentRuns.has(convId)) {+ log.info('agent.duplicate_send_blocked', { activeModel, convId })+ return+ }++ // R2, bau/review-wfgate.md klein 1/2: a workflow that asks a+ // question (`user_input`) cannot be answered while it runs -+ // neither this trigger nor `run_workflow` wires anything to+ // `provideUserInput`, so without a prefilled answer the FIRST such+ // step would wait forever, stoppable only by hand. Refuse up front+ // with the fix instead of starting a run nobody can finish.+ const firstAsk = workflow.steps.find(s => s.type === 'user_input')+ if (firstAsk && !workflowInput) {+ useChatStore.getState().addMessage(convId, {+ id: uuid(), role: 'user', content: userContent, timestamp: Date.now(),+ })+ useChatStore.getState().addMessage(convId, {+ id: uuid(),+ role: 'assistant',+ content: `Workflow "${workflow.name}" starts by asking "${firstAsk.userInputPrompt || 'for input'}", and nothing can answer that while it runs. Send "run workflow ${workflow.name}: <your answer>" to provide it up front.`,+ timestamp: Date.now(),+ })+ return+ }+useChatStore.getState().addMessage(convId, {id: uuid(), role: 'user', content: userContent, timestamp: Date.now(),})@@ -396,7 +441,15 @@ export function useAgentChat() {artifacts: [],abortSignal: workflowAbort.signal,})- const engine = new WorkflowEngine(workflow, convId, callbacks, gates.awaitApproval)+ // `workflowInput` (the text after "run workflow <name>:") answers+ // this run's first `user_input` step the same way `run_workflow`'s+ // own `input` argument does (klein 1 above); `undefined` when the+ // workflow needs no answer at all, matched by the `!firstAsk` branch+ // that skipped the refusal above.+ const initialVars: Record<string, string> | undefined = workflowInput+ ? { user_input: workflowInput, last_output: workflowInput }+ : undefined+ const 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)diff --git a/src/lib/workflow-engine.ts b/src/lib/workflow-engine.tsindex b1d9da3a..3dd27fd7 100644--- a/src/lib/workflow-engine.ts+++ b/src/lib/workflow-engine.ts@@ -492,6 +492,26 @@ export class WorkflowEngine {/*** Provide user input for a waiting user_input step.+ *+ * bau/review-wfgate.md Runde 2, klein 3: neither surviving caller+ * (`run_workflow`'s `executeRunWorkflow`, the "run workflow <name>" chat+ * trigger) ever calls this, and both now refuse UP FRONT+ * (`executeUserInputStep` below, and the callers' own pre-checks) when a+ * workflow's FIRST `user_input` step has no prefilled answer, closing the+ * hang the review measured for all three built-in workflows. Kept rather+ * than deleted: a workflow with a SECOND `user_input` step still reaches+ * this exact wait after its first step consumes the one prefilled value+ * (see `workflow-user-input-vorbefuellt.test.ts`'s third case), a real,+ * if narrow, gap neither caller's up-front check catches, since it only+ * looks at whether the workflow has a question at all, not how many.+ * This method is the only way anything could ever answer that second+ * question; deleting it would turn a stoppable wait into a permanently+ * unanswerable one instead of closing it. It also still backs the lane+ * tests that use a `user_input` step purely as a controllable pause point+ * (`workflow-engine-lane.test.ts`, `background-shutdown-lanes.test.ts`),+ * unrelated to `user_input`'s own semantics: rebuilding those around a+ * different pausable step type instead is a fair follow-up, not done+ * here.*/provideUserInput(input: string) {if (this.inputResolver) {@@ -815,7 +835,13 @@ export class WorkflowEngine {// (builtin-tools.ts's `initialVars`), so the FIRST `user_input` step can// read it directly instead of waiting. Consumed at most once: a second// `user_input` step in a custom workflow still genuinely waits, since- // only one caller-supplied value exists.+ // only one caller-supplied value exists. Runde 2 fix (klein 1/2,+ // bau/review-wfgate.md): both callers now refuse UP FRONT, before this+ // engine even starts, when a workflow has a `user_input` step and no+ // answer was given at all, so THIS wait branch is unreachable through+ // either surviving caller for that case; only a workflow with a SECOND+ // `user_input` step (after the first already consumed the one supplied+ // value) still reaches it, see `provideUserInput`'s own doc comment.if (this.prefilledUserInput !== undefined) {const input = this.prefilledUserInputthis.prefilledUserInput = undefined