AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
fix(agents): removing a flow tool keeps it removed after adding another flow (#17089)
Hazem Adelc649aea23667
diff --git a/brain/knowledge/ai-intelligence/ai-agents.md b/brain/knowledge/ai-intelligence/ai-agents.mdindex a163f77b00b..09784ed115b 100644--- a/brain/knowledge/ai-intelligence/ai-agents.md+++ b/brain/knowledge/ai-intelligence/ai-agents.md@@ -90,6 +90,7 @@ Three things follow. `run_agent` has two modes: pointed at a saved agent (`agent- **"Did the failing step send anything" is read off the UI stream, and `producedVisibleOutput` cannot answer it.** `uiParts` only grows in `onStepEnd`, after chunks have already reached the client. The UI stream sends `start`/`start-step` before any content. When the model call itself throws, there is no `start-step` at all, only `error`. A stream error arrives **before** `finish-step` (`text-delta, error, finish-step`). `trackStepContent` therefore resets on `start-step`/`finish-step` and freezes its answer at the first `error` chunk. Drive it through the real `toUIMessageStream` in tests, because a mocked drain hides the ordering.- **`AgentConfigResponse.tier` is always the console credits tier.** A platform tier run fills `platformTier`, `candidates` and `fastCandidate`. The single `credentials`/`modelId` fields equal `candidates[0]`. On a tier run the worker sends no `modelName` to `saveAgentMessages`, and the RPC ignores one on a tier row, because a model name clears the tier (the last write wins).- **A thinking-only final step triggers a reply nudge.** `decideLoopAction` (`run-agent-turn.ts`) decides the `continue_empty` nudge from the final step only (`stepEndsWithReply`), up to `MAX_EMPTY_CONTINUATIONS` nudges per turn. Counting every part the attempt produced, as it used to, let earlier tool chips and reasoning hide a last step that was only thinking, so the user saw "Thought for N seconds" and no reply. `shouldRetryStream` still uses the raw part count, since a stream retry is about the attempt, not its last step.+- **A tool dialog that copies `tools` into state must remount on every open.** The dialogs stay mounted and only flip an open flag in their zustand store, so `useState(tools...)` keeps the first snapshot. The flow-tool dialog saved that snapshot over the agent's flow tools, which brought back flows removed since (AI-120). Key the dialog content on the open flag, as the flow-tool and knowledge-base dialogs do, or build the result from the live `tools` at save time, as the MCP dialog does.### Key filesdiff --git a/packages/web/src/features/agents/agent-tools/flow-tool-dialog/index.tsx b/packages/web/src/features/agents/agent-tools/flow-tool-dialog/index.tsxindex dc6f0e3f3fc..20eb61ce347 100644--- a/packages/web/src/features/agents/agent-tools/flow-tool-dialog/index.tsx+++ b/packages/web/src/features/agents/agent-tools/flow-tool-dialog/index.tsx@@ -35,17 +35,30 @@ type AgentFlowToolDialogProps = {export function AgentFlowToolDialog({onToolsUpdate,tools,+}: AgentFlowToolDialogProps) {+ const { showAddFlowDialog, setShowAddFlowDialog } = useFlowToolDialogStore();++ return (+ <Dialog open={showAddFlowDialog} onOpenChange={setShowAddFlowDialog}>+ <FlowToolDialogContent+ key={`flow-dialog-${showAddFlowDialog}`}+ tools={tools}+ onToolsUpdate={onToolsUpdate}+ />+ </Dialog>+ );+}++function FlowToolDialogContent({+ onToolsUpdate,+ tools,}: AgentFlowToolDialogProps) {const [selectedFlows, setSelectedFlows] = useState<AgentFlowTool[]>(tools.filter((tools) => tools.type === AgentToolType.FLOW),);- const {- showAddFlowDialog,- setShowAddFlowDialog,- searchQuery,- setSearchQuery,- } = useFlowToolDialogStore();+ const { setShowAddFlowDialog, searchQuery, setSearchQuery } =+ useFlowToolDialogStore();const { data } = agentQueries.useFlowsForAgent();@@ -69,45 +82,43 @@ export function AgentFlowToolDialog({};return (- <Dialog open={showAddFlowDialog} onOpenChange={setShowAddFlowDialog}>- <DialogContent className="w-[90vw] max-w-[750px] h-[80vh] max-h-[800px] flex flex-col overflow-hidden p-0">- <DialogHeader className="min-h-16 flex px-4 items-start justify-center mb-0 border-b">- <DialogTitle>{t('Add Flow Tools')}</DialogTitle>- </DialogHeader>-- <div className="px-4 py-3 border-b">- <div className="relative border rounded-md">- <Search className="absolute left-2 top-2.5 size-4 text-gray-11" />- <Input- placeholder={t('Search')}- value={searchQuery}- onChange={(e) => setSearchQuery(e.target.value)}- className="pl-9 shadow-none border-none"- />- </div>- </div>+ <DialogContent className="w-[90vw] max-w-[750px] h-[80vh] max-h-[800px] flex flex-col overflow-hidden p-0">+ <DialogHeader className="min-h-16 flex px-4 items-start justify-center mb-0 border-b">+ <DialogTitle>{t('Add Flow Tools')}</DialogTitle>+ </DialogHeader>- <ScrollArea className="grow overflow-y-auto">- <FlowDialogContent- flows={flows || []}- searchQuery={searchQuery}- selectedFlows={selectedFlows}- setSelectedFlows={setSelectedFlows}+ <div className="px-4 py-3 border-b">+ <div className="relative border rounded-md">+ <Search className="absolute left-2 top-2.5 size-4 text-gray-11" />+ <Input+ placeholder={t('Search')}+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ className="pl-9 shadow-none border-none"/>- </ScrollArea>-- <DialogFooter className="border-t p-4 mt-auto">- <CreateMcpFlowButton />- <DialogClose asChild>- <Button type="button" variant="ghost">- {t('Close')}- </Button>- </DialogClose>- <Button type="button" onClick={handleSave}>- {t('Save')}+ </div>+ </div>++ <ScrollArea className="grow overflow-y-auto">+ <FlowDialogContent+ flows={flows || []}+ searchQuery={searchQuery}+ selectedFlows={selectedFlows}+ setSelectedFlows={setSelectedFlows}+ />+ </ScrollArea>++ <DialogFooter className="border-t p-4 mt-auto">+ <CreateMcpFlowButton />+ <DialogClose asChild>+ <Button type="button" variant="ghost">+ {t('Close')}</Button>- </DialogFooter>- </DialogContent>- </Dialog>+ </DialogClose>+ <Button type="button" onClick={handleSave}>+ {t('Save')}+ </Button>+ </DialogFooter>+ </DialogContent>);}diff --git a/packages/web/test/features/agents/agent-tools/flow-tool-dialog.test.tsx b/packages/web/test/features/agents/agent-tools/flow-tool-dialog.test.tsxnew file mode 100644index 00000000000..2a7e059bc52--- /dev/null+++ b/packages/web/test/features/agents/agent-tools/flow-tool-dialog.test.tsx@@ -0,0 +1,192 @@+/**+ * @vitest-environment jsdom+ */+/* eslint-disable testing-library/no-unnecessary-act */+import {+ AgentFlowTool,+ AgentTool,+ AgentToolType,+ FlowOperationStatus,+ FlowStatus,+ FlowTriggerType,+ FlowVersionState,+ PopulatedFlow,+} from '@activepieces/shared';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const available = vi.hoisted(() => ({ flows: [] as PopulatedFlow[] }));++vi.mock('@/features/agents/hooks/agent-hooks', () => ({+ agentQueries: {+ useFlowsForAgent: () => ({ data: { data: available.flows } }),+ },+}));++vi.mock('@/features/pieces/components/piece-icon-list', () => ({+ PieceIconList: () => null,+}));++vi.mock(+ '@/features/agents/agent-tools/flow-tool-dialog/create-mcp-flow-button',+ () => ({ CreateMcpFlowButton: () => null }),+);++vi.mock('i18next', () => ({ t: (key: string) => key }));++declare global {+ // eslint-disable-next-line no-var+ var IS_REACT_ACT_ENVIRONMENT: boolean;+}++globalThis.IS_REACT_ACT_ENVIRONMENT = true;++import { AgentFlowToolDialog } from '@/features/agents/agent-tools/flow-tool-dialog';+import { useFlowToolDialogStore } from '@/features/agents/agent-tools/stores/flows-tools';++let container: HTMLDivElement;+let root: Root;++function buildFlow(name: string): PopulatedFlow {+ const now = new Date().toISOString();+ return {+ id: name,+ created: now,+ updated: now,+ projectId: 'project-1',+ externalId: name,+ ownerId: null,+ folderId: null,+ status: FlowStatus.ENABLED,+ publishedVersionId: null,+ metadata: null,+ operationStatus: FlowOperationStatus.NONE,+ timeSavedPerRun: null,+ templateId: null,+ createdBy: null,+ version: {+ id: `${name}-version`,+ created: now,+ updated: now,+ flowId: name,+ displayName: name,+ updatedBy: null,+ valid: true,+ schemaVersion: null,+ agentIds: [],+ state: FlowVersionState.LOCKED,+ connectionIds: [],+ backupFiles: null,+ notes: [],+ trigger: {+ name: 'trigger',+ valid: true,+ displayName: 'Trigger',+ type: FlowTriggerType.PIECE,+ settings: {+ pieceName: '@activepieces/piece-mcp',+ pieceVersion: '0.0.1',+ triggerName: 'mcp_tool',+ input: {},+ propertySettings: {},+ },+ lastUpdatedDate: now,+ },+ },+ };+}++function flowTool(name: string): AgentFlowTool {+ return {+ type: AgentToolType.FLOW,+ externalFlowId: name,+ toolName: name,+ flowDisplayName: name,+ };+}++function render({+ tools,+ onToolsUpdate,+}: {+ tools: AgentTool[];+ onToolsUpdate: (tools: AgentTool[]) => void;+}) {+ act(() => {+ root.render(+ <AgentFlowToolDialog tools={tools} onToolsUpdate={onToolsUpdate} />,+ );+ });+}++function setOpen(open: boolean) {+ act(() => {+ useFlowToolDialogStore.getState().setShowAddFlowDialog(open);+ });+}++function click(text: string) {+ const target = Array.from(+ document.body.querySelectorAll<HTMLElement>('button, div'),+ )+ .filter((element) => element.textContent?.trim() === text)+ .at(-1);+ if (!target) {+ throw new Error(`nothing to click with text "${text}"`);+ }+ act(() => {+ target.click();+ });+}++function savedFlowIds(onToolsUpdate: ReturnType<typeof vi.fn>): string[] {+ const [tools] = onToolsUpdate.mock.lastCall ?? [[]];+ return tools+ .filter((tool: AgentTool) => tool.type === AgentToolType.FLOW)+ .map((tool: AgentFlowTool) => tool.externalFlowId);+}++beforeEach(() => {+ available.flows = ['F1', 'F2', 'F3'].map(buildFlow);+ useFlowToolDialogStore.setState({ showAddFlowDialog: false });+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => {+ root.unmount();+ });+ container.remove();+});++describe('adding flow tools to an agent', () => {+ it('keeps a removed flow tool removed when another flow is added', () => {+ const onToolsUpdate = vi.fn();+ render({ tools: [flowTool('F1'), flowTool('F2')], onToolsUpdate });+ setOpen(true);+ setOpen(false);++ render({ tools: [flowTool('F1')], onToolsUpdate });+ setOpen(true);+ click('F3');+ click('Save');++ expect(savedFlowIds(onToolsUpdate)).toEqual(['F1', 'F3']);+ });++ it('drops flows ticked before the dialog was closed without saving', () => {+ const onToolsUpdate = vi.fn();+ render({ tools: [flowTool('F1')], onToolsUpdate });+ setOpen(true);+ click('F3');+ click('Close');++ setOpen(true);+ click('Save');++ expect(savedFlowIds(onToolsUpdate)).toEqual(['F1']);+ });+});