Skip to content

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

fix(agents): users couldn't set values for piece tools in agents manually (#16722)

ziyadev17bc6cacb885
diff --git a/packages/core/shared/package.json b/packages/core/shared/package.json
index 0a171843a36..c99872a1c4b 100644
--- a/packages/core/shared/package.json
+++ b/packages/core/shared/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/shared",
- "version": "0.206.1",
+ "version": "0.207.1",
"type": "commonjs",
"sideEffects": false,
"main": "./dist/src/index.js",
diff --git a/packages/core/shared/src/lib/automation/pieces/dto/piece-requests.ts b/packages/core/shared/src/lib/automation/pieces/dto/piece-requests.ts
index 9e546a7223a..4fcf8b634a6 100644
--- a/packages/core/shared/src/lib/automation/pieces/dto/piece-requests.ts
+++ b/packages/core/shared/src/lib/automation/pieces/dto/piece-requests.ts
@@ -87,8 +87,8 @@ export const PieceOptionRequest = z.object({
pieceVersion: VersionType,
actionOrTriggerName: z.string(),
propertyName: z.string(),
- flowId: z.string(),
- flowVersionId: z.string(),
+ flowId: z.string().optional(),
+ flowVersionId: z.string().optional(),
input: z.any(),
searchValue: z.string().optional(),
})
diff --git a/packages/core/utils/src/lib/connection-template.ts b/packages/core/utils/src/lib/connection-template.ts
index 0e21d147806..b733cc73969 100644
--- a/packages/core/utils/src/lib/connection-template.ts
+++ b/packages/core/utils/src/lib/connection-template.ts
@@ -7,4 +7,18 @@ function unwrapExternalId(auth: unknown): string | null {
return auth.match(CONNECTION_TEMPLATE)?.[1] ?? auth
}
-export const connectionTemplate = { unwrapExternalId }
+function isTemplate(auth: unknown): auth is string {
+ return typeof auth === 'string' && CONNECTION_TEMPLATE.test(auth)
+}
+
+function wrapExternalId(auth: unknown): string | null {
+ if (isTemplate(auth)) {
+ return auth
+ }
+ if (typeof auth !== 'string' || auth.length === 0) {
+ return null
+ }
+ return `{{connections['${auth}']}}`
+}
+
+export const connectionTemplate = { unwrapExternalId, isTemplate, wrapExternalId }
diff --git a/packages/core/utils/test/connection-template.test.ts b/packages/core/utils/test/connection-template.test.ts
new file mode 100644
index 00000000000..45c2a66b426
--- /dev/null
+++ b/packages/core/utils/test/connection-template.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest'
+import { connectionTemplate } from '../src/lib/connection-template'
+
+describe('connectionTemplate.wrapExternalId', () => {
+ it('wraps a raw external id', () => {
+ expect(connectionTemplate.wrapExternalId('abc')).toBe('{{connections[\'abc\']}}')
+ })
+
+ it('leaves an already wrapped value as it is', () => {
+ expect(connectionTemplate.wrapExternalId('{{connections[\'abc\']}}')).toBe('{{connections[\'abc\']}}')
+ })
+
+ it('returns null for an empty value', () => {
+ expect(connectionTemplate.wrapExternalId('')).toBeNull()
+ expect(connectionTemplate.wrapExternalId(undefined)).toBeNull()
+ })
+})
+
+describe('connectionTemplate.isTemplate', () => {
+ it('is true for a wrapped connection', () => {
+ expect(connectionTemplate.isTemplate('{{connections[\'abc\']}}')).toBe(true)
+ })
+
+ it('is false for a raw id or a non string', () => {
+ expect(connectionTemplate.isTemplate('abc')).toBe(false)
+ expect(connectionTemplate.isTemplate(undefined)).toBe(false)
+ })
+})
diff --git a/packages/server/api/src/app/pieces/metadata/piece-metadata-controller.ts b/packages/server/api/src/app/pieces/metadata/piece-metadata-controller.ts
index bac6258ee23..d301b11c70c 100644
--- a/packages/server/api/src/app/pieces/metadata/piece-metadata-controller.ts
+++ b/packages/server/api/src/app/pieces/metadata/piece-metadata-controller.ts
@@ -1,6 +1,6 @@
import { ActivepiecesError, ErrorCode, isEmpty, isNil, LocalesEnum } from '@activepieces/core-utils'
import { PieceMetadataModel, PieceMetadataModelSummary } from '@activepieces/pieces-framework'
-import { ALL_PRINCIPAL_TYPES, ApEdition, EngineResponse, EngineResponseStatus, GetPieceRequestParams, GetPieceRequestQuery, GetPieceRequestWithScopeParams, ListPiecesRequestQuery, PieceAudienceFilter, PieceCategory, PieceOptionRequest, Principal, PrincipalType, RegistryPiecesRequestQuery, SampleDataFileType, WorkerJobType } from '@activepieces/shared'
+import { ALL_PRINCIPAL_TYPES, ApEdition, EngineResponse, EngineResponseStatus, FlowVersion, GetPieceRequestParams, GetPieceRequestQuery, GetPieceRequestWithScopeParams, ListPiecesRequestQuery, PieceAudienceFilter, PieceCategory, PieceOptionRequest, Principal, PrincipalType, RegistryPiecesRequestQuery, SampleDataFileType, WorkerJobType } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
import { StatusCodes } from 'http-status-codes'
@@ -133,14 +133,10 @@ const basePiecesController: FastifyPluginAsyncZod = async (app) => {
async (req) => {
const projectId = req.projectId
const platform = req.principal.platform
- const flow = await flowService(req.log).getOnePopulatedOrThrow({
+ const flowVersion = await getFlowVersionForOptions({ projectId, flowId: req.body.flowId, flowVersionId: req.body.flowVersionId, log: req.log })
+ const sampleData = isNil(flowVersion) ? {} : await sampleDataService(req.log).getSampleDataForFlow({
projectId,
- id: req.body.flowId,
- versionId: req.body.flowVersionId,
- })
- const sampleData = await sampleDataService(req.log).getSampleDataForFlow({
- projectId,
- flowVersion: flow.version,
+ flowVersion,
type: SampleDataFileType.OUTPUT,
referencedBy: req.body.input,
})
@@ -148,7 +144,7 @@ const basePiecesController: FastifyPluginAsyncZod = async (app) => {
jobType: WorkerJobType.EXECUTE_PROPERTY,
platformId: platform.id,
projectId,
- flowVersion: flow.version,
+ flowVersion,
propertyName: req.body.propertyName,
actionOrTriggerName: req.body.actionOrTriggerName,
input: req.body.input,
@@ -173,6 +169,18 @@ const basePiecesController: FastifyPluginAsyncZod = async (app) => {
}
+async function getFlowVersionForOptions({ projectId, flowId, flowVersionId, log }: GetFlowVersionForOptionsParams): Promise<FlowVersion | undefined> {
+ if (isNil(flowId)) {
+ return undefined
+ }
+ const flow = await flowService(log).getOnePopulatedOrThrow({
+ projectId,
+ id: flowId,
+ versionId: flowVersionId,
+ })
+ return flow.version
+}
+
async function assertProjectAccess({ principal, projectId, log }: AssertProjectAccessParams): Promise<void> {
if (![ApEdition.ENTERPRISE, ApEdition.CLOUD].includes(system.getEdition())) {
return
@@ -288,6 +296,13 @@ const DeletePieceRequest = {
},
}
+type GetFlowVersionForOptionsParams = {
+ projectId: string
+ flowId: string | undefined
+ flowVersionId: string | undefined
+ log: FastifyBaseLogger
+}
+
type AssertProjectAccessParams = {
principal: Principal
projectId: string | undefined
diff --git a/packages/web/src/app/builder/builder-hooks.ts b/packages/web/src/app/builder/builder-hooks.ts
index 618d806f1dc..60751b48e44 100644
--- a/packages/web/src/app/builder/builder-hooks.ts
+++ b/packages/web/src/app/builder/builder-hooks.ts
@@ -1,7 +1,8 @@
+import { isNil } from '@activepieces/core-utils';
import { QueryClient } from '@tanstack/react-query';
import { createContext, useContext } from 'react';
import { Socket } from 'socket.io-client';
-import { create, useStore } from 'zustand';
+import { create, createStore, useStore } from 'zustand';
import { CanvasState, createCanvasState } from './state/canvas-state';
import { ChatState, createChatState } from './state/chat-state';
@@ -29,6 +30,15 @@ export function useBuilderStateContext<T>(
return useStore(useBuilderStore(), selector);
}
+export function useOptionalBuilderStateContext<T>(
+ selector: (state: BuilderState) => T,
+): T | null {
+ const store = useContext(BuilderStateContext) ?? noBuilderStore;
+ return useStore(store, (state) => (isNil(state) ? null : selector(state)));
+}
+
+const noBuilderStore = createStore<BuilderState | null>(() => null);
+
export type BuilderState = FlowState &
PieceSelectorState &
RunState &
diff --git a/packages/web/src/app/builder/piece-properties/dynamic-dropdown-piece-property.tsx b/packages/web/src/app/builder/piece-properties/dynamic-dropdown-piece-property.tsx
index f42d9fc02b4..f8c6f4c13b9 100644
--- a/packages/web/src/app/builder/piece-properties/dynamic-dropdown-piece-property.tsx
+++ b/packages/web/src/app/builder/piece-properties/dynamic-dropdown-piece-property.tsx
@@ -6,7 +6,7 @@ import { t } from 'i18next';
import React, { useContext, useEffect, useRef, useState } from 'react';
import { UseFormReturn, useWatch } from 'react-hook-form';
-import { useBuilderStateContext } from '@/app/builder/builder-hooks';
+import { useOptionalBuilderStateContext } from '@/app/builder/builder-hooks';
import { SearchableSelect } from '@/components/custom/searchable-select';
import { piecesHooks } from '@/features/pieces';
import { authenticationSession } from '@/lib/authentication-session';
@@ -18,10 +18,11 @@ import { DynamicPropertiesContext } from './dynamic-properties-context';
const DynamicDropdownPiecePropertyImplementation = React.memo(
(props: DynamicDropdownProps) => {
- const [flowVersion, readonly] = useBuilderStateContext((state) => [
- state.flowVersion,
- state.readonly,
- ]);
+ const flowVersion = useOptionalBuilderStateContext(
+ (state) => state.flowVersion,
+ );
+ const readonly =
+ useOptionalBuilderStateContext((state) => state.readonly) ?? false;
const isFirstRender = useRef(true);
const previousValues = useRef<undefined | unknown[]>(undefined);
@@ -122,8 +123,8 @@ const DynamicDropdownPiecePropertyImplementation = React.memo(
propertyName: props.propertyName,
actionOrTriggerName: props.actionOrTriggerName,
input,
- flowVersionId: flowVersion.id,
- flowId: flowVersion.flowId,
+ flowVersionId: flowVersion?.id,
+ flowId: flowVersion?.flowId,
searchValue: term,
},
propertyType: PropertyType.DROPDOWN,
diff --git a/packages/web/src/app/builder/piece-properties/dynamic-piece-property.tsx b/packages/web/src/app/builder/piece-properties/dynamic-piece-property.tsx
index 5c4d1b9d63c..6d697876897 100644
--- a/packages/web/src/app/builder/piece-properties/dynamic-piece-property.tsx
+++ b/packages/web/src/app/builder/piece-properties/dynamic-piece-property.tsx
@@ -9,7 +9,7 @@ import React, { useState, useRef, useContext } from 'react';
import { useFormContext, UseFormReturn, useWatch } from 'react-hook-form';
import { useDeepCompareEffectNoCheck } from 'use-deep-compare-effect';
-import { useBuilderStateContext } from '@/app/builder/builder-hooks';
+import { useOptionalBuilderStateContext } from '@/app/builder/builder-hooks';
import { SkeletonList } from '@/components/ui/skeleton';
import { piecesHooks, formUtils } from '@/features/pieces';
import { authenticationSession } from '@/lib/authentication-session';
@@ -36,10 +36,11 @@ const removeOptionsFromDropdownPropertiesSchema = (
const DynamicPropertiesImplementation = React.memo(
(props: DynamicPropertiesProps) => {
- const [flowVersion, readonly] = useBuilderStateContext((state) => [
- state.flowVersion,
- state.readonly,
- ]);
+ const flowVersion = useOptionalBuilderStateContext(
+ (state) => state.flowVersion,
+ );
+ const readonly =
+ useOptionalBuilderStateContext((state) => state.readonly) ?? false;
const form = useFormContext();
const watchConfig: Record<string, unknown> = {
name:
@@ -142,8 +143,8 @@ const DynamicPropertiesImplementation = React.memo(
propertyName: props.propertyName,
actionOrTriggerName: props.actionOrTriggerName,
input: refresherValues,
- flowVersionId: flowVersion.id,
- flowId: flowVersion.flowId,
+ flowVersionId: flowVersion?.id,
+ flowId: flowVersion?.flowId,
},
propertyType: PropertyType.DYNAMIC,
},
diff --git a/packages/web/src/app/builder/step-settings/agent-settings/piece-tool-dialog.tsx b/packages/web/src/app/builder/step-settings/agent-settings/piece-tool-dialog.tsx
index b4b9464f6d8..6d7221880e3 100644
--- a/packages/web/src/app/builder/step-settings/agent-settings/piece-tool-dialog.tsx
+++ b/packages/web/src/app/builder/step-settings/agent-settings/piece-tool-dialog.tsx
@@ -6,6 +6,7 @@ import { useMemo, useEffect } from 'react';
import { toast } from 'sonner';
import { useDebounce } from 'use-debounce';
+import { LogoPlate } from '@/components/custom/logo-plate';
import { Button } from '@/components/ui/button';
import {
Dialog,
@@ -194,7 +195,20 @@ export function AgentPieceDialog({
</TooltipTrigger>
<TooltipContent>{t('Back')}</TooltipContent>
</Tooltip>
- {selectedAction.displayName}
+ <LogoPlate
+ className="size-9 rounded-md p-1.5"
+ border
+ src={selectedPiece?.logoUrl}
+ alt=""
+ />
+ <div className="min-w-0 flex flex-col">
+ <span>{selectedAction.displayName}</span>
+ {selectedAction.description && (
+ <span className="text-xs font-normal text-gray-11 line-clamp-1">
+ {selectedAction.description}
+ </span>
+ )}
+ </div>
</div>
)
);
@@ -204,7 +218,7 @@ export function AgentPieceDialog({
return (
<Dialog open={showAddPieceDialog} onOpenChange={handleDialogClose}>
- <DialogContent className="w-[90vw] max-w-[750px] h-[80vh] max-h-[800px] flex flex-col overflow-hidden p-0">
+ <DialogContent className="w-[90vw] max-w-[750px] h-[80vh] max-h-[800px] flex flex-col gap-0 overflow-hidden p-0">
<DialogHeader className="min-h-16 flex px-4 items-start justify-center mb-0 border-b">
<DialogTitle>{renderDialogHeaderContent()}</DialogTitle>
</DialogHeader>
diff --git a/packages/web/src/app/builder/step-settings/agent-settings/predefined-inputs-form.tsx b/packages/web/src/app/builder/step-settings/agent-settings/predefined-inputs-form.tsx
index 811360e7869..9372ed01cb8 100644
--- a/packages/web/src/app/builder/step-settings/agent-settings/predefined-inputs-form.tsx
+++ b/packages/web/src/app/builder/step-settings/agent-settings/predefined-inputs-form.tsx
@@ -1,4 +1,4 @@
-import { isNil } from '@activepieces/core-utils';
+import { connectionTemplate, isNil } from '@activepieces/core-utils';
import { PieceProperty, PropertyType } from '@activepieces/pieces-framework';
import { FieldControlMode, PredefinedInputField } from '@activepieces/shared';
import { zodResolver } from '@hookform/resolvers/zod';
@@ -7,9 +7,10 @@ import { useEffect, useMemo } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
-import { LogoPlate } from '@/components/custom/logo-plate';
+import { ConnectionSelect } from '@/app/connections/connection-select';
import { ApMarkdown } from '@/components/custom/markdown';
import { Form, FormField } from '@/components/ui/form';
+import { Label } from '@/components/ui/label';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
Select,
@@ -18,11 +19,11 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
-import {
- ConnectionDropdown,
- usePieceToolsDialogStore,
-} from '@/features/agents';
+import { Skeleton } from '@/components/ui/skeleton';
+import { usePieceToolsDialogStore } from '@/features/agents';
+import { appConnectionsQueries } from '@/features/connections';
import { piecesHooks } from '@/features/pieces';
+import { authenticationSession } from '@/lib/authentication-session';
import { selectGenericFormComponentForProperty } from '../../piece-properties/properties-utils';
@@ -46,9 +47,21 @@ export const PredefinedInputsForm = () => {
selectedAction,
selectedPiece: piece,
} = usePieceToolsDialogStore();
- const { pieces } = piecesHooks.usePieces({});
+ const { pieces, isLoading: isLoadingPieces } = piecesHooks.usePieces({});
const selectedPiece = pieces?.find((p) => p.name === piece?.pieceName);
const requireAuth = selectedAction?.requireAuth ?? true;
+ const { isLoading: isLoadingConnections } =
+ appConnectionsQueries.useAppConnections({
+ request: {
+ pieceName: selectedPiece?.name ?? '',
+ projectId: authenticationSession.getProjectId()!,
+ limit: 1000,
+ },
+ pieceAuth: selectedPiece?.auth,
+ extraKeys: [selectedPiece?.name, authenticationSession.getProjectId()!],
+ staleTime: 0,
+ enabled: requireAuth && !isNil(selectedPiece?.auth),
+ });
const formSchema = useMemo(
() => createPredefinedInputsFormSchema(requireAuth),
[requireAuth],
@@ -67,8 +80,9 @@ export const PredefinedInputsForm = () => {
);
const defaultValues = useMemo<PredefinedInputsFormValues>(() => {
const values: PredefinedInputsFormValues = {};
- if (requireAuth && predefinedInputs?.auth) {
- values.auth = predefinedInputs.auth;
+ const auth = connectionTemplate.wrapExternalId(predefinedInputs?.auth);
+ if (requireAuth && !isNil(auth)) {
+ values.auth = auth;
}
if (predefinedInputs?.fields) {
Object.entries(predefinedInputs.fields).forEach(([key, field]) => {
@@ -113,13 +127,12 @@ export const PredefinedInputsForm = () => {
return () => subscription.unsubscribe();
}, [form, setPredefinedInputs]);
- const handleAuthChange = (value: string | null) => {
- const newAuth = !isNil(value) ? value : undefined;
+ const handleAuthChange = (value: string) => {
setPredefinedInputs({
- auth: newAuth,
+ auth: connectionTemplate.unwrapExternalId(value) ?? undefined,
fields: predefinedInputs?.fields || {},
});
- form.setValue('auth', value ?? '');
+ form.setValue('auth', value);
};
const getModeForProperty = (propertyName: string): FieldControlMode =>
predefinedInputs?.fields?.[propertyName]?.mode ??
@@ -151,120 +164,115 @@ export const PredefinedInputsForm = () => {
}
};
const pieceHasAuth = requireAuth && selectedPiece?.auth;
+ if (isLoadingPieces || isLoadingConnections) {
+ return (
+ <div className="flex flex-col gap-4 p-4">
+ {Array.from({ length: 4 }).map((_, index) => (
+ <Skeleton key={index} className="w-full h-10" />
+ ))}
+ </div>
+ );
+ }
return (
<Form {...form}>
<ScrollArea className="h-full">
- <div className="flex items-start border-b gap-3 p-4">
- <LogoPlate
- className="size-11 rounded-md p-1.5"
- border
- src={selectedPiece?.logoUrl}
- alt=""
- />
- <div className="min-w-0 flex-1">
- <div className="text-sm font-medium">
- {selectedAction?.displayName}
- </div>
- {selectedAction?.description && (
- <p className="mt-0.5 text-xs text-gray-11 line-clamp-2">
- {selectedAction.description}
- </p>
- )}
- </div>
- </div>
- <div className="space-y-6 p-4">
- {pieceHasAuth && !isNil(selectedPiece) && (
- <ConnectionDropdown
+ {pieceHasAuth && !isNil(selectedPiece) && (
+ <div className="flex flex-col gap-2 p-4 border-b">
+ <Label showRequiredIndicator>{t('Connection')}</Label>
+ <ConnectionSelect
piece={selectedPiece}
- value={form.watch('auth') as string | null}
+ value={
+ connectionTemplate.wrapExternalId(form.watch('auth')) ??
+ undefined
+ }
onChange={handleAuthChange}
- placeholder={t('Connect your account')}
/>
- )}
- {Object.keys(properties).length > 0 && (
- <div className="space-y-5">
- {Object.entries(properties).map(([propertyName, property]) => {
- const isMarkdown = property.type === PropertyType.MARKDOWN;
-
- if (isMarkdown) {
- return (
- <ApMarkdown
- key={propertyName}
- markdown={property.description}
- variables={{}}
- variant={property.variant}
- />
- );
- }
+ </div>
+ )}
+ {Object.keys(properties).length > 0 && (
+ <div className="flex flex-col gap-3 p-4">
+ <span className="text-xs text-gray-11">{t('Inputs')}</span>
+ {Object.entries(properties).map(([propertyName, property]) => {
+ const isMarkdown = property.type === PropertyType.MARKDOWN;
- const mode = getModeForProperty(propertyName);
- const showInput = mode === FieldControlMode.CHOOSE_YOURSELF;
+ if (isMarkdown) {
return (
- <div key={propertyName} className="space-y-2">
- <div className="flex items-center justify-between">
- <h3 className="text-sm font-medium">
- {property.displayName} {property.required && '*'}
- </h3>
- <Select
- value={mode}
- onValueChange={(v) =>
- handleModeChange(propertyName, v as FieldControlMode)
- }
- >
- <SelectTrigger className="w-80">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value={FieldControlMode.AGENT_DECIDE}>
- {t('Let agent decide')}
- </SelectItem>
- <SelectItem value={FieldControlMode.CHOOSE_YOURSELF}>
- {t('Set value myself')}
+ <ApMarkdown
+ key={propertyName}
+ markdown={property.description}
+ variables={{}}
+ variant={property.variant}
+ />
+ );
+ }
+
+ const mode = getModeForProperty(propertyName);
+ const showInput = mode === FieldControlMode.CHOOSE_YOURSELF;
+ return (
+ <div key={propertyName} className="space-y-2">
+ <div className="flex items-center justify-between">
+ <Label showRequiredIndicator={property.required}>
+ {property.displayName}
+ </Label>
+ <Select
+ value={mode}
+ onValueChange={(v) =>
+ handleModeChange(propertyName, v as FieldControlMode)
+ }
+ >
+ <SelectTrigger className="w-80">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={FieldControlMode.AGENT_DECIDE}>
+ {t('Let agent decide')}
+ </SelectItem>
+ <SelectItem value={FieldControlMode.CHOOSE_YOURSELF}>
+ {t('Set value myself')}
+ </SelectItem>
+ {!property.required && (
+ <SelectItem value={FieldControlMode.LEAVE_EMPTY}>
+ {t('Leave empty')}
</SelectItem>
- {!property.required && (
- <SelectItem value={FieldControlMode.LEAVE_EMPTY}>
- {t('Leave empty')}
- </SelectItem>
- )}
- </SelectContent>
- </Select>
- </div>
- {showInput && (
- <FormField
- name={propertyName}
- control={form.control}
- render={({ field }) =>
- selectGenericFormComponentForProperty({
- field,
- hideLabel: true,
- propertyName,
- inputName: propertyName,
- property,
- allowDynamicValues: false,
- markdownVariables: {},
- useMentionTextInput: true,
- disabled: false,
- dynamicInputModeToggled: false,
- form,
- dynamicPropsInfo: {
- pieceName: selectedPiece?.name ?? '',
- pieceVersion: selectedPiece?.version ?? '',
- actionOrTriggerName: selectedAction?.name ?? '',
- placedInside: 'predefinedAgentInputs',
- updateFormSchema: null,
- updatePropertySettingsSchema: null,
- },
- propertySettings: null,
- })
- }
- />
- )}
+ )}
+ </SelectContent>
+ </Select>
</div>
- );
- })}
- </div>
- )}
- </div>
+ {showInput && (
+ <FormField
+ name={propertyName}
+ control={form.control}
+ render={({ field }) =>
+ selectGenericFormComponentForProperty({
+ field,
+ hideLabel: true,
+ propertyName,
+ inputName: propertyName,
+ property,
+ allowDynamicValues: false,
+ markdownVariables: {},
+ useMentionTextInput: true,
+ disabled: false,
+ dynamicInputModeToggled: false,
+ form,
+ dynamicPropsInfo: {
+ pieceName: selectedPiece?.name ?? '',
+ pieceVersion: selectedPiece?.version ?? '',
+ actionOrTriggerName: selectedAction?.name ?? '',
+ placedInside: 'predefinedAgentInputs',
+ updateFormSchema: null,
+ updatePropertySettingsSchema: null,
+ },
+ propertySettings: null,
+ })
+ }
+ />
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
</ScrollArea>
</Form>
);
diff --git a/packages/web/src/app/builder/step-settings/piece-settings/connection-select.tsx b/packages/web/src/app/builder/step-settings/piece-settings/connection-select.tsx
deleted file mode 100644
index 3249a87edd7..00000000000
--- a/packages/web/src/app/builder/step-settings/piece-settings/connection-select.tsx
+++ /dev/null
@@ -1,416 +0,0 @@
-import { Permission, isNil } from '@activepieces/core-utils';
-import {
- PieceMetadataModel,
- PieceMetadataModelSummary,
-} from '@activepieces/pieces-framework';
-import {
- AppConnectionScope,
- AppConnectionStatus,
- AppConnectionWithoutSensitiveData,
- PieceAction,
- PieceAudienceFilter,
- PieceTrigger,
- PropertyExecutionType,
-} from '@activepieces/shared';
-import { t } from 'i18next';
-import {
- Plus,
- Globe,
- Key,
- Cable,
- Check,
- Unplug,
- X,
- LucideIcon,
-} from 'lucide-react';
-import { useState } from 'react';
-import { useFormContext } from 'react-hook-form';
-
-import { AutoFormFieldWrapper } from '@/app/builder/piece-properties/auto-form-field-wrapper';
-import { CreateOrEditConnectionDialog } from '@/app/connections/create-edit-connection-dialog';
-import { PermissionNeededTooltip } from '@/components/custom/permission-needed-tooltip';
-import { SearchableSelect } from '@/components/custom/searchable-select';
-import { Button } from '@/components/ui/button';
-import { FormField, FormLabel } from '@/components/ui/form';
-import {
- Select,
- SelectAction,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from '@/components/ui/select';
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from '@/components/ui/tooltip';
-import {
- appConnectionsQueries,
- appConnectionUtils,
-} from '@/features/connections';
-import { piecesHooks } from '@/features/pieces';
-import {
- useAuthorization,
- useIsPlatformAdmin,
-} from '@/hooks/authorization-hooks';
-import { authenticationSession } from '@/lib/authentication-session';
-import { cn } from '@/lib/utils';
-
-function ConnectionSelect(params: ConnectionSelectProps) {
- const [connectionDialogOpen, setConnectionDialogOpen] = useState(false);
- const [selectConnectionOpen, setSelectConnectionOpen] = useState(false);
- const [reconnectConnection, setReconnectConnection] =
- useState<AppConnectionWithoutSensitiveData | null>(null);
- //in case of reconnection we need to use the piece version from the connection
- const { pieceModel: pieceWithCorrectVersion, isLoading: isLoadingPiece } =
- piecesHooks.usePiece({
- name: params.piece.name,
- version: reconnectConnection?.pieceVersion ?? params.piece.version,
- audience: PieceAudienceFilter.ALL,
- });
- const form = useFormContext<PieceAction | PieceTrigger>();
- const hasPermissionToCreateConnection = useAuthorization().checkAccess(
- Permission.WRITE_APP_CONNECTION,
- );
- const {
- data: connections,
- isLoading: isLoadingConnections,
- refetch,
- } = appConnectionsQueries.useAppConnections({
- request: {
- pieceName: params.piece.name,
- projectId: authenticationSession.getProjectId()!,
- limit: 1000,
- },
- pieceAuth: params.piece.auth,
- extraKeys: [params.piece.name, authenticationSession.getProjectId()!],
- staleTime: 0,
- });
- const selectedConnection = connections?.data?.find(
- (connection) =>
- connection.externalId ===
- removeBrackets(form.getValues().settings.input.auth ?? ''),
- );
- const isSelectedConnectionGlobal =
- selectedConnection?.scope === AppConnectionScope.PLATFORM;
- // The create/reconnect dialog runs in global (PLATFORM) scope ONLY when
- // reconnecting an existing global connection. Creating a brand-new connection
- // from a project flow must default to PROJECT scope, otherwise it silently
- // inherits the selected connection's platform scope and (for non-admins) hits
- // the platform-admin-only global-connections endpoint (GIT-1587).
- const isReconnectingGlobalConnection =
- reconnectConnection?.scope === AppConnectionScope.PLATFORM;
- const dynamicInputModeToggled =
- form.getValues().settings.propertySettings['auth']?.type ===
- PropertyExecutionType.DYNAMIC;
- const isPlatformAdmin = useIsPlatformAdmin();
- const statusDisplay = selectedConnection
- ? getConnectionStatusDisplay(selectedConnection.status)
- : null;
- const canShowConnectionStatus =
- !!selectedConnection && (!isSelectedConnectionGlobal || isPlatformAdmin);
- const openReconnectDialog = () => {
- setReconnectConnection(selectedConnection ?? null);
- setSelectConnectionOpen(false);
- setConnectionDialogOpen(true);
- };
-
- return (
- <FormField
- control={form.control}
- key={
- dynamicInputModeToggled
- ? 'auth-dynamic'
- : `auth-${form.getValues().settings.input.auth}`
- }
- name={'settings.input.auth'}
- render={({ field }) => (
- <>
- {(isLoadingConnections || !pieceWithCorrectVersion) && (
- <div className="flex flex-col gap-2">
- <FormLabel showRequiredIndicator>{t('Connection')}</FormLabel>
- <SearchableSelect
- options={[]}
- disabled={true}
- loading={isLoadingConnections}
- placeholder={t('Select a connection')}
- value={field.value as React.Key}
- onChange={(value) => field.onChange(value)}
- showDeselect={false}
- onRefresh={() => {}}
- showRefresh={false}
- />
- </div>
- )}
- {!isLoadingConnections &&
- pieceWithCorrectVersion &&
- params.piece.auth && (
- <AutoFormFieldWrapper
- property={params.piece.auth}
- propertyName="auth"
- field={field}
- disabled={params.disabled}
- inputName="settings.input.auth"
- allowDynamicValues={!params.isTrigger}
- dynamicInputModeToggled={dynamicInputModeToggled}
- isForConnectionSelect={true}
- >
- <CreateOrEditConnectionDialog
- reconnectConnection={reconnectConnection}
- isGlobalConnection={isReconnectingGlobalConnection}
- piece={pieceWithCorrectVersion}
- key={`CreateOrEditConnectionDialog-open-${connectionDialogOpen}`}
- open={connectionDialogOpen}
- setOpen={(open, connection) => {
- setConnectionDialogOpen(open);
- if (connection) {
- refetch();
- field.onChange(addBrackets(connection.externalId));
- }
- }}
- ></CreateOrEditConnectionDialog>
- <Select
- open={selectConnectionOpen}
- onOpenChange={setSelectConnectionOpen}
- defaultValue={field.value as string | undefined}
- onValueChange={field.onChange}
- disabled={params.disabled}
- >
- <div className="relative">
- {field.value &&
- !field.disabled &&
- canShowConnectionStatus &&
- statusDisplay && (
- <div className="z-50 absolute right-8 top-1.5 flex items-center gap-1.5 pointer-events-none">
- <span className="flex items-center gap-1 text-xs text-gray-11 select-none pointer-events-none">
- <statusDisplay.Icon
- className={cn(
- 'size-3.5 shrink-0',
- statusDisplay.iconClassName,
- )}
- />
- {statusDisplay.label}
- </span>
- <Tooltip>
- <TooltipTrigger asChild>
- <span className="inline-flex pointer-events-auto">
- <Button
- variant="ghost"
- size="icon-xs"
- loading={isLoadingPiece}
- onClick={(e) => {
- e.stopPropagation();
- openReconnectDialog();
- }}
- disabled={!hasPermissionToCreateConnection}
- >
- <Cable className="size-3.5" />
- </Button>
- </span>
- </TooltipTrigger>
- <TooltipContent>
- {!hasPermissionToCreateConnection
- ? t('Permission needed')
- : t('Reconnect')}
- </TooltipContent>
- </Tooltip>
- </div>
- )}
-
- <SelectTrigger className="flex gap-2 items-center">
- <SelectValue
- className="truncate grow shrink"
- placeholder={t('Select a connection')}
- data-testid="select-connection-value"
- >
- <SelectedConnectionLabel
- value={field.value}
- connections={connections?.data ?? []}
- />
- </SelectValue>
- <div className="grow"></div>
- {field.value &&
- !field.disabled &&
- canShowConnectionStatus &&
- statusDisplay && (
- <span
- aria-hidden
- className="z-50 opacity-0 pointer-events-none flex items-center gap-1.5"
- >
- <span className="flex items-center gap-1 text-xs">
- <statusDisplay.Icon className="size-3.5 shrink-0" />
- {statusDisplay.label}
- </span>
- <span className="size-6 shrink-0" />
- </span>
- )}
- </SelectTrigger>
- </div>
-
- <SelectContent>
- <PermissionNeededTooltip
- hasPermission={hasPermissionToCreateConnection}
- >
- <SelectAction
- onClick={() => {
- setSelectConnectionOpen(false);
- setReconnectConnection(null);
- setConnectionDialogOpen(true);
- }}
- disabled={!hasPermissionToCreateConnection}
- >
- <span
- className={cn(
- 'flex items-center gap-1 text-accent-11 w-full',
- {
- 'text-gray-11 cursor-not-allowed':
- !hasPermissionToCreateConnection,
- },
- )}
- >
- <Plus size={16} />
- {t('Create Connection')}
- </span>
- </SelectAction>
- </PermissionNeededTooltip>
-
- {connections &&
- connections.data &&
- connections.data?.map((connection) => {
- const accountIdentifier =
- appConnectionUtils.getConnectionAccountIdentifier(
- connection,
- );
- const rowStatus =
- connection.status !== AppConnectionStatus.ACTIVE
- ? getConnectionStatusDisplay(connection.status)
- : null;
- return (
- <SelectItem
- value={addBrackets(connection.externalId)}
- key={connection.externalId}
- className="*:[span]:last:w-full"
- >
- <div className="flex items-center gap-2 w-full min-w-0">
- {connection.usingSecretManager && (
- <Key size={16} className="shrink-0" />
- )}
- {connection.scope ===
- AppConnectionScope.PLATFORM && (
- <Globe size={16} className="shrink-0" />
- )}
- <span className="truncate min-w-0">
- {connection.displayName}
- </span>
- {accountIdentifier && (
- <span className="ml-auto shrink-0 truncate max-w-[50%] text-xs text-gray-11">
- {accountIdentifier}
- </span>
- )}
- {rowStatus && (
- <span
- className={cn(
- 'flex items-center gap-1 text-xs text-gray-11 shrink-0',
- { 'ml-auto': !accountIdentifier },
- )}
- >
- <rowStatus.Icon
- className={cn(
- 'size-3.5 shrink-0',
- rowStatus.iconClassName,
- )}
- />
- {rowStatus.label}
- </span>
- )}
- </div>
- </SelectItem>
- );
- })}
- </SelectContent>
- </Select>
- </AutoFormFieldWrapper>
- )}
- </>
- )}
- ></FormField>
- );
-}
-
-ConnectionSelect.displayName = 'ConnectionSelect';
-export { ConnectionSelect };
-
-type ConnectionSelectProps = {
- disabled: boolean;
- piece: PieceMetadataModelSummary | PieceMetadataModel;
- isTrigger: boolean;
-};
-function addBrackets(str: string) {
- return `{{connections['${str}']}}`;
-}
-function removeBrackets(str: string | undefined) {
- if (isNil(str)) {
- return undefined;
- }
- return str.replace(
- /\{\{connections\['(.*?)'\]\}\}/g,
- (_, connectionName) => connectionName,
- );
-}
-function SelectedConnectionLabel({
- value,
- connections,
-}: {
- value: string | undefined;
- connections: AppConnectionWithoutSensitiveData[];
-}) {
- if (isNil(value) || value === '') {
- return null;
- }
- const connection = connections.find(
- (connection) => connection.externalId === removeBrackets(value),
- );
- if (isNil(connection)) {
- return (
- <div className="truncate grow shrink flex items-center gap-2 text-gray-11">
- <Unplug size={16} className="shrink-0 text-danger-11" />
- {t('Connection not found')}
- </div>
- );
- }
- return (
- <div className="truncate grow shrink flex items-center gap-2">
- {connection.scope === AppConnectionScope.PLATFORM && (
- <Globe size={16} className="shrink-0" />
- )}
- {connection.displayName}
- </div>
- );
-}
-function getConnectionStatusDisplay(status: AppConnectionStatus): {
- Icon: LucideIcon;
- iconClassName: string;
- label: string;
-} {
- switch (status) {
- case AppConnectionStatus.ACTIVE:
- return {
- Icon: Check,
- iconClassName: 'text-success-11',
- label: t('Connected'),
- };
- case AppConnectionStatus.ERROR:
- return {
- Icon: X,
- iconClassName: 'text-danger-11',
- label: t('Error'),
- };
- case AppConnectionStatus.MISSING:
- return {
- Icon: Unplug,
- iconClassName: 'text-gray-11',
- label: t('Missing'),
- };
- }
-}
diff --git a/packages/web/src/app/builder/step-settings/piece-settings/index.tsx b/packages/web/src/app/builder/step-settings/piece-settings/index.tsx
index 6cf05e39902..63ec69cf9f4 100644
--- a/packages/web/src/app/builder/step-settings/piece-settings/index.tsx
+++ b/packages/web/src/app/builder/step-settings/piece-settings/index.tsx
@@ -10,9 +10,14 @@ import {
PieceActionSettings,
PieceTrigger,
PieceTriggerSettings,
+ PropertyExecutionType,
} from '@activepieces/shared';
import React from 'react';
+import { useFormContext } from 'react-hook-form';
+import { AutoFormFieldWrapper } from '@/app/builder/piece-properties/auto-form-field-wrapper';
+import { ConnectionSelect } from '@/app/connections/connection-select';
+import { FormField } from '@/components/ui/form';
import { Skeleton } from '@/components/ui/skeleton';
import { flagsHooks } from '@/hooks/flags-hooks';
@@ -23,8 +28,6 @@ import { GenericPropertiesForm } from '../../piece-properties/generic-properties
import { PieceNotAvailableAlert } from '../piece-not-available-alert';
import { useStepSettingsContext } from '../step-settings-context';
-import { ConnectionSelect } from './connection-select';
-
const PieceSettings = React.memo((props: PieceSettingsProps) => {
const {
pieceModel,
@@ -33,6 +36,7 @@ const PieceSettings = React.memo((props: PieceSettingsProps) => {
updateFormSchema,
updatePropertySettingsSchema,
} = useStepSettingsContext();
+ const form = useFormContext<PieceAction | PieceTrigger>();
const actionName = (props.step.settings as PieceActionSettings).actionName;
const selectedAction = actionName
@@ -75,6 +79,10 @@ const PieceSettings = React.memo((props: PieceSettingsProps) => {
!isNil(selectedAction) && (selectedAction.requireAuth ?? true);
const showAuthForTrigger =
!isNil(selectedTrigger) && (selectedTrigger.requireAuth ?? true);
+ const pieceAuth = pieceModel?.auth;
+ const authDynamicInputModeToggled =
+ form.getValues().settings.propertySettings['auth']?.type ===
+ PropertyExecutionType.DYNAMIC;
if (!pieceModel && pieceModelNotFound) {
return (
@@ -142,12 +150,35 @@ const PieceSettings = React.memo((props: PieceSettingsProps) => {
{pieceModel && (
<>
- {pieceModel.auth && (showAuthForAction || showAuthForTrigger) && (
- <ConnectionSelect
- isTrigger={!isNil(selectedTrigger)}
- piece={pieceModel}
- disabled={props.readonly}
- ></ConnectionSelect>
+ {pieceAuth && (showAuthForAction || showAuthForTrigger) && (
+ <FormField
+ control={form.control}
+ key={
+ authDynamicInputModeToggled
+ ? 'auth-dynamic'
+ : `auth-${form.getValues().settings.input.auth}`
+ }
+ name={'settings.input.auth'}
+ render={({ field }) => (
+ <AutoFormFieldWrapper
+ property={pieceAuth}
+ propertyName="auth"
+ field={field}
+ disabled={props.readonly}
+ inputName="settings.input.auth"
+ allowDynamicValues={isNil(selectedTrigger)}
+ dynamicInputModeToggled={authDynamicInputModeToggled}
+ isForConnectionSelect={true}
+ >
+ <ConnectionSelect
+ piece={pieceModel}
+ value={field.value}
+ onChange={field.onChange}
+ disabled={props.readonly}
+ />
+ </AutoFormFieldWrapper>
+ )}
+ />
)}
{selectedAction && (
<>
diff --git a/packages/web/src/app/builder/test-step/agent-test-step/index.tsx b/packages/web/src/app/builder/test-step/agent-test-step/index.tsx
index 92e51785bd0..6b88b7d363e 100644
--- a/packages/web/src/app/builder/test-step/agent-test-step/index.tsx
+++ b/packages/web/src/app/builder/test-step/agent-test-step/index.tsx
@@ -38,7 +38,7 @@ export const AgentTestStep = ({
errorMessage,
}: AgentTestStepProps) => {
return (
- <div className="flex flex-col justify-center w-full items-start">
+ <div className="flex flex-col justify-center w-full items-start pt-3">
<Tabs defaultValue="timeline" className="w-full">
<TabsList className="w-full grid grid-cols-2">
<TabsTrigger value="timeline">{t('Timeline')}</TabsTrigger>
diff --git a/packages/web/src/app/builder/test-step/test-sample-data-viewer.tsx b/packages/web/src/app/builder/test-step/test-sample-data-viewer.tsx
index b683c1a7521..0b537c3589f 100644
--- a/packages/web/src/app/builder/test-step/test-sample-data-viewer.tsx
+++ b/packages/web/src/app/builder/test-step/test-sample-data-viewer.tsx
@@ -22,7 +22,11 @@ import { ClosePanelButton } from '../step-data/close-panel-button';
import { StepDataPanelHeader } from '../step-data/step-data-panel-header';
import { StepDataPanelViewToggle } from '../step-data/step-data-panel-view-toggle';
-import { AgentTestStep, isRunAgent } from './agent-test-step';
+import {
+ AgentTestStep,
+ defaultAgentOutput,
+ isRunAgent,
+} from './agent-test-step';
import { JsonTreeSkeleton } from './json-tree-skeleton';
import { TestButtonTooltip } from './test-step-tooltip';
@@ -145,7 +149,7 @@ export const TestSampleDataViewer = React.memo(
<TestingPreviewContent data={activeData} />
) : showAgentView ? (
<AgentTestStep
- agentResult={getAgentResult(sampleData)}
+ agentResult={getAgentResult({ sampleData, isTesting })}
errorMessage={errorMessage}
/>
) : friendlyError ? (
@@ -374,7 +378,21 @@ const TestingPreviewContent = ({ data }: TestingPreviewContentProps) => {
TestSampleDataViewer.displayName = 'TestSampleDataViewer';
//In case the user has mangled sample data
-function getAgentResult(sampleData: unknown) {
+function getAgentResult({
+ sampleData,
+ isTesting,
+}: {
+ sampleData: unknown;
+ isTesting: boolean;
+}): AgentResult | undefined {
+ const agentResult = parseAgentResult(sampleData);
+ if (isTesting && agentResult?.status !== AgentTaskStatus.IN_PROGRESS) {
+ return defaultAgentOutput;
+ }
+ return agentResult;
+}
+
+function parseAgentResult(sampleData: unknown) {
if (isNil(sampleData)) return undefined;
if (typeof sampleData !== 'object' || sampleData === null) return undefined;
if (!('status' in sampleData)) return undefined;
diff --git a/packages/web/src/app/connections/connection-select.tsx b/packages/web/src/app/connections/connection-select.tsx
new file mode 100644
index 00000000000..e68a38b6382
--- /dev/null
+++ b/packages/web/src/app/connections/connection-select.tsx
@@ -0,0 +1,373 @@
+import {
+ Permission,
+ connectionTemplate,
+ isNil,
+} from '@activepieces/core-utils';
+import {
+ PieceMetadataModel,
+ PieceMetadataModelSummary,
+} from '@activepieces/pieces-framework';
+import {
+ AppConnectionScope,
+ AppConnectionStatus,
+ AppConnectionWithoutSensitiveData,
+ PieceAudienceFilter,
+} from '@activepieces/shared';
+import { t } from 'i18next';
+import {
+ Plus,
+ Globe,
+ Key,
+ Cable,
+ Check,
+ Unplug,
+ X,
+ LucideIcon,
+} from 'lucide-react';
+import { useState } from 'react';
+
+import { CreateOrEditConnectionDialog } from '@/app/connections/create-edit-connection-dialog';
+import { PermissionNeededTooltip } from '@/components/custom/permission-needed-tooltip';
+import { SearchableSelect } from '@/components/custom/searchable-select';
+import { Button } from '@/components/ui/button';
+import {
+ Select,
+ SelectAction,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@/components/ui/tooltip';
+import {
+ appConnectionsQueries,
+ appConnectionUtils,
+} from '@/features/connections';
+import { piecesHooks } from '@/features/pieces';
+import {
+ useAuthorization,
+ useIsPlatformAdmin,
+} from '@/hooks/authorization-hooks';
+import { authenticationSession } from '@/lib/authentication-session';
+import { cn } from '@/lib/utils';
+
+export function ConnectionSelect({
+ piece,
+ value,
+ onChange,
+ disabled,
+}: ConnectionSelectProps) {
+ const [connectionDialogOpen, setConnectionDialogOpen] = useState(false);
+ const [selectConnectionOpen, setSelectConnectionOpen] = useState(false);
+ const [reconnectConnection, setReconnectConnection] =
+ useState<AppConnectionWithoutSensitiveData | null>(null);
+ //in case of reconnection we need to use the piece version from the connection
+ const { pieceModel: pieceWithCorrectVersion, isLoading: isLoadingPiece } =
+ piecesHooks.usePiece({
+ name: piece.name,
+ version: reconnectConnection?.pieceVersion ?? piece.version,
+ audience: PieceAudienceFilter.ALL,
+ });
+ const hasPermissionToCreateConnection = useAuthorization().checkAccess(
+ Permission.WRITE_APP_CONNECTION,
+ );
+ const {
+ data: connections,
+ isLoading: isLoadingConnections,
+ refetch,
+ } = appConnectionsQueries.useAppConnections({
+ request: {
+ pieceName: piece.name,
+ projectId: authenticationSession.getProjectId()!,
+ limit: 1000,
+ },
+ pieceAuth: piece.auth,
+ extraKeys: [piece.name, authenticationSession.getProjectId()!],
+ staleTime: 0,
+ });
+ const selectedConnection = connections?.data?.find(
+ (connection) =>
+ connection.externalId === connectionTemplate.unwrapExternalId(value),
+ );
+ const isSelectedConnectionGlobal =
+ selectedConnection?.scope === AppConnectionScope.PLATFORM;
+ // The create/reconnect dialog runs in global (PLATFORM) scope ONLY when
+ // reconnecting an existing global connection. Creating a brand-new connection
+ // from a project flow must default to PROJECT scope, otherwise it silently
+ // inherits the selected connection's platform scope and (for non-admins) hits
+ // the platform-admin-only global-connections endpoint (GIT-1587).
+ const isReconnectingGlobalConnection =
+ reconnectConnection?.scope === AppConnectionScope.PLATFORM;
+ const isPlatformAdmin = useIsPlatformAdmin();
+ const statusDisplay = selectedConnection
+ ? getConnectionStatusDisplay(selectedConnection.status)
+ : null;
+ const canShowConnectionStatus =
+ !!selectedConnection && (!isSelectedConnectionGlobal || isPlatformAdmin);
+ const openReconnectDialog = () => {
+ setReconnectConnection(selectedConnection ?? null);
+ setSelectConnectionOpen(false);
+ setConnectionDialogOpen(true);
+ };
+
+ if (isLoadingConnections || !pieceWithCorrectVersion) {
+ return (
+ <SearchableSelect
+ options={[]}
+ disabled={true}
+ loading={isLoadingConnections}
+ placeholder={t('Select a connection')}
+ value={value}
+ onChange={() => {}}
+ showDeselect={false}
+ showRefresh={false}
+ />
+ );
+ }
+
+ return (
+ <>
+ <CreateOrEditConnectionDialog
+ reconnectConnection={reconnectConnection}
+ isGlobalConnection={isReconnectingGlobalConnection}
+ piece={pieceWithCorrectVersion}
+ key={`CreateOrEditConnectionDialog-open-${connectionDialogOpen}`}
+ open={connectionDialogOpen}
+ setOpen={(open, connection) => {
+ setConnectionDialogOpen(open);
+ const createdValue = connectionTemplate.wrapExternalId(
+ connection?.externalId,
+ );
+ if (!isNil(createdValue)) {
+ refetch();
+ onChange(createdValue);
+ }
+ }}
+ ></CreateOrEditConnectionDialog>
+ <Select
+ key={value ?? ''}
+ open={selectConnectionOpen}
+ onOpenChange={setSelectConnectionOpen}
+ defaultValue={value}
+ onValueChange={onChange}
+ disabled={disabled}
+ >
+ <div className="relative">
+ {value && !disabled && canShowConnectionStatus && statusDisplay && (
+ <div className="z-50 absolute right-8 top-1.5 flex items-center gap-1.5 pointer-events-none">
+ <span className="flex items-center gap-1 text-xs text-gray-11 select-none pointer-events-none">
+ <statusDisplay.Icon
+ className={cn(
+ 'size-3.5 shrink-0',
+ statusDisplay.iconClassName,
+ )}
+ />
+ {statusDisplay.label}
+ </span>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex pointer-events-auto">
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ loading={isLoadingPiece}
+ onClick={(e) => {
+ e.stopPropagation();
+ openReconnectDialog();
+ }}
+ disabled={!hasPermissionToCreateConnection}
+ >
+ <Cable className="size-3.5" />
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ {!hasPermissionToCreateConnection
+ ? t('Permission needed')
+ : t('Reconnect')}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ )}
+
+ <SelectTrigger className="flex gap-2 items-center">
+ <SelectValue
+ className="truncate grow shrink"
+ placeholder={t('Select a connection')}
+ data-testid="select-connection-value"
+ >
+ <SelectedConnectionLabel
+ value={value}
+ connections={connections?.data ?? []}
+ />
+ </SelectValue>
+ <div className="grow"></div>
+ {value && !disabled && canShowConnectionStatus && statusDisplay && (
+ <span
+ aria-hidden
+ className="z-50 opacity-0 pointer-events-none flex items-center gap-1.5"
+ >
+ <span className="flex items-center gap-1 text-xs">
+ <statusDisplay.Icon className="size-3.5 shrink-0" />
+ {statusDisplay.label}
+ </span>
+ <span className="size-6 shrink-0" />
+ </span>
+ )}
+ </SelectTrigger>
+ </div>
+
+ <SelectContent>
+ <PermissionNeededTooltip
+ hasPermission={hasPermissionToCreateConnection}
+ >
+ <SelectAction
+ onClick={() => {
+ setSelectConnectionOpen(false);
+ setReconnectConnection(null);
+ setConnectionDialogOpen(true);
+ }}
+ disabled={!hasPermissionToCreateConnection}
+ >
+ <span
+ className={cn('flex items-center gap-1 text-accent-11 w-full', {
+ 'text-gray-11 cursor-not-allowed':
+ !hasPermissionToCreateConnection,
+ })}
+ >
+ <Plus size={16} />
+ {t('Create Connection')}
+ </span>
+ </SelectAction>
+ </PermissionNeededTooltip>
+
+ {connections &&
+ connections.data &&
+ connections.data?.map((connection) => {
+ const connectionValue = connectionTemplate.wrapExternalId(
+ connection.externalId,
+ );
+ if (isNil(connectionValue)) {
+ return null;
+ }
+ const accountIdentifier =
+ appConnectionUtils.getConnectionAccountIdentifier(connection);
+ const rowStatus =
+ connection.status !== AppConnectionStatus.ACTIVE
+ ? getConnectionStatusDisplay(connection.status)
+ : null;
+ return (
+ <SelectItem
+ value={connectionValue}
+ key={connection.externalId}
+ className="*:[span]:last:w-full"
+ >
+ <div className="flex items-center gap-2 w-full min-w-0">
+ {connection.usingSecretManager && (
+ <Key size={16} className="shrink-0" />
+ )}
+ {connection.scope === AppConnectionScope.PLATFORM && (
+ <Globe size={16} className="shrink-0" />
+ )}
+ <span className="truncate min-w-0">
+ {connection.displayName}
+ </span>
+ {accountIdentifier && (
+ <span className="ml-auto shrink-0 truncate max-w-[50%] text-xs text-gray-11">
+ {accountIdentifier}
+ </span>
+ )}
+ {rowStatus && (
+ <span
+ className={cn(
+ 'flex items-center gap-1 text-xs text-gray-11 shrink-0',
+ { 'ml-auto': !accountIdentifier },
+ )}
+ >
+ <rowStatus.Icon
+ className={cn(
+ 'size-3.5 shrink-0',
+ rowStatus.iconClassName,
+ )}
+ />
+ {rowStatus.label}
+ </span>
+ )}
+ </div>
+ </SelectItem>
+ );
+ })}
+ </SelectContent>
+ </Select>
+ </>
+ );
+}
+
+function SelectedConnectionLabel({
+ value,
+ connections,
+}: {
+ value: string | undefined;
+ connections: AppConnectionWithoutSensitiveData[];
+}) {
+ if (isNil(value) || value === '') {
+ return null;
+ }
+ const connection = connections.find(
+ (connection) =>
+ connection.externalId === connectionTemplate.unwrapExternalId(value),
+ );
+ if (isNil(connection)) {
+ return (
+ <div className="truncate grow shrink flex items-center gap-2 text-gray-11">
+ <Unplug size={16} className="shrink-0 text-danger-11" />
+ {t('Connection not found')}
+ </div>
+ );
+ }
+ return (
+ <div className="truncate grow shrink flex items-center gap-2">
+ {connection.scope === AppConnectionScope.PLATFORM && (
+ <Globe size={16} className="shrink-0" />
+ )}
+ {connection.displayName}
+ </div>
+ );
+}
+function getConnectionStatusDisplay(status: AppConnectionStatus): {
+ Icon: LucideIcon;
+ iconClassName: string;
+ label: string;
+} {
+ switch (status) {
+ case AppConnectionStatus.ACTIVE:
+ return {
+ Icon: Check,
+ iconClassName: 'text-success-11',
+ label: t('Connected'),
+ };
+ case AppConnectionStatus.ERROR:
+ return {
+ Icon: X,
+ iconClassName: 'text-danger-11',
+ label: t('Error'),
+ };
+ case AppConnectionStatus.MISSING:
+ return {
+ Icon: Unplug,
+ iconClassName: 'text-gray-11',
+ label: t('Missing'),
+ };
+ }
+}
+
+type ConnectionSelectProps = {
+ piece: PieceMetadataModelSummary | PieceMetadataModel;
+ value: string | undefined;
+ onChange: (value: string) => void;
+ disabled?: boolean;
+};
diff --git a/packages/web/src/features/agents/agent-tools/piece-tool-dialog/connection-select.tsx b/packages/web/src/features/agents/agent-tools/piece-tool-dialog/connection-select.tsx
deleted file mode 100644
index b7a18d022d2..00000000000
--- a/packages/web/src/features/agents/agent-tools/piece-tool-dialog/connection-select.tsx
+++ /dev/null
@@ -1,106 +0,0 @@
-import { connectionTemplate } from '@activepieces/core-utils';
-import { PieceMetadataModelSummary } from '@activepieces/pieces-framework';
-import { t } from 'i18next';
-import React, { useState } from 'react';
-
-// eslint-disable-next-line import/no-restricted-paths
-import { CreateOrEditConnectionDialog } from '@/app/connections/create-edit-connection-dialog';
-import { SearchableSelect } from '@/components/custom/searchable-select';
-import { appConnectionsQueries } from '@/features/connections/hooks/app-connections-hooks';
-import { authenticationSession } from '@/lib/authentication-session';
-
-type ConnectionDropdownProps = {
- piece: PieceMetadataModelSummary;
- value: string | null;
- onChange: (connectionExternalId: string | null) => void;
- disabled?: boolean;
- placeholder?: string;
- showError?: boolean;
-};
-
-export const ConnectionDropdown = React.memo(
- ({
- piece,
- value,
- onChange,
- disabled = false,
- showError = false,
- placeholder = t('Select a connection'),
- }: ConnectionDropdownProps) => {
- const [connectionDialogOpen, setConnectionDialogOpen] = useState(false);
-
- const {
- data: connections,
- isLoading: connectionsLoading,
- isRefetching: isRefetchingConnections,
- } = appConnectionsQueries.useAppConnections({
- request: {
- pieceName: piece?.name || '',
- projectId: authenticationSession.getProjectId()!,
- limit: 1000,
- },
- extraKeys: [piece?.name, authenticationSession.getProjectId()!],
- staleTime: 0,
- });
-
- if (!piece) {
- return null;
- }
-
- const connectionOptions =
- connections?.data?.map((connection) => ({
- label: connection.displayName,
- value: connection.externalId,
- })) ?? [];
-
- const connectionOptionsWithNewConnectionOption = [
- { label: t('+ New Connection'), value: '' },
- ...connectionOptions,
- ];
-
- const handleChange = (selectedValue: string | null) => {
- if (selectedValue) {
- onChange(selectedValue);
- } else {
- setConnectionDialogOpen(true);
- }
- };
-
- return (
- <>
- <CreateOrEditConnectionDialog
- piece={piece}
- open={connectionDialogOpen}
- setOpen={(open, connection) => {
- setConnectionDialogOpen(open);
- if (connection) {
- onChange(connection.externalId);
- }
- }}
- reconnectConnection={null}
- isGlobalConnection={false}
- />
-
- <div className="space-y-2">
- <SearchableSelect
- value={connectionTemplate.unwrapExternalId(value) ?? undefined}
- onChange={handleChange}
- options={connectionOptionsWithNewConnectionOption}
- placeholder={placeholder}
- loading={connectionsLoading || isRefetchingConnections}
- disabled={disabled}
- showDeselect={!disabled && value !== null}
- triggerClassName={showError ? 'border-danger-9' : undefined}
- />
- {showError && (
- <p className="text-sm font-medium text-danger-11 break-words">
- {t('Connection is required')}
- </p>
- )}
- </div>
- </>
- );
- },
-);
-
-ConnectionDropdown.displayName = 'ConnectionDropdown';
diff --git a/packages/web/src/features/agents/index.ts b/packages/web/src/features/agents/index.ts
index 3ee2ed618af..e9af86ad1a1 100644
--- a/packages/web/src/features/agents/index.ts
+++ b/packages/web/src/features/agents/index.ts
@@ -10,7 +10,6 @@ export { useKnowledgeBaseEmbeddingSource } from './agent-tools/knowledge-base-di
export { AgentPieceToolComponent } from './agent-tools/components/piece-tool';
export { AgentFlowToolDialog } from './agent-tools/flow-tool-dialog';
export { AgentMcpDialog } from './agent-tools/mcp-tool-dialog';
-export { ConnectionDropdown } from './agent-tools/piece-tool-dialog/connection-select';
export { PieceActionsList } from './agent-tools/piece-tool-dialog/dialog-pages/piece-actions-list';
export { PiecesList } from './agent-tools/piece-tool-dialog/dialog-pages/pieces-list';
export { usePieceToolsDialogStore } from './agent-tools/stores/pieces-tools';
diff --git a/packages/web/test/app/builder/piece-properties/dynamic-dropdown-piece-property.test.tsx b/packages/web/test/app/builder/piece-properties/dynamic-dropdown-piece-property.test.tsx
index 6b44fd9a171..c04335a9ada 100644
--- a/packages/web/test/app/builder/piece-properties/dynamic-dropdown-piece-property.test.tsx
+++ b/packages/web/test/app/builder/piece-properties/dynamic-dropdown-piece-property.test.tsx
@@ -24,7 +24,7 @@ vi.mock('@/lib/authentication-session', () => ({
}));
vi.mock('@/app/builder/builder-hooks', () => ({
- useBuilderStateContext: (
+ useOptionalBuilderStateContext: (
selector: (state: Record<string, unknown>) => unknown,
) =>
selector({
diff --git a/packages/web/test/app/builder/piece-properties/dynamic-piece-property.test.tsx b/packages/web/test/app/builder/piece-properties/dynamic-piece-property.test.tsx
index 61572c3e2fc..436951eab03 100644
--- a/packages/web/test/app/builder/piece-properties/dynamic-piece-property.test.tsx
+++ b/packages/web/test/app/builder/piece-properties/dynamic-piece-property.test.tsx
@@ -23,7 +23,7 @@ vi.mock('@/lib/authentication-session', () => ({
}));
vi.mock('@/app/builder/builder-hooks', () => ({
- useBuilderStateContext: (
+ useOptionalBuilderStateContext: (
selector: (state: Record<string, unknown>) => unknown,
) =>
selector({