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): route the workflow gate through the real surface, identity and Stop
purple9a7bb03f7c45
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.tsindex 56715662..3ccf7536 100644--- a/src/api/mcp/builtin-tools.ts+++ b/src/api/mcp/builtin-tools.ts@@ -1574,12 +1574,31 @@ async function executeRunWorkflow(args: ToolArgs, run?: AgentRunContext): Promisconst results: StepResult[] = []let finalOutput = ''+ // Auflage 4, bau/review-wfgate.md: a no-op `onStepError` (the old body)+ // left `finalOutput` empty on a rejected approval, so `run_workflow`+ // returned '' to the model, no sign the user said no, and it just tried+ // again. `runSteps` (workflow-engine.ts) calls `onStepError` and BREAKS+ // the step loop on a failure, but still calls `onComplete` afterward (it+ // is not the same as `onError`, which fires only on a thrown exception),+ // and that handler's own fallback ("Workflow completed with no output.")+ // would otherwise silently overwrite the error message set here, since a+ // failed step's own `output` is '' and gets filtered out by+ // `results.filter(r => r.output)`. `hadStepError` keeps `onComplete` from+ // clobbering it.+ let hadStepError = falseconst callbacks = {onStepStart: () => {},onStepComplete: (_idx: number, result: StepResult) => { results.push(result) },- onStepError: () => {},+ onStepError: (_idx: number, error: string) => {+ hadStepError = true+ // The step's own `error` is already the gate's English message+ // ("Tool call rejected: ... was not approved.", `gatedApproval` in+ // workflow-engine.ts).+ finalOutput = `Workflow error: ${error}`+ },onWaitingForInput: () => {},onComplete: () => {+ if (hadStepError) returnconst lastOutput = results.filter(r => r.output).pop()finalOutput = lastOutput?.output || 'Workflow completed with no output.'},@@ -1621,7 +1640,14 @@ async function executeRunWorkflow(args: ToolArgs, run?: AgentRunContext): Promis// `confirm` tool inside the workflow still asks, on the same queue the// rest of Agent mode uses.const approve = buildWorkflowApprovalGate(run)- const engine = new WorkflowEngine(workflow, 'tool-execution', callbacks, approve, initialVars, _workflowDepth, run?.heldLocalLane ?? null)+ // `run` itself is also passed as `invokingRun` (Auflage 2,+ // bau/review-wfgate.md): 'tool-execution' above is only a lane-booking+ // placeholder, not a real conversation, so IF this workflow's own step+ // calls `run_workflow` again, the nested engine needs the REAL outer+ // `run` (its conversation, `abortSignal`, `mode`) to build that+ // third-level call's context from, not this placeholder. See+ // `effectiveOuterRun`/`effectiveConversationId` in workflow-engine.ts.+ const engine = new WorkflowEngine(workflow, 'tool-execution', callbacks, approve, initialVars, _workflowDepth, run?.heldLocalLane ?? null, run)await engine.run()} finally {_workflowDepth--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.tsnew file mode 100644index 00000000..e78cd74d--- /dev/null+++ b/src/hooks/__tests__/workflow-trigger-echtes-gate-und-stop.test.ts@@ -0,0 +1,145 @@+/**+ * @vitest-environment jsdom+ *+ * bau/review-wfgate.md, Auflage 3 (Waechter je Aufrufstelle) und Auflage 8+ * (Chat-Ausloeser ohne Abbruchsignal): the "run workflow <name>" chat trigger+ * in useAgentChat.ts is the SECOND caller of `WorkflowEngine` (the first is+ * `run_workflow` itself, guarded in build-workflow-approval-gate.test.ts). A+ * future silent swap of `gates.awaitApproval` for `APPROVE_ALL` here must+ * fail a test, and Stop must actually reach this run (it did not before:+ * no `abortSignal` was built, and the run was never registered so `stopAgent`+ * had nothing to call `.abort()` on).+ *+ * Run: npx vitest run src/hooks/__tests__/workflow-trigger-echtes-gate-und-stop.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'++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+}++function guardWorkflow() {+ return {+ id: 'guard-wf-chat',+ name: 'Guard Chat Workflow',+ 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,+ }+}++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: [guardWorkflow()] })+})++afterEach(() => {+ usePermissionStore.getState().resetToDefaults()+ vi.restoreAllMocks()+})++describe('Waechter: der Chat-Ausloeser "run workflow <name>" uebergibt ein ECHTES Gate', () => {+ it('ein blockiertes Werkzeug im Ablauf laeuft nie, auch nicht ueber den Chat-Ausloeser', async () => {+ usePermissionStore.getState().setGlobalPermission('terminal', 'blocked')+ const execSpy = vi.spyOn(toolRegistry, 'execute')++ const { result } = renderHook(() => useAgentChat())+ const convId = seed()++ await act(async () => {+ await result.current.sendAgentMessage('run workflow Guard Chat Workflow')+ await tick()+ })++ expect(execSpy.mock.calls.map((c) => c[0])).not.toContain('shell_execute')+ const conv = useChatStore.getState().conversations.find((c) => c.id === convId)!+ const lastAssistant = [...conv.messages].reverse().find((m) => m.role === 'assistant')!+ expect(lastAssistant.content).toMatch(/Workflow error/)+ })+})++describe('Auflage 8: Stop erreicht den Chat-ausgeloesten Ablauf', () => {+ it('waehrend einer wartenden Freigabe registriert der Ausloeser den Lauf, und Stop raeumt die Warteschlange ab', 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 Guard Chat Workflow')+ await tick()+ await tick()++ // The run is registered (Auflage 8's fix) and its approval is+ // sitting in the queue under the REAL conversation.+ expect(__activeAgentRunConvIdsForTests()).toContain(convId)+ expect(headApproval(convId)).not.toBeNull()++ 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 f5c4c7c5..0bd6c72c 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -336,7 +336,19 @@ export function useAgentChat() {const callbacks: WorkflowEngineCallbacks = {onStepStart: () => {},onStepComplete: (_i, r) => { results.push(r) },- onStepError: () => {},+ // Same fix as Auflage 4, bau/review-wfgate.md (builtin-tools.ts's+ // `executeRunWorkflow`): `runSteps` calls `onStepError` and then+ // breaks WITHOUT calling `onComplete` or `onError`, so a no-op+ // here left a rejected approval's chat turn with no message at+ // all, the same silent-failure shape the review flagged for the+ // `run_workflow` tool's return value.+ onStepError: (_i, error) => {+ if (convId) {+ useChatStore.getState().addMessage(convId, {+ id: uuid(), role: 'assistant', content: `Workflow error: ${error}`, timestamp: Date.now(),+ })+ }+ },onWaitingForInput: () => {},onComplete: () => {const lastOutput = results.filter(r => r.output).pop()@@ -362,6 +374,17 @@ export function useAgentChat() {// 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,@@ -371,9 +394,21 @@ export function useAgentChat() {readOnlyShellTurn: false,mode: null,artifacts: [],+ abortSignal: workflowAbort.signal,})const engine = new WorkflowEngine(workflow, convId, callbacks, gates.awaitApproval)- await engine.run()+ workflowAbort.signal.addEventListener('abort', () => engine.cancel(), { once: true })+ const workflowRunState: AgentRunState = { convId, content: '', thinking: '', blocks: [], abort: workflowAbort }+ activeAgentRuns.set(convId, workflowRunState)+ setIsAgentRunning(true)+ try {+ await engine.run()+ } finally {+ if (activeAgentRuns.get(convId) === workflowRunState) {+ activeAgentRuns.delete(convId)+ setIsAgentRunning(activeAgentRuns.size > 0)+ }+ }return}}diff --git a/src/lib/__tests__/build-workflow-approval-gate.test.ts b/src/lib/__tests__/build-workflow-approval-gate.test.tsnew file mode 100644index 00000000..b87cb3be--- /dev/null+++ b/src/lib/__tests__/build-workflow-approval-gate.test.ts@@ -0,0 +1,219 @@+/**+ * bau/review-wfgate.md Auflage 3: `buildWorkflowApprovalGate`+ * (workflow-engine.ts) had zero direct tests, only the five cases in+ * workflow-engine-approval-gate.test.ts, which exercise the ENGINE with+ * `APPROVE_ALL`, a rejecting stub and `buildSubAgentGates`, never this+ * function itself. This file tests the gate builder directly: 'blocked',+ * 'auto', the chat queue's 'confirm', the Code tab's 'confirm' (Auflage 1),+ * no-conversation fail-closed, and abort cleanup.+ *+ * Each case names its negative control (what fails without the Round 2 fix,+ * bau/wfgate.md "Runde 2" carries the numbers).+ *+ * Run: npx vitest run src/lib/__tests__/build-workflow-approval-gate.test.ts+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { buildWorkflowApprovalGate } from '../workflow-engine'+import { usePermissionStore } from '../../stores/permissionStore'+import { headApproval, dequeueApproval, resetApprovals } from '../approval-queue'+import { useCodexConfirmStore } from '../../stores/codexConfirmStore'+import { toolRegistry, registerBuiltinTools } from '../../api/mcp'+import type { AgentRunContext } from '../../api/agent-context'+import type { ExecutorToolDef, ExecutionRequest } from '../../api/agents/tool-executor'++const TOOL: ExecutorToolDef = { name: 'shell_execute' }++function makeRun(over: Partial<AgentRunContext> = {}): AgentRunContext {+ return {+ token: 'wf-test',+ chatId: null,+ conversationId: 'conv-1',+ workspace: null,+ artifactMode: false,+ readOnlyShellTurn: false,+ mode: null,+ artifacts: [],+ ...over,+ }+}++beforeEach(() => {+ registerBuiltinTools(toolRegistry)+ resetApprovals()+ useCodexConfirmStore.setState({ pending: null, resolve: null })+})++afterEach(() => {+ usePermissionStore.getState().resetToDefaults()+ vi.restoreAllMocks()+})++describe("'blocked': das Gate lehnt sofort ab, ohne je einzureihen", () => {+ it('shell_execute mit Kategorie terminal=blocked liefert false und reiht nichts ein', async () => {+ usePermissionStore.getState().setGlobalPermission('terminal', 'blocked')+ const gate = buildWorkflowApprovalGate(makeRun())++ const approved = await gate(+ { id: 'r1', toolName: 'shell_execute', args: { command: 'echo hi' }, run: undefined } as ExecutionRequest,+ TOOL,+ )++ expect(approved).toBe(false)+ expect(headApproval('conv-1')).toBeNull()+ })+})++describe("'auto': das Gate laesst sofort durch", () => {+ it('shell_execute mit Kategorie terminal=auto liefert true ohne Warteschlange', async () => {+ usePermissionStore.getState().setGlobalPermission('terminal', 'auto')+ const gate = buildWorkflowApprovalGate(makeRun())++ const approved = await gate(+ { id: 'r2', toolName: 'shell_execute', args: { command: 'echo hi' }, run: undefined } as ExecutionRequest,+ TOOL,+ )++ expect(approved).toBe(true)+ expect(headApproval('conv-1')).toBeNull()+ })+})++describe("'confirm' ohne mode: die Frage geht in die Chat-Warteschlange (approval-queue.ts)", () => {+ it('reiht unter der echten conversationId ein, und ein Klick loest auf', async () => {+ usePermissionStore.getState().setGlobalPermission('terminal', 'confirm')+ const gate = buildWorkflowApprovalGate(makeRun({ conversationId: 'conv-chat' }))++ const promise = gate(+ { id: 'r3', toolName: 'shell_execute', args: { command: 'echo hi' }, run: undefined } as ExecutionRequest,+ TOOL,+ )+ // Give the microtask queue a turn so `enqueueApproval` has run.+ await Promise.resolve()+ await Promise.resolve()++ const head = headApproval('conv-chat')+ expect(head).not.toBeNull()+ expect(head!.toolName).toBe('shell_execute')+ expect(useCodexConfirmStore.getState().pending).toBeNull()++ dequeueApproval('conv-chat')?.resolve(true)+ await expect(promise).resolves.toBe(true)+ })++ it('NEGATIVKONTROLLE ohne conversationId: faellt geschlossen aus (false), reiht nichts ein', async () => {+ usePermissionStore.getState().setGlobalPermission('terminal', 'confirm')+ const gate = buildWorkflowApprovalGate(makeRun({ conversationId: null }))++ const approved = await gate(+ { id: 'r4', toolName: 'shell_execute', args: { command: 'echo hi' }, run: undefined } as ExecutionRequest,+ TOOL,+ )++ expect(approved).toBe(false)+ })+})++describe("Auflage 1: 'confirm' MIT run.mode geht ueber codexConfirmStore, NICHT die Chat-Warteschlange", () => {+ it('run.mode gesetzt (Code-Tab/Sub-Agent): fragt useCodexConfirmStore, die Chat-Warteschlange bleibt leer', async () => {+ usePermissionStore.getState().setGlobalPermission('terminal', 'auto')+ // execConfirm true + mode set is what actually drives resolveApprovalLevel+ // to 'confirm' for an arbitrary-exec tool on the Code tab (see+ // agent-approval-policy.ts): the category itself may be 'auto' there,+ // since the Code tab does not read it at all once `codexMode` is set.+ const run = makeRun({ mode: 'ask', execApproval: { confirmExec: true, cloudReason: false }, conversationId: 'conv-code' })+ const gate = buildWorkflowApprovalGate(run)++ const promise = gate(+ { id: 'r5', toolName: 'shell_execute', args: { command: 'rm -rf /tmp/x' }, run: undefined } as ExecutionRequest,+ TOOL,+ )++ for (let i = 0; i < 50 && !useCodexConfirmStore.getState().pending; i++) await Promise.resolve()+ const pending = useCodexConfirmStore.getState().pending+ expect(pending).not.toBeNull()+ expect(pending!.toolName).toBe('shell_execute')+ expect(pending!.command).toMatch(/rm -rf \/tmp\/x/)+ // NEGATIVKONTROLLE, exactly what Auflage 1 says the pre-fix code did:+ // the question also must NOT additionally sit in the chat queue nobody+ // in the Code tab reads.+ expect(headApproval('conv-code')).toBeNull()++ useCodexConfirmStore.getState().answer(true)+ await expect(promise).resolves.toBe(true)+ })++ it('NEGATIVKONTROLLE: dieselbe Frage bei No lehnt ab, ohne die Chat-Warteschlange zu benutzen', async () => {+ usePermissionStore.getState().setGlobalPermission('terminal', 'auto')+ const run = makeRun({ mode: 'ask', execApproval: { confirmExec: true, cloudReason: false }, conversationId: 'conv-code-2' })+ const gate = buildWorkflowApprovalGate(run)++ const promise = gate(+ { id: 'r6', toolName: 'shell_execute', args: { command: 'echo hi' }, run: undefined } as ExecutionRequest,+ TOOL,+ )+ for (let i = 0; i < 50 && !useCodexConfirmStore.getState().pending; i++) await Promise.resolve()+ useCodexConfirmStore.getState().answer(false)++ await expect(promise).resolves.toBe(false)+ expect(headApproval('conv-code-2')).toBeNull()+ })+})++describe('Abbruch waehrend wartender Freigabe raeumt den Warteschlangen-Eintrag ab', () => {+ it('abortSignal.abort() loest die wartende Chat-Freigabe mit false auf und entfernt sie', async () => {+ usePermissionStore.getState().setGlobalPermission('terminal', 'confirm')+ const controller = new AbortController()+ const gate = buildWorkflowApprovalGate(makeRun({ conversationId: 'conv-abort', abortSignal: controller.signal }))++ const promise = gate(+ { id: 'r7', toolName: 'shell_execute', args: { command: 'echo hi' }, run: undefined } as ExecutionRequest,+ TOOL,+ )+ await Promise.resolve()+ await Promise.resolve()+ expect(headApproval('conv-abort')).not.toBeNull()++ controller.abort()++ await expect(promise).resolves.toBe(false)+ expect(headApproval('conv-abort')).toBeNull()+ })+})++describe('Waechter: `run_workflow` (builtin-tools.ts) uebergibt ein ECHTES Gate, kein APPROVE_ALL', () => {+ it('ein blockiertes Werkzeug in einem Werkzeugschritt laeuft NIE, auch nicht ueber run_workflow', async () => {+ // A future silent swap of `buildWorkflowApprovalGate(run)` for+ // `APPROVE_ALL` in builtin-tools.ts's `executeRunWorkflow` would let+ // this pass: this test is the guard the review's Auflage 3 asks for.+ const { useAgentWorkflowStore } = await import('../../stores/agentWorkflowStore')+ useAgentWorkflowStore.setState({+ workflows: [{+ id: 'guard-wf',+ name: 'Guard Workflow',+ 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,+ }],+ })+ usePermissionStore.getState().setGlobalPermission('terminal', 'blocked')+ const execSpy = vi.spyOn(toolRegistry, 'execute')++ const output = await toolRegistry.execute(+ 'run_workflow',+ { name: 'Guard Workflow' },+ 1,+ makeRun({ conversationId: 'conv-guard' }),+ )++ // toolRegistry.execute is called once for `run_workflow` itself (the+ // spy sees its own outer call too); shell_execute must never be among+ // the calls the workflow's own step made.+ expect(execSpy.mock.calls.map((c) => c[0])).not.toContain('shell_execute')+ expect(output).toMatch(/Workflow error/)+ expect(output).toMatch(/not approved|rejected/i)+ })+})diff --git a/src/lib/__tests__/workflow-engine-echte-kennung-bei-drittem-grad.test.ts b/src/lib/__tests__/workflow-engine-echte-kennung-bei-drittem-grad.test.tsnew file mode 100644index 00000000..3d9943c3--- /dev/null+++ b/src/lib/__tests__/workflow-engine-echte-kennung-bei-drittem-grad.test.ts@@ -0,0 +1,104 @@+/**+ * bau/review-wfgate.md Auflage 2: ein Werkzeugschritt, der `run_workflow`+ * aufruft, hat der ZWEITEN Engine bisher `conversationId: this.conversationId`+ * mitgegeben (builtin-tools.ts's `executeRunWorkflow` bucht IMMER unter der+ * erfundenen Kennung `'tool-execution'`, egal wie tief verschachtelt). Ruft+ * DIESE zweite Engine ihrerseits `run_workflow` (DRITTER Grad), bekam die+ * DRITTE Engine also `'tool-execution'` als "echte Unterhaltung" vorgesetzt,+ * eine Kennung, die kein Fenster je anzeigt.+ *+ * Aufbau: eine echte Unterhaltung 'real-conv' ruft `run_workflow('level-b')`+ * auf. `level-b`s einziger Schritt ruft selbst `run_workflow('level-c')`.+ * `level-c`s einziger Schritt ist ein `shell_execute` mit Kategorie+ * 'confirm'. Die Frage dazu muss unter 'real-conv' liegen, NIE unter+ * 'tool-execution', sonst kann sie niemand beantworten (headApproval liest+ * nur `activeConversationId`).+ *+ * Lauf: npx vitest run src/lib/__tests__/workflow-engine-echte-kennung-bei-drittem-grad.test.ts+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { toolRegistry, registerBuiltinTools } from '../../api/mcp'+import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'+import { usePermissionStore } from '../../stores/permissionStore'+import { useModelStore } from '../../stores/modelStore'+import { headApproval, dequeueApproval, resetApprovals } from '../approval-queue'+import type { AgentWorkflow, WorkflowStep } from '../../types/agent-workflows'+import type { AgentRunContext } from '../../api/agent-context'++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)+ resetApprovals()+ // Cloud lane: nested run_workflow calls at every level book under the SAME+ // lane-booking string ('tool-execution', unchanged scope of this fix), so+ // a local model would need the ride-along mechanism this test does not+ // exercise. Cloud bookings do not serialize against each other at all.+ useModelStore.setState({ activeModel: 'anthropic::claude' })++ const levelC = workflowOf('id-c', 'level-c', [+ { id: 'shell', type: 'tool', label: 'shell', toolName: 'shell_execute', toolArgs: { command: 'echo hi' } },+ ])+ const levelB = workflowOf('id-b', 'level-b', [+ { id: 'call-c', type: 'tool', label: 'call-c', toolName: 'run_workflow', toolArgs: { name: 'level-c' } },+ ])+ useAgentWorkflowStore.setState({ workflows: [levelB, levelC] })+ usePermissionStore.getState().setGlobalPermission('workflow', 'auto')+ usePermissionStore.getState().setGlobalPermission('terminal', 'confirm')+})++afterEach(() => {+ usePermissionStore.getState().resetToDefaults()+ vi.restoreAllMocks()+})++describe('dritter Verschachtelungsgrad reicht die ECHTE Unterhaltung durch, nicht die Buchungskennung', () => {+ it('die Freigabefrage von level-c liegt unter real-conv, nicht unter tool-execution', async () => {+ const run: AgentRunContext = {+ token: 'wf-real', chatId: null, conversationId: 'real-conv', workspace: null,+ artifactMode: false, readOnlyShellTurn: false, mode: null, artifacts: [],+ }++ const outputPromise = toolRegistry.execute('run_workflow', { name: 'level-b' }, 1, run)++ // Let the two nested engines run until the shell_execute step parks its+ // approval.+ for (let i = 0; i < 200 && !headApproval('real-conv'); i++) await Promise.resolve()++ expect(headApproval('real-conv')).not.toBeNull()+ expect(headApproval('real-conv')!.toolName).toBe('shell_execute')+ // NEGATIVKONTROLLE (was Auflage 2 describes as the pre-fix behaviour):+ // the entry must NOT be sitting under the internal lane-booking string,+ // which no window ever reads.+ expect(headApproval('tool-execution')).toBeNull()++ dequeueApproval('real-conv')?.resolve(true)+ const output = await outputPromise++ // The approval itself is what this test is about, not whatever the real+ // shell_execute backend call does in a test environment with no server+ // behind it (it errors on the network call, a separate, expected+ // failure): the point is that resolving the REAL conversation's approval+ // actually reached this step, so it must NOT still be the rejection this+ // test's own sibling checks for below.+ expect(output).not.toMatch(/not approved|rejected/i)+ })++ it('NEGATIVKONTROLLE: eine Ablehnung unter real-conv erreicht auch tatsaechlich level-c, level-b meldet den Fehler', async () => {+ const run: AgentRunContext = {+ token: 'wf-real-2', chatId: null, conversationId: 'real-conv-2', workspace: null,+ artifactMode: false, readOnlyShellTurn: false, mode: null, artifacts: [],+ }++ const outputPromise = toolRegistry.execute('run_workflow', { name: 'level-b' }, 1, run)+ for (let i = 0; i < 200 && !headApproval('real-conv-2'); i++) await Promise.resolve()++ dequeueApproval('real-conv-2')?.resolve(false)+ const output = await outputPromise++ expect(output).toMatch(/Workflow error/)+ expect(output).toMatch(/not approved|rejected/i)+ })+})diff --git a/src/lib/__tests__/workflow-user-input-vorbefuellt.test.ts b/src/lib/__tests__/workflow-user-input-vorbefuellt.test.tsnew file mode 100644index 00000000..42755a95--- /dev/null+++ b/src/lib/__tests__/workflow-user-input-vorbefuellt.test.ts@@ -0,0 +1,100 @@+/**+ * ZUSATZFRAGE / Auflage 6, bau/review-wfgate.md: alle drei eingebauten+ * Ablaeufe (Research Topic, Summarize URL, Code Review) beginnen mit einem+ * `user_input`-Schritt (built-in-workflows.ts:20,:59,:83). Beide Aufrufer+ * (builtin-tools.ts's `executeRunWorkflow`, useAgentChat.ts's Chat-Ausloeser)+ * setzen `onWaitingForInput: () => {}` und rufen `provideUserInput` nie, also+ * haengt jeder der drei am ersten Schritt, ein Aufloeser, den es nicht mehr+ * gibt. `run_workflow` legt sein eigenes `input`-Argument bereits als+ * `user_input`-Variable an (builtin-tools.ts's `initialVars`); dieser Test+ * belegt, dass die Engine das jetzt fuer den ERSTEN `user_input`-Schritt+ * konsumiert statt zu warten, und dass ein ZWEITER `user_input`-Schritt+ * weiterhin echt wartet (nur EIN vorbefuellter Wert existiert).+ *+ * Lauf: npx vitest run src/lib/__tests__/workflow-user-input-vorbefuellt.test.ts+ */+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { WorkflowEngine } from '../workflow-engine'+import { APPROVE_ALL } from '../../api/agents/tool-executor'+import { __resetRunLanesForTests } from '../run-lanes'+import { useGenerationStore } from '../../stores/generationStore'+import { useModelStore } from '../../stores/modelStore'+import type { AgentWorkflow, WorkflowStep, WorkflowEngineCallbacks } from '../../types/agent-workflows'++function workflowOf(steps: WorkflowStep[]): AgentWorkflow {+ return { id: 'wf', name: 'test', description: '', icon: 'Zap', steps, variables: {}, isBuiltIn: false, createdAt: 0, updatedAt: 0 }+}++function callbacks(waiting: (i: number, p: string) => void = () => {}): WorkflowEngineCallbacks {+ return {+ onStepStart: () => {}, onStepComplete: () => {}, onStepError: () => {},+ onWaitingForInput: waiting, onComplete: () => {}, onError: () => {},+ }+}++beforeEach(() => {+ __resetRunLanesForTests()+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })+ useModelStore.setState({ activeModel: 'anthropic::claude' })+})++describe('ein vorbefuellter user_input Wert wird vom ERSTEN Schritt konsumiert, kein Warten', () => {+ it('run_workflow-Stil: initialVariables.user_input erreicht den Schritt sofort, onWaitingForInput feuert nie', async () => {+ const waiting = vi.fn()+ const step: WorkflowStep = { id: 's1', type: 'user_input', label: 'Ask', userInputPrompt: 'What topic?' }+ const engine = new WorkflowEngine(+ workflowOf([step]), 'conv-prefill', callbacks(waiting), APPROVE_ALL,+ { user_input: 'quantum computing', last_output: 'quantum computing' },+ )++ const results = await engine.run()++ expect(waiting).not.toHaveBeenCalled()+ expect(results).toHaveLength(1)+ expect(results[0].status).toBe('completed')+ expect(results[0].output).toBe('quantum computing')+ })++ it('NEGATIVKONTROLLE: ohne initialVariables.user_input haengt der Schritt am Aufloeser (onWaitingForInput feuert, provideUserInput bleibt der einzige Weg weiter)', async () => {+ const waiting = vi.fn()+ const step: WorkflowStep = { id: 's1', type: 'user_input', label: 'Ask', userInputPrompt: 'What topic?' }+ const engine = new WorkflowEngine(workflowOf([step]), 'conv-no-prefill', callbacks(waiting), APPROVE_ALL)++ const laufend = engine.run()+ for (let i = 0; i < 20; i++) await Promise.resolve()+ expect(waiting).toHaveBeenCalledTimes(1)++ // Genau der Haenge-Zustand, den die ZUSATZFRAGE beschreibt: ohne einen+ // Aufrufer, der `provideUserInput` ruft, bliebe das Promise fuer immer+ // offen. Der Test loest selbst auf, um sich nicht wirklich aufzuhaengen,+ // aber demonstriert damit genau die Luecke.+ engine.provideUserInput('manually answered')+ const results = await laufend+ expect(results[0].output).toBe('manually answered')+ })++ it('ein ZWEITER user_input-Schritt wartet weiterhin echt: nur der ERSTE wird vorbefuellt', async () => {+ const waiting = vi.fn()+ const first: WorkflowStep = { id: 's1', type: 'user_input', label: 'Ask 1', userInputPrompt: 'First?' }+ const second: WorkflowStep = { id: 's2', type: 'user_input', label: 'Ask 2', userInputPrompt: 'Second?' }+ const engine = new WorkflowEngine(+ workflowOf([first, second]), 'conv-second', callbacks(waiting), APPROVE_ALL,+ { user_input: 'first-value' },+ )++ const laufend = engine.run()+ for (let i = 0; i < 20; i++) await Promise.resolve()++ // The first step consumed the prefill without calling onWaitingForInput;+ // the second has nothing left to consume and genuinely waits.+ expect(waiting).toHaveBeenCalledTimes(1)+ expect(waiting).toHaveBeenCalledWith(1, 'Second?')++ engine.provideUserInput('second-value')+ const results = await laufend++ expect(results).toHaveLength(2)+ expect(results[0].output).toBe('first-value')+ expect(results[1].output).toBe('second-value')+ })+})diff --git a/src/lib/workflow-engine.ts b/src/lib/workflow-engine.tsindex e30b0c0a..b1d9da3a 100644--- a/src/lib/workflow-engine.ts+++ b/src/lib/workflow-engine.ts@@ -56,14 +56,23 @@ import type { ApprovalGate, ExecutionRequest, ExecutorToolDef } from '../api/age/*** Build a real `ApprovalGate` for a `run_workflow` tool call's nested engine- * (builtin-tools.ts's `executeRunWorkflow`), synchronously wired (no dynamic- * `import()`) so it never adds a tick the lane-timing tests do not expect.- * Same decision table as `buildSubAgentGates` (sub-agent.ts): a `blocked`- * category refuses outright, `auto` runs unattended, `confirm` enqueues into- * the SAME conversation-keyed queue the rest of Agent mode reads- * (`approval-queue.ts`), so the user sees the same "Requesting approval"- * card. Fail closed: no conversation to ask in refuses a `confirm` tool- * rather than running it.+ * (builtin-tools.ts's `executeRunWorkflow`), synchronously wired (no+ * top-level dynamic `import()`) so it never adds a tick the lane-timing+ * tests do not expect. Same decision table as `buildSubAgentGates`+ * (sub-agent.ts): a `blocked` category refuses outright, `auto` runs+ * unattended, `confirm` asks on the surface that actually started this run+ * (`sub-agent.ts:380-393`, same reasoning): the Code tab's own+ * `codexConfirmStore` when `run.mode` is set (`run_workflow` sits in category+ * 'workflow', reachable there via `CODEX_CATEGORIES`, and a sub-agent+ * inherits its parent's `mode`, bau/review-wfgate.md Auflage 1), otherwise+ * the SAME conversation-keyed chat queue the rest of Agent mode reads+ * (`approval-queue.ts`). The dynamic imports for `codexConfirmStore` and+ * `codexShellGate` only happen inside that rare `confirm`+`mode` branch, not+ * at construction time, so the lane-timing tests this function was written+ * to protect (see the header comment above) stay unaffected. Fail closed: no+ * conversation to ask in, and no Code-tab surface either, refuses a+ * `confirm` tool rather than running it or hanging on a question nobody can+ * see.*/export function buildWorkflowApprovalGate(run: AgentRunContext | undefined): ApprovalGate {const convId = run?.conversationId ?? null@@ -79,13 +88,26 @@ export function buildWorkflowApprovalGate(run: AgentRunContext | undefined): Appconst level = resolveApprovalLevel(req.toolName, {categoryLevel,override: perm.perToolOverrides[req.toolName],- // A workflow is never a Code-tab surface: there is no preset to defer- // to, only the permission store above.- codexMode: null,+ codexMode: run?.mode ?? null,+ execConfirm: run?.execApproval?.confirmExec === true,readOnlyRun: run?.readOnlyShellTurn === true,})if (level === 'blocked') return falseif (level === 'auto') return true+ // Stufe 'confirm': ask on the surface that started this run. The Code+ // tab's own dialog, not the chat queue, once `run.mode` is set, or the+ // question ends up somewhere nobody is looking at it+ // (bau/review-wfgate.md Auflage 1).+ if (run?.mode) {+ const { useCodexConfirmStore } = await import('../stores/codexConfirmStore')+ const { renderApprovalPreview } = await import('../hooks/codexShellGate')+ return useCodexConfirmStore.getState().ask({+ toolName: req.toolName,+ command: renderApprovalPreview(req.toolName, req.args),+ args: req.args,+ cloudReason: run.execApproval?.cloudReason === true,+ }, abortSignal)+ }if (!convId) return falsereturn new Promise<boolean>((resolve) => {const toolCall: AgentToolCall = {@@ -176,6 +198,33 @@ export class WorkflowEngine {* header, "DIE WEITERGABE DES ELTERNLAUF-TOKENS".*/private heldLocalLane: HeldLocalLane | null = null+ /**+ * The REAL run this engine was started from, when one exists: the+ * `run_workflow` tool's own `AgentRunContext` (builtin-tools.ts), carrying+ * the actual conversation, `abortSignal`, `mode` and `readOnlyShellTurn` of+ * whoever called `run_workflow`. `undefined` for a top-level workflow+ * started from the "run workflow <name>" chat trigger, which already IS+ * the real conversation (`this.conversationId` itself is real there).+ * Without this, a nested `run_workflow` step used `this.conversationId`+ * (the fabricated lane-booking string `'tool-execution'`, see the `run()`+ * docstring below) as if it were a real conversation when building ITS OWN+ * child run context, so a further-nested `run_workflow` or `delegate_task`+ * step asked a question under a conversation id no window reads and lost+ * the parent's `abortSignal` entirely, a queued approval nobody could ever+ * answer or clean up (bau/review-wfgate.md Auflage 2). `effectiveOuterRun`+ * and `effectiveConversationId` below read this field instead of+ * hardcoding `this.conversationId` for that purpose.+ */+ private invokingRun?: AgentRunContext+ /**+ * A value for the FIRST `user_input` step to consume instead of waiting,+ * taken from `initialVariables.user_input` (see the constructor). Set once+ * at construction, consumed at most once, then cleared: only the first+ * `user_input` step in a run is meant to read the caller's own argument, a+ * second one still genuinely waits (bau/review-wfgate.md Auflage 6 /+ * ZUSATZFRAGE, `executeUserInputStep` below).+ */+ private prefilledUserInput?: stringconstructor(workflow: AgentWorkflow,@@ -202,7 +251,14 @@ export class WorkflowEngine {* the dead Settings play button was removed) is never nested, so it* leaves this at the default `null` and books its own slot from scratch.*/- runsInHeldLane: HeldLocalLane | null = null+ runsInHeldLane: HeldLocalLane | null = null,+ /**+ * See the `invokingRun` field doc above. Only a `run_workflow` tool step+ * passes this (its own `AgentRunContext`, builtin-tools.ts); every other+ * caller leaves it `undefined` and this run's own `conversationId` is+ * already the real one.+ */+ invokingRun?: AgentRunContext,) {if (!approve) {// Defense in depth behind the TS type: a caller reached from plain JS,@@ -219,6 +275,54 @@ export class WorkflowEngine {this.abortController = new AbortController()this.depth = depththis.runsInHeldLane = runsInHeldLane+ this.invokingRun = invokingRun+ this.prefilledUserInput = initialVariables?.user_input+ }++ /**+ * The `AgentRunContext` to hand to a NESTED `run_workflow`/`delegate_task`+ * tool step (second-degree recursion). Built from `invokingRun` when this+ * engine itself was started from a real outer run, so the real+ * conversation, `mode`, `readOnlyShellTurn` and `abortSignal` reach a+ * further-nested call instead of this run's own lane-booking+ * `conversationId` (`'tool-execution'` on the `run_workflow` path, see the+ * `run()` docstring) standing in for a conversation no window reads+ * (bau/review-wfgate.md Auflage 2). Falls back to the pre-existing+ * `this.conversationId`-based shape for a top-level engine (the chat+ * trigger), where `this.conversationId` already IS the real conversation.+ */+ private effectiveOuterRun(): AgentRunContext {+ const base = this.invokingRun+ return {+ token: base?.token ?? `workflow-${this.conversationId}`,+ chatId: base?.chatId ?? null,+ conversationId: base?.conversationId ?? this.conversationId,+ workspace: base?.workspace ?? null,+ artifactMode: base?.artifactMode ?? false,+ readOnlyShellTurn: base?.readOnlyShellTurn ?? false,+ mode: base?.mode ?? null,+ execApproval: base?.execApproval,+ artifacts: base?.artifacts ?? [],+ // The real outer abortSignal when there is one, so Stop on the ORIGINAL+ // run reaches a call two levels deep too; this run's own controller+ // otherwise, so at least Stop on THIS run still reaches the child.+ abortSignal: base?.abortSignal ?? this.abortController.signal,+ heldLocalLane: this.heldLocalLane,+ }+ }++ /**+ * The conversation id to use for anything that should agree with the gate+ * (`buildWorkflowApprovalGate`, constructed from the same `invokingRun` by+ * `executeRunWorkflow`): the real outer conversation when this engine was+ * started from one, this run's own id otherwise. Fixes the split Auflage 5+ * describes: the prompt-step tool catalog used to read `this.conversationId`+ * ('tool-execution' on the `run_workflow` path) while the gate itself+ * already decided against the real conversation, so a per-conversation+ * override applied to one and not the other.+ */+ private effectiveConversationId(): string {+ return this.invokingRun?.conversationId ?? this.conversationId}/**@@ -480,7 +584,12 @@ export class WorkflowEngine {// wfplay.md Teil B): `DEFAULT_PERMISSIONS` used to sit here, so a// category the user set to 'blocked' was invisible everywhere else in// the app yet still handed to the model in a workflow prompt step.- const permissions = usePermissionStore.getState().getEffectivePermissions(this.conversationId)+ // `effectiveConversationId()`, not `this.conversationId` (Auflage 5,+ // bau/review-wfgate.md): on the `run_workflow` path this run's own id+ // is the fabricated lane-booking string, so a per-conversation+ // override the user set on the REAL chat used to reach the gate's+ // decision but not this catalog, or the reverse.+ const permissions = usePermissionStore.getState().getEffectivePermissions(this.effectiveConversationId())const tools: ToolDefinition[] = toolRegistry.toOllamaTools(permissions)const allowedTools = step.allowedTools? tools.filter(t => step.allowedTools!.includes(t.function.name))@@ -578,31 +687,23 @@ export class WorkflowEngine {}// A tool step calling run_workflow OR delegate_task is second-degree- // nesting: hand it THIS run's own held-lane proof (null on a cloud lane,- // or before this run's own admission resolved), so a FOREGROUND nested- // run rides along instead of booking its own place behind this one and- // hanging (Nachpruefung, bau/review-w2lane.md, "Sub-Agent im Workflow":- // a workflow tool step calling a foreground `delegate_task` with its own- // local `model` got `run: undefined` here, so it always booked normally- // under a fresh identity while this engine's own step awaited it,- // deadlocking whenever this engine already held the one local slot).+ // nesting: hand it the REAL outer run context (`effectiveOuterRun`, see+ // its doc above), not a context built from this run's own+ // `conversationId`, which is the fabricated lane-booking string+ // `'tool-execution'` on the `run_workflow` path (bau/review-wfgate.md+ // Auflage 2: a further-nested call used to ask under that fake id,+ // unreachable by any window and never cleaned up on Stop, since it also+ // carried no `abortSignal`). `effectiveOuterRun` still carries THIS run's+ // own `heldLocalLane` proof (null on a cloud lane, or before this run's+ // own admission resolved), so a FOREGROUND nested run rides along+ // instead of booking its own place behind this one and hanging+ // (Nachpruefung, bau/review-w2lane.md, "Sub-Agent im Workflow").// `delegate_task`'s BACKGROUND branch is `void`-fired and never awaited- // by this step, so it cannot deadlock this loop either way; giving it- // `this.conversationId` as well is a minor, harmless side effect, not a- // second bug. Every other tool keeps its long-standing `run: undefined`- // (unchanged scope: only these two recursive tools read `heldLocalLane`).+ // by this step, so it cannot deadlock this loop either way. Every other+ // tool keeps its long-standing `run: undefined` (unchanged scope: only+ // these two recursive tools read `heldLocalLane`).const runForTool: AgentRunContext | undefined = step.toolName === 'run_workflow' || step.toolName === 'delegate_task'- ? {- token: `workflow-${this.conversationId}`,- chatId: null,- conversationId: this.conversationId,- workspace: null,- artifactMode: false,- readOnlyShellTurn: false,- mode: null,- artifacts: [],- heldLocalLane: this.heldLocalLane,- }+ ? this.effectiveOuterRun(): undefinedconst gate = await this.gatedApproval(step.toolName, args, runForTool)@@ -703,6 +804,32 @@ export class WorkflowEngine {// ── User Input Step ───────────────────────────────────────private async executeUserInputStep(step: WorkflowStep, stepIndex: number, startedAt: number): Promise<StepResult> {+ // ZUSATZFRAGE / Auflage 6, bau/review-wfgate.md: all three built-in+ // workflows (Research Topic, Summarize URL, Code Review) begin with a+ // `user_input` step, and neither surviving caller ever calls+ // `provideUserInput` below (`onWaitingForInput: () => {}` in both+ // builtin-tools.ts's `executeRunWorkflow` and useAgentChat.ts's chat+ // trigger), so every one of them used to hang here forever, waiting on a+ // resolver nothing can reach except Stop. `run_workflow` already turns+ // its own `input` argument into the `user_input` variable+ // (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.+ if (this.prefilledUserInput !== undefined) {+ const input = this.prefilledUserInput+ this.prefilledUserInput = undefined+ this.variables['user_input'] = input+ this.variables['last_output'] = input+ return {+ stepId: step.id,+ status: 'completed',+ output: input,+ startedAt,+ completedAt: Date.now(),+ }+ }+const prompt = interpolate(step.userInputPrompt || 'Enter input:', this.variables)this.callbacks.onWaitingForInput(stepIndex, prompt)