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): gate every tool call the workflow engine executes
purple91304188824f
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.tsindex aeb19747..56715662 100644--- a/src/api/mcp/builtin-tools.ts+++ b/src/api/mcp/builtin-tools.ts@@ -11,7 +11,7 @@ import { backendCall, fetchExternal } from '../backend'import { getActiveChatId, getActiveConversationId, getActiveWorkspace, isChatArtifactMode, captureChatArtifact, isReadOnlyShellTurn } from '../agent-context'import type { AgentRunContext } from '../agent-context'import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'-import { WorkflowEngine } from '../../lib/workflow-engine'+import { WorkflowEngine, buildWorkflowApprovalGate } from '../../lib/workflow-engine'import type { StepResult } from '../../types/agent-workflows'import { DELEGATE_TASK_TOOL_DEF, buildDelegateExecutor } from '../agents/sub-agent'import {@@ -1608,7 +1608,20 @@ async function executeRunWorkflow(args: ToolArgs, run?: AgentRunContext): Promis// it against the actual holder at run time before skipping its own// booking, so a stale or absent proof falls back to booking normally// instead of silently trusting the marker.- const engine = new WorkflowEngine(workflow, 'tool-execution', callbacks, initialVars, _workflowDepth, run?.heldLocalLane ?? null)+ //+ // The gate (Nebenbefund, bau/review-wfplay.md Teil B): one approval for+ // `run_workflow` itself already fell before this executor ran, but that+ // approval was for "run this workflow", not for whatever it does inside.+ // Passing `APPROVE_ALL` here, the reviewer's own first suggestion, would+ // turn that single approval into a blank check for every tool the+ // workflow's steps (or a model inside a prompt step) go on to call,+ // including a `shell_execute` the user never saw. `buildWorkflowApprovalGate`+ // resolves the REAL gate from `run`'s own conversation and read-only flag,+ // same decision table `delegate_task` already goes through, so a+ // `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)await engine.run()} finally {_workflowDepth--diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex c49e2ebf..f5c4c7c5 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -69,7 +69,7 @@ import {fanoutDirective,unresolvedModelNote,} from '../lib/agent-fanout'-import { setExplicitFanout } from '../api/agents/sub-agent'+import { setExplicitFanout, buildSubAgentGates } from '../api/agents/sub-agent'import { appendTaskReport } from '../lib/agent-task-report'import { useAgentTaskStore } from '../stores/agentTaskStore'import { useAgentGoalStore, renderGoalSection } from '../stores/agentGoalStore'@@ -355,7 +355,24 @@ export function useAgentChat() {},}- const engine = new WorkflowEngine(workflow, convId, callbacks)+ // Nebenbefund, bau/review-wfplay.md Teil B: this trigger used to hand+ // the engine no gate at all, so a workflow's own tool steps ran+ // unattended. Reusing `buildSubAgentGates` (audit AGT-1's fix, same+ // approach a delegated sub-agent already gets) reaches the SAME+ // conversation-keyed approval queue and permission store the rest of+ // Agent mode uses, so the user sees the same "Requesting approval"+ // block, not a bespoke one for workflows.+ const gates = await buildSubAgentGates({+ token: `workflow-trigger-${convId}`,+ chatId: null,+ conversationId: convId,+ workspace: null,+ artifactMode: false,+ readOnlyShellTurn: false,+ mode: null,+ artifacts: [],+ })+ const engine = new WorkflowEngine(workflow, convId, callbacks, gates.awaitApproval)await engine.run()return}diff --git a/src/lib/__tests__/background-shutdown-lanes.test.ts b/src/lib/__tests__/background-shutdown-lanes.test.tsindex ba4b8e9f..3a9c6cb6 100644--- a/src/lib/__tests__/background-shutdown-lanes.test.ts+++ b/src/lib/__tests__/background-shutdown-lanes.test.ts@@ -20,6 +20,7 @@import { describe, it, expect, beforeEach } from 'vitest'import { stopAllBackgroundWork } from '../background-shutdown'import { WorkflowEngine } from '../workflow-engine'+import { APPROVE_ALL } from '../../api/agents/tool-executor'import { buildDelegateExecutor, _setDepth, type SubAgentRunner } from '../../api/agents/sub-agent'import { useAgentTaskStore } from '../../stores/agentTaskStore'import { useGenerationStore } from '../../stores/generationStore'@@ -63,7 +64,7 @@ describe('stopAllBackgroundWork erreicht Workflow-Lauf UND Hintergrund-Sub-AgentonStepError: (_i, e) => stepErrors.push(e),onWaitingForInput: () => {}, onComplete: () => {}, onError: () => {},}- const engine = new WorkflowEngine(workflow, 'wf-conv', callbacks)+ const engine = new WorkflowEngine(workflow, 'wf-conv', callbacks, APPROVE_ALL)const workflowLaufend = engine.run()await takte()expect(localLaneHolder()).toBe('wf-conv')diff --git a/src/lib/__tests__/heldLocalLane-wird-immer-weitergereicht.test.ts b/src/lib/__tests__/heldLocalLane-wird-immer-weitergereicht.test.tsindex 0a7ed59c..c89fbe43 100644--- a/src/lib/__tests__/heldLocalLane-wird-immer-weitergereicht.test.ts+++ b/src/lib/__tests__/heldLocalLane-wird-immer-weitergereicht.test.ts@@ -44,6 +44,7 @@ import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'import { useAgentTaskStore } from '../../stores/agentTaskStore'import { toolRegistry, registerBuiltinTools } from '../../api/mcp'import { WorkflowEngine } from '../workflow-engine'+import { APPROVE_ALL } from '../../api/agents/tool-executor'import { buildDelegateExecutor, _setDepth, type SubAgentRunner } from '../../api/agents/sub-agent'import type { AgentWorkflow, WorkflowStep, WorkflowEngineCallbacks } from '../../types/agent-workflows'import type { AgentRunContext } from '../../api/agent-context'@@ -151,7 +152,7 @@ describe('3) Workflow reicht den eigenen Beweis an einen zweiten run_workflow-Scconst outer = workflowOf('outer-id', 'outer', [{ id: 'call-inner', type: 'tool', label: 'call-inner', toolName: 'run_workflow', toolArgs: { name: 'inner' } },])- const engine = new WorkflowEngine(outer, 'wf-outer', callbacks())+ const engine = new WorkflowEngine(outer, 'wf-outer', callbacks(), APPROVE_ALL)const results = await engine.run()expect(results.map((r) => r.status)).toEqual(['completed'])@@ -218,7 +219,7 @@ describe('5) Sub-Agent im Workflow: ein Arbeitsablaufschritt ruft delegate_taskconst outer = workflowOf('outer-id', 'outer', [{ id: 'call-agent', type: 'tool', label: 'call-agent', toolName: 'delegate_task', toolArgs: { goal: 'x' } },])- const engine = new WorkflowEngine(outer, 'wf-outer', callbacks())+ const engine = new WorkflowEngine(outer, 'wf-outer', callbacks(), APPROVE_ALL)const results = await engine.run()expect(results.map((r) => r.status)).toEqual(['completed'])@@ -245,7 +246,7 @@ describe('5) Sub-Agent im Workflow: ein Arbeitsablaufschritt ruft delegate_taskconst outer = workflowOf('outer-id', 'outer', [{ id: 'call-agent', type: 'tool', label: 'call-agent', toolName: 'delegate_task', toolArgs: { goal: 'x' } },])- const engine = new WorkflowEngine(outer, 'wf-outer', callbacks())+ const engine = new WorkflowEngine(outer, 'wf-outer', callbacks(), APPROVE_ALL)const results = await engine.run()expect(results.map((r) => r.status)).toEqual(['completed'])diff --git a/src/lib/__tests__/workflow-engine-approval-gate.test.ts b/src/lib/__tests__/workflow-engine-approval-gate.test.tsnew file mode 100644index 00000000..e331cbfc--- /dev/null+++ b/src/lib/__tests__/workflow-engine-approval-gate.test.ts@@ -0,0 +1,188 @@+/**+ * Nebenbefund, bau/review-wfplay.md Teil B (Schweregrad hoch): die Engine+ * fuehrte Werkzeugschritte bisher direkt ueber `toolRegistry.execute` aus und+ * bot Prompt-Schritten `DEFAULT_PERMISSIONS` an statt des Berechtigungs-+ * Stores, dieselbe Luecke, die AGT-1 in `tool-executor.ts`/`sub-agent.ts`+ * schon einmal geschlossen hat. Dieser Test prueft den Fix: ein Pflicht-Gate+ * im Konstruktor (`approve: ApprovalGate`), gleiche Politik wie im+ * Agenten-Chat.+ *+ * Fuenf Faelle, jeder mit Negativkontrolle gegen den Stand vor diesem Fix+ * (Zahlen im Baubericht, bau/wfgate.md):+ * (a) ablehnendes Gate: execute laeuft nie.+ * (b) Prompt-Schritt bietet ein blockiertes Werkzeug nicht an und fuehrt+ * einen erfundenen Aufruf darauf trotzdem nicht aus.+ * (c) erlaubendes Gate laesst den Schritt normal laufen.+ * (d) Stop waehrend einer wartenden Freigabe: kein execute, Spur frei.+ * (e) Konstruktion ohne Gate wirft.+ *+ * Lauf: npx vitest run src/lib/__tests__/workflow-engine-approval-gate.test.ts+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'++vi.mock('../agent-strategy', () => ({+ resolveToolCallingStrategy: vi.fn(),+}))++import { WorkflowEngine } from '../workflow-engine'+import { APPROVE_ALL, type ApprovalGate } from '../../api/agents/tool-executor'+import { buildSubAgentGates } from '../../api/agents/sub-agent'+import { toolRegistry, registerBuiltinTools } from '../../api/mcp'+import { useModelStore } from '../../stores/modelStore'+import { usePermissionStore } from '../../stores/permissionStore'+import { useGenerationStore } from '../../stores/generationStore'+import { localLaneHolder, __resetRunLanesForTests } from '../run-lanes'+import { resolveToolCallingStrategy } from '../agent-strategy'+import type { AgentWorkflow, WorkflowStep, WorkflowEngineCallbacks } from '../../types/agent-workflows'+import type { AgentRunContext } from '../../api/agent-context'++/** No prefix means Ollama, and Ollama defaults to this machine in tests+ * (`isOllamaLocal()` with no configured base), so this resolves LOCAL. */+const LOCAL_MODEL = 'qwen3:8b'+const CLOUD_MODEL = 'anthropic::claude'++function workflowOf(steps: WorkflowStep[]): AgentWorkflow {+ return { id: 'wf', name: 'test', description: '', icon: 'Zap', steps, variables: {}, isBuiltIn: false, createdAt: 0, updatedAt: 0 }+}++function callbacks(): WorkflowEngineCallbacks {+ return {+ onStepStart: () => {}, onStepComplete: () => {}, onStepError: () => {},+ onWaitingForInput: () => {}, onComplete: () => {}, onError: () => {},+ }+}++async function takte(n = 20): Promise<void> {+ for (let i = 0; i < n; i++) await Promise.resolve()+}++beforeEach(() => {+ __resetRunLanesForTests()+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })+ registerBuiltinTools(toolRegistry)+})++afterEach(() => {+ usePermissionStore.getState().resetToDefaults()+ vi.restoreAllMocks()+})++describe('(a) ein ablehnendes Gate laesst den Werkzeugschritt nie ausfuehren', () => {+ it('toolRegistry.execute wird nie gerufen, der Schritt endet mit einer englischen Meldung', async () => {+ useModelStore.setState({ activeModel: CLOUD_MODEL })+ const execSpy = vi.spyOn(toolRegistry, 'execute')+ const rejectAll: ApprovalGate = async () => false++ const workflow = workflowOf([+ { id: 'call', type: 'tool', label: 'call', toolName: 'shell_execute', toolArgs: { command: 'echo hi' } },+ ])+ const engine = new WorkflowEngine(workflow, 'conv-a', callbacks(), rejectAll)+ const results = await engine.run()++ expect(execSpy).not.toHaveBeenCalled()+ expect(results).toHaveLength(1)+ expect(results[0].status).toBe('failed')+ expect(results[0].error).toMatch(/rejected/i)+ expect(results[0].error).toMatch(/not approved/i)+ })+})++describe('(b) ein Prompt-Schritt bietet nur, was der Store erlaubt, und fuehrt einen erfundenen verbotenen Aufruf nicht aus', () => {+ it('shell_execute (Kategorie terminal, blockiert) fehlt im Angebot UND ein erfundener Aufruf darauf laeuft nicht', async () => {+ useModelStore.setState({ activeModel: CLOUD_MODEL })+ usePermissionStore.getState().setGlobalPermission('terminal', 'blocked')++ let offeredNames: string[] = []+ const chatWithTools = vi.fn(async (_model: string, _messages: unknown, tools: Array<{ function: { name: string } }>) => {+ offeredNames = tools.map((t) => t.function.name)+ // The model hallucinates a call to a tool that was never offered.+ return {+ content: '',+ toolCalls: [{ id: '1', function: { name: 'shell_execute', arguments: { command: 'rm -rf /' } } }],+ }+ })+ vi.mocked(resolveToolCallingStrategy).mockResolvedValue({+ strategy: 'native',+ modelToUse: 'claude',+ modelId: 'claude',+ providerId: 'anthropic',+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ provider: { chatWithTools, chatStream: vi.fn() } as any,+ })++ const execSpy = vi.spyOn(toolRegistry, 'execute')+ // The real gate, resolved from the SAME store the offering just read:+ // 'terminal' is 'blocked', so this refuses without ever queuing.+ const gates = await buildSubAgentGates({+ token: 'wf', chatId: null, conversationId: 'conv-b', workspace: null,+ artifactMode: false, readOnlyShellTurn: false, mode: null, artifacts: [],+ } as AgentRunContext)++ const workflow = workflowOf([{ id: 'p', type: 'prompt', label: 'p', prompt: 'go' }])+ const engine = new WorkflowEngine(workflow, 'conv-b', callbacks(), gates.awaitApproval)+ const results = await engine.run()++ expect(offeredNames).not.toContain('shell_execute')+ expect(execSpy).not.toHaveBeenCalled()+ expect(results).toHaveLength(1)+ expect(results[0].status).toBe('failed')+ })+})++describe('(c) ein erlaubendes Gate laesst den Werkzeugschritt normal laufen', () => {+ it('APPROVE_ALL fuehrt zu einem completed-Schritt und einem echten execute-Aufruf', async () => {+ useModelStore.setState({ activeModel: CLOUD_MODEL })+ const execSpy = vi.spyOn(toolRegistry, 'execute').mockResolvedValue('ok-result')++ const workflow = workflowOf([+ { id: 'call', type: 'tool', label: 'call', toolName: 'shell_execute', toolArgs: { command: 'echo hi' } },+ ])+ const engine = new WorkflowEngine(workflow, 'conv-c', callbacks(), APPROVE_ALL)+ const results = await engine.run()++ expect(execSpy).toHaveBeenCalledTimes(1)+ expect(execSpy).toHaveBeenCalledWith('shell_execute', { command: 'echo hi' }, 1, undefined)+ expect(results[0].status).toBe('completed')+ expect(results[0].output).toBe('ok-result')+ })+})++describe('(d) Stop waehrend einer wartenden Freigabe fuehrt nie aus und gibt die Spur frei', () => {+ it('ein Gate, das nie von selbst aufloest: cancel() beantwortet es mit false, execute laeuft nie, die lokale Spur ist danach leer', async () => {+ useModelStore.setState({ activeModel: LOCAL_MODEL })+ const execSpy = vi.spyOn(toolRegistry, 'execute')+ // A real pending approval (a queued "Requesting approval" card the user+ // never clicks) never resolves on its own either.+ const neverResolves: ApprovalGate = () => new Promise<boolean>(() => {})++ const workflow = workflowOf([+ { id: 'call', type: 'tool', label: 'call', toolName: 'shell_execute', toolArgs: { command: 'echo hi' } },+ ])+ const engine = new WorkflowEngine(workflow, 'conv-d', callbacks(), neverResolves)+ const laufend = engine.run()+ await takte(5)++ // The run is genuinely holding the local lane while it awaits approval.+ expect(localLaneHolder()).toBe('conv-d')++ // Stop.+ engine.cancel()+ const results = await laufend++ expect(execSpy).not.toHaveBeenCalled()+ expect(results).toHaveLength(1)+ expect(results[0].status).toBe('failed')+ expect(localLaneHolder()).toBeNull()+ })+})++describe('(e) Konstruktion ohne Gate ist ein Typfehler und wirft', () => {+ it('new WorkflowEngine ohne approve wirft statt still zu klaffen', () => {+ const workflow = workflowOf([])+ expect(() => {+ // @ts-expect-error approve is required; a caller that omits it must not+ // type-check, and this run-time check is the defense behind that.+ return new WorkflowEngine(workflow, 'conv-e', callbacks())+ }).toThrow(/approve gate/i)+ })+})diff --git a/src/lib/__tests__/workflow-engine-branching.test.ts b/src/lib/__tests__/workflow-engine-branching.test.tsindex 05f4d62e..9204d4b6 100644--- a/src/lib/__tests__/workflow-engine-branching.test.ts+++ b/src/lib/__tests__/workflow-engine-branching.test.ts@@ -13,6 +13,7 @@*/import { describe, it, expect, beforeEach, vi } from 'vitest'import { WorkflowEngine, MAX_STEPS_EXECUTED } from '../workflow-engine'+import { APPROVE_ALL } from '../../api/agents/tool-executor'import { useMemoryStore } from '../../stores/memoryStore'import type { AgentWorkflow, WorkflowStep, WorkflowEngineCallbacks } from '../../types/agent-workflows'@@ -53,7 +54,7 @@ function run(steps: WorkflowStep[], variables: Record<string, string> = {}) {onComplete: () => {},onError: (e) => errors.push(e),}- const engine = new WorkflowEngine(workflow, 'conv', callbacks, variables)+ const engine = new WorkflowEngine(workflow, 'conv', callbacks, APPROVE_ALL, variables)return engine.run().then((results) => ({ results, errors }))}diff --git a/src/lib/__tests__/workflow-engine-lane.test.ts b/src/lib/__tests__/workflow-engine-lane.test.tsindex fb6d0eb9..1d7899db 100644--- a/src/lib/__tests__/workflow-engine-lane.test.ts+++ b/src/lib/__tests__/workflow-engine-lane.test.ts@@ -18,6 +18,7 @@*/import { describe, it, expect, beforeEach, vi } from 'vitest'import { WorkflowEngine } from '../workflow-engine'+import { APPROVE_ALL } from '../../api/agents/tool-executor'import { localLaneHolder, queuedRunIds, __resetRunLanesForTests } from '../run-lanes'import { useGenerationStore } from '../../stores/generationStore'import { useModelStore } from '../../stores/modelStore'@@ -64,7 +65,7 @@ describe('einmal je Lauf, nicht je Schritt', () => {// angestellt, statt in derselben Buchung mitzulaufen).const cb = callbacks()cb.onStepStart = () => { gesehen.push(localLaneHolder()) }- const engine = new WorkflowEngine(workflowOf(steps), 'wf-conv', cb)+ const engine = new WorkflowEngine(workflowOf(steps), 'wf-conv', cb, APPROVE_ALL)const laufend = engine.run()expect(localLaneHolder()).toBe('wf-conv')@@ -80,7 +81,7 @@ describe('einmal je Lauf, nicht je Schritt', () => {// sonst ist der synchrone memory_save-Schritt schon durch, bevor der// zweite Lauf ueberhaupt anstellt.const step: WorkflowStep = { id: 'warte', type: 'user_input', label: 'warte', userInputPrompt: 'weiter?' }- const engine = new WorkflowEngine(workflowOf([step]), 'wf-conv', callbacks())+ const engine = new WorkflowEngine(workflowOf([step]), 'wf-conv', callbacks(), APPROVE_ALL)const laufend = engine.run()await Promise.resolve()@@ -113,7 +114,7 @@ describe('Stop wirkt, wartend wie laufend', () => {const errors: string[] = []const cb = callbacks((e) => errors.push(e))cb.onStepStart = () => { stepLief = true }- const engine = new WorkflowEngine(workflowOf([noteStep('a')]), 'wf-conv', cb)+ const engine = new WorkflowEngine(workflowOf([noteStep('a')]), 'wf-conv', cb, APPROVE_ALL)const laufend = engine.run()expect(queuedRunIds()).toEqual(['wf-conv'])@@ -142,7 +143,7 @@ describe('Stop wirkt, wartend wie laufend', () => {useGenerationStore.getState().abortConversation('wf-conv')}}- const engine = new WorkflowEngine(workflowOf([noteStep('a'), noteStep('b'), noteStep('c')]), 'wf-conv', cb)+ const engine = new WorkflowEngine(workflowOf([noteStep('a'), noteStep('b'), noteStep('c')]), 'wf-conv', cb, APPROVE_ALL)const results = await engine.run()// Abgebrochen NACH dem ersten Schritt, VOR dem zweiten: die Abbruchpruefungdiff --git a/src/lib/__tests__/workflow-engine-nested-run-workflow.test.ts b/src/lib/__tests__/workflow-engine-nested-run-workflow.test.tsindex 2e12aa33..ff8f19da 100644--- a/src/lib/__tests__/workflow-engine-nested-run-workflow.test.ts+++ b/src/lib/__tests__/workflow-engine-nested-run-workflow.test.ts@@ -25,6 +25,7 @@*/import { describe, it, expect, beforeEach, vi } from 'vitest'import { WorkflowEngine } from '../workflow-engine'+import { APPROVE_ALL } from '../../api/agents/tool-executor'import { runInLane } from '../run-slot'import { localLaneHolder, queuedRunIds, __resetRunLanesForTests } from '../run-lanes'import { useGenerationStore } from '../../stores/generationStore'@@ -79,7 +80,7 @@ describe('ein run_workflow-Schritt reicht den eigenen echten Beweis an die innerconst outer = workflowOf('outer-id', 'outer', [{ id: 'call-inner', type: 'tool', label: 'call-inner', toolName: 'run_workflow', toolArgs: { name: 'inner' } },])- const engine = new WorkflowEngine(outer, 'wf-outer', callbacks())+ const engine = new WorkflowEngine(outer, 'wf-outer', callbacks(), APPROVE_ALL)const results = await engine.run()expect(results.map((r) => r.status)).toEqual(['completed'])@@ -105,7 +106,7 @@ describe('ein run_workflow-Schritt reicht den eigenen echten Beweis an die inner// aufruft) beginnt: ein dritter Aufrufer meldet sich jetzt an.dritterLauf = runInLane({ conversationId: 'dritter', lane: 'local' }, async () => { dritterLief = true })}- const engine = new WorkflowEngine(outer, 'wf-outer', cb)+ const engine = new WorkflowEngine(outer, 'wf-outer', cb, APPROVE_ALL)await engine.run()await dritterLauf@@ -126,7 +127,7 @@ describe('ein run_workflow-Schritt reicht den eigenen echten Beweis an die innerconst outer = workflowOf('outer-id', 'outer', [{ id: 'call-inner', type: 'tool', label: 'call-inner', toolName: 'run_workflow', toolArgs: { name: 'inner' } },])- const engine = new WorkflowEngine(outer, 'wf-outer', callbacks())+ const engine = new WorkflowEngine(outer, 'wf-outer', callbacks(), APPROVE_ALL)const results = await engine.run()expect(results.map((r) => r.status)).toEqual(['completed'])diff --git a/src/lib/workflow-engine.ts b/src/lib/workflow-engine.tsindex 53ab719a..e30b0c0a 100644--- a/src/lib/workflow-engine.ts+++ b/src/lib/workflow-engine.ts@@ -24,7 +24,6 @@ import { buildSamplingRequest } from './sampling'// Beides sind generische Module ohne Rückkante. Der Shim bleibt für seine// verbliebenen Aufrufer bestehen.import { toolRegistry } from '../api/mcp/tool-registry'-import { DEFAULT_PERMISSIONS } from '../api/mcp/types'import type { ToolArgs } from '../api/mcp/types'import { streamProviderTurn } from './provider-stream'import { runInLane, type HeldLocalLane } from './run-slot'@@ -35,6 +34,77 @@ import { buildHermesToolPrompt, parseHermesToolCalls, stripToolCallTags, hasToolimport { resolveToolCallingStrategy } from './agent-strategy'import type { AgentWorkflow, WorkflowStep, StepResult, WorkflowEngineCallbacks } from '../types/agent-workflows'import type { ChatMessage, ToolDefinition } from '../api/providers/types'+import { usePermissionStore } from '../stores/permissionStore'+// Nebenbefund, bau/review-wfplay.md Teil B: die Engine fuehrte Werkzeuge+// bisher direkt ueber `toolRegistry.execute` aus, ohne jede Freigabe, und bot+// Prompt-Schritten `DEFAULT_PERMISSIONS` an statt des echten Stores. Derselbe+// Fehler wie AGT-1 (sub-agent.ts), derselbe Fix: ein Pflicht-Gate im+// Konstruktor. Die ENTSCHEIDUNG selbst kommt aus derselben, bereits+// gehaerteten Tabelle wie beim Agenten-Chat und beim Sub-Agenten+// (`resolveApprovalLevel`, agent-approval-policy.ts), nur das VERDRAHTEN auf+// die Warteschlange baut `buildWorkflowApprovalGate` unten selbst, statt+// `sub-agent.ts`s `buildSubAgentGates` zu importieren: deren zwei+// `await import(...)` (Permission-Store, Warteschlange) haengen einen echten+// Tick ein, den `run_workflow`s bestehende Lane-Zeitmess-Tests (u.a.+// `heldLocalLane-wird-immer-weitergereicht.test.ts`) nicht vorhalten, vorher+// gruen, mit `buildSubAgentGates` dort zwei rot (Zahlen im Baubericht). Die+// Politik-TABELLE bleibt eine einzige Stelle, nur die Verdrahtung ist doppelt.+import { resolveApprovalLevel } from './agent-approval-policy'+import { enqueueApproval, removeApproval, type ApprovalEntry } from './approval-queue'+import type { AgentToolCall } from '../types/agent-mode'+import type { ApprovalGate, ExecutionRequest, ExecutorToolDef } from '../api/agents/tool-executor'++/**+ * 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.+ */+export function buildWorkflowApprovalGate(run: AgentRunContext | undefined): ApprovalGate {+ const convId = run?.conversationId ?? null+ const abortSignal = run?.abortSignal+ return async (req) => {+ if (abortSignal?.aborted) return false+ const perm = usePermissionStore.getState()+ const categoryLevel = toolRegistry.getPermissionLevelWithOverrides(+ req.toolName,+ perm.getEffectivePermissions(convId ?? undefined),+ {},+ )+ const 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,+ readOnlyRun: run?.readOnlyShellTurn === true,+ })+ if (level === 'blocked') return false+ if (level === 'auto') return true+ if (!convId) return false+ return new Promise<boolean>((resolve) => {+ const toolCall: AgentToolCall = {+ id: req.id,+ toolName: req.toolName,+ args: req.args,+ status: 'pending_approval',+ timestamp: Date.now(),+ }+ const entry: ApprovalEntry = { toolCall, resolve }+ enqueueApproval(convId, entry)+ abortSignal?.addEventListener(+ 'abort',+ () => { if (removeApproval(convId, entry)) resolve(false) },+ { once: true },+ )+ })+ }+}// ── Safety Limits ─────────────────────────────────────────────@@ -87,6 +157,16 @@ export class WorkflowEngine {private inputResolver: ((input: string) => void) | null = nullprivate depth: numberprivate runsInHeldLane: HeldLocalLane | null+ /**+ * The gate every tool call this engine executes has to pass, whether from+ * a `tool` step or requested by the model inside a `prompt` step. Required,+ * with no default: a caller that forgets to wire one gets a compile error+ * instead of a silent, ungated `shell_execute` (same lesson as AGT-1's+ * `awaitApproval` on `ExecutorRuntime`, tool-executor.ts). A caller that+ * genuinely wants no gating passes `APPROVE_ALL` and thereby says so in+ * writing.+ */+ private approve: ApprovalGate/*** The proof this run itself hands to ITS OWN nested `run_workflow` or* (foreground) `delegate_task` tool step (second-degree nesting), set from@@ -101,6 +181,11 @@ export class WorkflowEngine {workflow: AgentWorkflow,conversationId: string,callbacks: WorkflowEngineCallbacks,+ /**+ * REQUIRED, see the field doc above. Pass tool-executor's `APPROVE_ALL`+ * to opt out explicitly; there is no implicit opt-out.+ */+ approve: ApprovalGate,initialVariables?: Record<string, string>,depth: number = 0,/**@@ -113,21 +198,65 @@ export class WorkflowEngine {* Runde 4, bau/review-w2lane.md, a boolean here used to be blind trust).* If the check fails, this run books its own place instead of hanging* behind a stale or fake proof. A top-level workflow (started from the- * workflow panel, or from the "run workflow <name>" chat trigger) is- * never nested, so it leaves this at the default `null` and books its- * own slot from scratch.+ * "run workflow <name>" chat trigger, the only surviving trigger since+ * 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) {+ if (!approve) {+ // Defense in depth behind the TS type: a caller reached from plain JS,+ // or one that spreads old positional args after a signature change,+ // gets a thrown error instead of `undefined` quietly skipping every+ // gate check below.+ throw new Error('WorkflowEngine requires an approve gate (ApprovalGate). Pass APPROVE_ALL from tool-executor.ts to opt out explicitly.')+ }this.workflow = workflowthis.conversationId = conversationIdthis.callbacks = callbacks+ this.approve = approvethis.variables = { ...workflow.variables, ...(initialVariables || {}) }this.abortController = new AbortController()this.depth = depththis.runsInHeldLane = runsInHeldLane}+ /**+ * Gate one tool call through the same policy an agent-chat turn or a+ * delegated sub-agent already goes through (Nebenbefund,+ * bau/review-wfplay.md Teil B). Raced against this run's own abort signal+ * so Stop resolves a still-pending approval with `false` even if the+ * underlying gate's own promise (a real queued approval, say) never+ * settles on its own: the run must not hang on a click that is never+ * coming once Stop was pressed.+ */+ private async gatedApproval(+ toolName: string,+ args: ToolArgs,+ run: AgentRunContext | undefined,+ ): Promise<{ approved: true } | { approved: false; message: string }> {+ if (this.abortController.signal.aborted) {+ return { approved: false, message: `Cancelled: the run was stopped before ${toolName} could run.` }+ }+ const tool: ExecutorToolDef = toolRegistry.resolveExecutable(toolName) ?? { name: toolName }+ const req: ExecutionRequest = {+ id: `${this.conversationId}-${toolName}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,+ toolName,+ args,+ run,+ }+ const approved = await Promise.race([+ this.approve(req, tool),+ new Promise<boolean>((resolve) => {+ this.abortController.signal.addEventListener('abort', () => resolve(false), { once: true })+ }),+ ])+ if (!approved) {+ return { approved: false, message: `Tool call rejected: ${toolName} was not approved.` }+ }+ return { approved: true }+ }+/*** Run the workflow from start to finish.*@@ -144,9 +273,9 @@ export class WorkflowEngine {** `conversationId: this.conversationId` DELIBERATELY, not a private* per-run identity (BLOCKER 3, Nachpruefung 2 von review-w2lane.md): a- * workflow started from the Workflow panel shares its visible- * conversation on purpose, it writes its step messages into that same- * chat, so a queued workflow SHOULD show up there ("waiting for the local+ * workflow started from the "run workflow <name>" chat trigger shares its+ * visible conversation on purpose, it writes its step messages into that+ * same chat, so a queued workflow SHOULD show up there ("waiting for the local* lane") via `isRunQueued`/`runQueuePosition`. A private identity like the* sub-agent's would have fixed the abort-handle bug just as well but at* the cost of that legitimate wait-row attribution, per the review's own@@ -346,8 +475,13 @@ export class WorkflowEngine {if (chunk.done) break}} else {- // With tools- const tools: ToolDefinition[] = toolRegistry.toOllamaTools(DEFAULT_PERMISSIONS)+ // With tools. The catalog offered to the model is the user's OWN+ // permission store, not a fixed default (Nebenbefund, bau/review-+ // 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)+ const tools: ToolDefinition[] = toolRegistry.toOllamaTools(permissions)const allowedTools = step.allowedTools? tools.filter(t => step.allowedTools!.includes(t.function.name)): tools@@ -361,8 +495,13 @@ export class WorkflowEngine {})output = turn.content || ''- // Execute any tool calls+ // Execute any tool calls, gated the same as a tool step (see+ // executeToolStep below): the catalog above already hides a blocked+ // category from the model, but a model can still hallucinate a name+ // or ask for a 'confirm' tool the user has not approved yet.for (const tc of turn.toolCalls) {+ const gate = await this.gatedApproval(tc.function.name, tc.function.arguments, undefined)+ if (!gate.approved) throw new Error(gate.message)const result = await toolRegistry.execute(tc.function.name, tc.function.arguments)output += `\n[Tool: ${tc.function.name}] ${result}`}@@ -397,6 +536,8 @@ export class WorkflowEngine {const toolCalls = parseHermesToolCalls(rawContent)output = stripToolCallTags(rawContent)for (const tc of toolCalls) {+ const gate = await this.gatedApproval(tc.name, tc.arguments, undefined)+ if (!gate.approved) throw new Error(gate.message)const result = await toolRegistry.execute(tc.name, tc.arguments)output += `\n[Tool: ${tc.name}] ${result}`}@@ -463,6 +604,20 @@ export class WorkflowEngine {heldLocalLane: this.heldLocalLane,}: undefined++ const gate = await this.gatedApproval(step.toolName, args, runForTool)+ if (!gate.approved) {+ return {+ stepId: step.id,+ status: 'failed',+ output: '',+ startedAt,+ completedAt: Date.now(),+ error: gate.message,+ toolCalls: [{ name: step.toolName, args, result: gate.message }],+ }+ }+const result = await toolRegistry.execute(step.toolName, args, 1, runForTool)const isError = result.startsWith('Error:')